-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathmisc.js
920 lines (775 loc) · 38 KB
/
misc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
'use strict';
/**
* This is a bot that looks up different fast foods based on user requests and returns the caloric amount
*/
// variables that contain lookup information including restaurant name and calories by food
var foodChoices = require("data/foods.json");
var restaurants = require("data/restaurants.json");
var chickenChoices = require("data/chicken.json");
var subOfDay = require("data/specials.json");
var healthyOptions = require("data/healthy.json");
const dietExamples = [
"Skipping a single 20oz Coke or Pepsi at any restaurant eliminates 250 calories.",
"Drinking a 12oz Mountain Dew versus a large 32oz Mountain Dew reduces your calorie intake by 240 calories.",
"Drinking a water versus a 20oz Lemonade eliminates 250 calories.",
"Skipping the mayonnaise on a Footlong Subway sandwich eliminates 220 calories.",
"Not adding guacamole to a Burrito at Chipotle eliminates 230 calories.",
"Going without rice or cheese in a Burrito Bowl at Chipotle eliminates 320 calories.",
"Having a Grilled Chicken Sandwich versus a Crispy Chicken Sandwich at Burger King reduces calories by 200.",
"Eating a Small Chicken Noodle Soup rather than a Large Waffle Fries at Chick-fil-A saves you 320 calories.",
"Eating a Egg White Delight McMuffin for breakfast rather than a Sausage and Egg McMuffin reduces your calorie count by 210.",
"Having a Single rather than a Double at Wendy's reduces your calories by 240.",
"Eating a Fresco Chicken Burrito instead of a Double Chalupa at Taco Bell saves 240 calories.",
"Eating a Small French Fries at Hardees rather than a Large French Fries saves 230 calories.",
"Eating a Regular Fries rather than a Large Fries at Five Guys saves 361 calories.",
"Having your Orange Chicken on Mixed Vegetables rather than White Rice saves 300 calories.",
"Eating a side order of Hushpuppies at Cookout rather than a full order saves 300 calories."
];
// --------------- Helpers that build all of the responses -----------------------
function buttonResponse(sessionAttributes, message, buttonData) {
console.log("processing:" + JSON.stringify(buttonData));
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState: 'Fulfilled',
message: { contentType: 'PlainText', content: message },
responseCard: {
version: '1',
contentType: 'application/vnd.amazonaws.card.generic',
genericAttachments: [
{
title: 'Options:',
subTitle: 'Click button below or type response.',
buttons: buttonData,
},
],
},
},
};
}
function elicitSlot(sessionAttributes, intentName, slots, slotToElicit, message) {
return {
sessionAttributes,
dialogAction: {
type: 'ElicitSlot',
intentName,
slots,
slotToElicit,
message,
},
};
}
function buttonSlot(sessionAttributes, intentName, slots, slotToElicit, messageContent, buttonData) {
console.log("processing:" + JSON.stringify(buttonData));
return {
sessionAttributes,
dialogAction: {
type: 'ElicitSlot',
intentName,
slots,
slotToElicit,
message: { contentType: 'PlainText', content: messageContent },
responseCard: {
version: '1',
contentType: 'application/vnd.amazonaws.card.generic',
genericAttachments: [
{
title: 'Options:',
subTitle: 'Click button below or type response.',
buttons: buttonData,
},
],
},
},
};
}
function confirmIntent(sessionAttributes, intentName, slots, message) {
return {
sessionAttributes,
dialogAction: {
type: 'ConfirmIntent',
intentName,
slots,
message,
},
};
}
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}
function delegate(sessionAttributes, slots) {
return {
sessionAttributes,
dialogAction: {
type: 'Delegate',
slots,
},
};
}
// ---------------- Helper Functions --------------------------------------------------
function buildValidationResult(isValid, violatedSlot, messageContent) {
return {
isValid,
violatedSlot,
message: { contentType: 'PlainText', content: messageContent },
};
}
// this function is what builds the introduction
function getIntroduction(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
const slots = intentRequest.currentIntent.slots;
var message = "Hello, my name is Chuck. I am a chatbot that is an expert at fast food. " +
"To get started, ask me something like 'How many calories in a Chicken Sandwich'.";
// these are default buttons that show up to the user
var buttonData = [];
buttonData.push({ "text":"Calories in Big Mac", "value":"Calories in a Big Mac" });
buttonData.push({ "text":"Eating a pizza", "value":"Eating a pizza" });
buttonData.push({ "text":"Sub of the Day", "value":"Sub of the day" });
callback(buttonResponse(sessionAttributes, message, buttonData));
}
// this function is what retrieves the restaurants that data is available for
function getRestaurants(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var buttonData = [];
var counterResponse = "Okay, here are the fast food restaurants that I have " +
"info on. ";
// cycle through all of the restaurant names that are listed as valid
for (var i = 0; i < restaurants.length; i++) {
if (restaurants[i].validRestaurant) {
counterResponse = counterResponse + restaurants[i].restaurantName + ", ";
}
if (i < 3) {
buttonData.push({ "text":restaurants[i].restaurantName, "value":restaurants[i].restaurantName });
}
}
counterResponse = counterResponse + "Say something like, 'Eating at McDonalds', to begin.";
callback(buttonResponse(sessionAttributes, counterResponse, buttonData));
}
// this function calculates how much a given meal covers for daily calories
function getBasicDailyAnalysis(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
const maleAverage = 2500;
const femaleAverage = 2000;
const sodiumIntake = 2300;
var buttonData = [];
// change response depending on if a prior food calculation was saved in the session
if (intentRequest.sessionAttributes.totalCalories) {
const mealEstimate = sessionAttributes.totalCalories;
const restaurantName = intentRequest.sessionAttributes.restaurantName;
var botResponse = "This meal of " + mealEstimate + " calories at " + restaurantName +
" is " + ((mealEstimate * 100) /maleAverage) + "% of a daily average male diet, or " +
((mealEstimate * 100) /femaleAverage) + "% of a daily average female diet based on " +
"guidelines set by nutrition experts. ";
if (intentRequest.sessionAttributes.chineseRestaurant) {
const sodiumEstimate = intentRequest.sessionAttributes.totalSodium;
botResponse = botResponse + "The American Heart Association recommends no more than " +
sodiumIntake + " mg of sodium per day, and this meal is " +
Math.round((sodiumEstimate * 100) /sodiumIntake) + "% of the daily amount.";
}
buttonData.push({ "text":"Customize for me", "value":"customize" });
callback(buttonResponse(sessionAttributes, botResponse, buttonData));
} else {
var defaultResponse = "An average daily diet requires " + maleAverage + " calories " +
" for a male, and " + femaleAverage + " for a female. For how this compares to a " +
"fast food meal, please describe what you would eat. Start with something like below.";
buttonData.push({ "text":"Eating at McDonalds", "value":"eating at McDonalds" });
callback(buttonResponse(sessionAttributes, defaultResponse, buttonData));
}
}
// this function is what builds the wrap-up of a conversation
function endConversation(intentRequest, callback) {
// note: this intent resets the session data
const sessionAttributes = {};
var counterResponse = 'Thanks for stoping by. I get off work at 5pm... on June 14, 2035! ';
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function is what builds the response to a deez nuts comment
function replyDeezNuts(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "LOL - well I'm not really trying to mess with them ;)";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function reacts to someone asking for a beer
function beerReply(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "Beer. Delicious beer. Sorry, I don't know about how many calories in it.";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function is used to give away prizes for contests
function drawingReply(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "Thanks for getting back to us. We will respond shortly.";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function reacts to someone paying a complement
function replyComplement(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "Awww - you're too kind!";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function reacts to someone being harsh or critical
function replyCritic(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "Sorry, I'm trying my best and will learn from my mistakes!";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function reacts to someone indicating that they will come back
function replyComingBack(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "Okay I.will.be.right.here! :)";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function reacts to someone indicating that they want a new restaurant
function resetRestaurant(intentRequest, callback) {
const sessionAttributes = {};
var buttonData = [];
var counterResponse = "Got it. Which restaurant are you at now?";
// provide a button to easily list restaurants
buttonData.push({ "text":"List Restaurants", "value":"List restaurants" });
callback(buttonResponse(sessionAttributes, counterResponse, buttonData));
}
// this function reacts to a pause in the conversation
function replyNextTopic(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "What's next? ";
if (sessionAttributes.restaurantName) {
counterResponse = counterResponse + "I assume you are still at " +
sessionAttributes.restaurantName + ".";
} else {
counterResponse = counterResponse + "Interested in getting a pizza?";
}
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function is what builds the response to a request for what the bots name is
function getBotName(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var botResponse = "My name is Chuck. I'm a chatbot that helps people sort out " +
"fast food options. Talking about food all day makes me hungry!!!";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: botResponse }));
}
// this function is what builds the response to a request for help
function getHelp(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "I'm Chuck, a chatbot that helps out on questions around " +
"Fast Food, including how many calories are in different meals. " +
"To get started, just ask me a question like 'How many calories in a Big Mac?', " +
"or 'Eating one slice of Pepperoni Pizza'. I will ask a few additional " +
"questions and tell you what I know. For the latest list of fast food " +
"restaurants I know about, just say 'List of restaurants.'";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function retrieves the Subway sub of the day
function getSubOfDay(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var subName = "Default";
// get today's day of week
var d = new Date();
var n = d.getDay();
// go through array and depending on user request, find appropriate sub
for (var i = 0; i < subOfDay.length ; i++) {
const dayRequest = intentRequest.currentIntent.slots.DayOfWeek.toLowerCase();
if (dayRequest === "today") {
if (n === subOfDay[i].todayNum) {
subName = subOfDay[i].subName;
}
} else if (dayRequest === "tomorrow") {
if (n === subOfDay[i].tomorrowNum) {
subName = subOfDay[i].subName;
}
} else {
if (dayRequest === subOfDay[i].weekday.toLowerCase()) {
subName = subOfDay[i].subName;
}
}
}
// formulate response
var counterResponse = "The Subway Sub of the Day for " +
intentRequest.currentIntent.slots.DayOfWeek +
" is " + subName + ". " +
"Would you like nutritional details?";
// add buttons
var buttonData = [];
buttonData.push({ "text":"6 Inch Sub", "value":"How many calories in a 6 inch " + subName + " at Subway" });
buttonData.push({ "text":"Footlong Sub", "value":"How many calories in a footlong " + subName + " at Subway" });
callback(buttonResponse(sessionAttributes, counterResponse, buttonData));
}
// this function is to solicit interest in weight loss tips
function getWeightLossTips(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
const dci = intentRequest.sessionAttributes.dci;
const goal = 250;
var counterResponse = "How much you weigh depends on your calorie consumption, " +
"versus what your body uses. For example, consuming just " + goal + " calories less " +
"than you use each day loses a pound of fat every other week. ";
if (dci) {
counterResponse = counterResponse + "For you, that would be consuming " + (dci-goal) +
" calories each day, or " + Math.round((dci-goal)/3) + " per meal.";
}
// add a button to offer health advice
var buttonData = [];
buttonData.push({ "text":"Diet Food Idea", "value":"What's a good diet food" });
buttonData.push({ "text":"How to Adjust", "value":"another calorie reduction example" });
callback(buttonResponse(sessionAttributes, counterResponse, buttonData));
}
// this function is what calculates the BMR for a given user
function calculateBMR(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
const gender = intentRequest.currentIntent.slots.Gender;
const age = intentRequest.currentIntent.slots.Age;
const heightFeet = intentRequest.currentIntent.slots.HeightFeet;
const heightInches = intentRequest.currentIntent.slots.HeightInches;
const weightUnits = intentRequest.currentIntent.slots.WeightUnits;
const weight = intentRequest.currentIntent.slots.Weight;
var counterResponse = "Daily calorie intake for a " + age + " year old " + gender + ", weighing " +
weight + " lbs, and is " + heightFeet + " ft " + heightInches + " inches tall is ";
var bmr = 0;
if (gender.toLowerCase() === "male") {
// This is the male BMR calculation
bmr = 66 + ( 6.2 * Number(weight)) + ( 12.7 * Number(heightFeet) * 12 ) + ( -6.76 * Number(age));
if (intentRequest.currentIntent.slots.HeightInches) {
if (heightInches !== "?") {
bmr = bmr + 12.7 * Number(heightInches);
}
}
} else {
// This is the female BMR calculation
bmr = 655.1 + (4.35 * Number(weight)) + (4.7 * Number(heightFeet) * 12 ) + (- 4.7 * Number(age));
if (intentRequest.currentIntent.slots.HeightInches) {
if (heightInches !== "?") {
bmr = bmr + 4.7 * Number(heightInches);
}
}
}
var dci = Math.round(bmr * 1.2);
counterResponse = counterResponse + dci + " calories per day, or " + Math.round(dci/3) +
" calories per meal. " +
"This amount will increase if you are active at work or exercise on a regular basis. ";
// add a button to offer health advice
var buttonData = [];
buttonData.push({ "text":"Weight loss tips", "value":"Weight loss tips" });
// save the daily caloric intake for later in session
sessionAttributes.dci = dci;
callback(buttonResponse(sessionAttributes, counterResponse, buttonData));
}
// this function is what builds the response to a shock message (i.e. wow)
function getShockResponse(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var counterResponse = "Well it could be worse, at least you haven't eaten this " +
"meal yet...right? oh sorry :)";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
}
// this function returns what healthy options exist at a particular restaurant
function getHealthyChoice(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var buttonData = [];
const restaurant = intentRequest.currentIntent.slots.Restaurant;
var counterResponse = restaurant + " has ";
if (restaurant === "Subway") {
counterResponse = counterResponse + "healthy salads and sandwiches.";
} else if (restaurant === "McDonalds") {
counterResponse = counterResponse + "grilled chicken sandwiches and salads.";
} else if (restaurant === "Panera") {
counterResponse = counterResponse + "healthy soups, salads, and sandwiches.";
} else if (restaurant === "Burger King") {
counterResponse = counterResponse + "a nice grilled chicken sandwich.";
} else if (restaurant === "Cookout") {
counterResponse = counterResponse + "char-grilled chicken breast sandwiches. Just stay away from their fancy milkshakes.";
} else if (restaurant === "Chick-fil-A") {
counterResponse = counterResponse + "grilled chicken sandwiches and salads.";
} else if (restaurant === "Wendys") {
counterResponse = counterResponse + "chicken sandwiches and a healthy fish sandwich.";
} else if (restaurant === "Arbys") {
counterResponse = counterResponse + "roast beef and turkey sandwiches as well as salads.";
} else if (restaurant === "Hardees") {
counterResponse = counterResponse + "charbroiled chicken and veggie sandwiches.";
} else if (restaurant === "Five Guys") {
counterResponse = counterResponse + "veggie sandwiches, and little size burgers. Just stay away from the fries.";
} else if (restaurant === "Sonic") {
counterResponse = counterResponse + "veggie burgers.";
} else if (restaurant === "Taco Bell") {
counterResponse = counterResponse + "fresco style preparation of many items with no cheese or sour cream. Just watch how many you eat!";
} else if (restaurant === "Panda Express") {
counterResponse = counterResponse + "the option of putting the entree onto vegetables rather than rice.";
} else if (restaurant === "Chipotle") {
counterResponse = counterResponse + "bowls. The tortilla on a burrito has 300 calories. Also skip the chips and guac.";
}
// this adds a button giving a meal option under 500 calories for that restaurant
const buttonValue = "What items are at " + restaurant + " under 500 calories.";
buttonData.push({"text":"Example Meal", "value":buttonValue});
counterResponse = counterResponse + " Let me know if I can recommend a meal for you.";
callback(buttonResponse(sessionAttributes, counterResponse, buttonData));
}
// this function returns an idea around reducing calories a slight amount (200-300 calories)
function getCalorieReductionIdea(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var buttonData = [];
const exampleNum = Math.floor(Math.random() * dietExamples.length);
var counterResponse = "Here is an example of a small change to make once a day. " + dietExamples[exampleNum];
// add buttons to provide options
buttonData.push({ "text":"Another Example", "value":"another calorie reduction example"});
buttonData.push({ "text":"Diet Food Idea", "value":"What's a good diet food" });
callback(buttonResponse(sessionAttributes, counterResponse, buttonData))
}
// this function returns a meal recommendation based on certain calorie thresholds for a given restaurant
function getLowCalorieOption(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var restaurantName = intentRequest.currentIntent.slots.Restaurant;
const calorieLimit = intentRequest.currentIntent.slots.QtyCalories;
const foodType = intentRequest.currentIntent.slots.FoodType;
var buttonData = [];
var validRestaurant = false;
// check if the restaurant name hasn't been entered, but there's one in the session data - default for user
if (!restaurantName && sessionAttributes.restaurantName) {
restaurantName = sessionAttributes.restaurantName;
intentRequest.currentIntent.slots.Restaurant = sessionAttributes.restaurantName;
}
// validate restaurant choice - right now this is limited
if (restaurantName) {
if (restaurantName.toLowerCase() === "mcdonalds" ||
restaurantName.toLowerCase() === "subway" ||
restaurantName.toLowerCase() === "chipotle" ||
restaurantName.toLowerCase() === "chick-fil-a" ||
restaurantName.toLowerCase() === "taco bell" ||
restaurantName.toLowerCase() === "panda express" ||
restaurantName.toLowerCase() === "burger king") {
validRestaurant = true;
} else {
console.log("no low calorie options for " + restaurantName);
}
}
var counterResponse = "At " + restaurantName + ", you can get ";
const mealOptions = getHealthyOptions(restaurantName, calorieLimit).mealOptions;
console.log("Get Low Calorie Options " + JSON.stringify(mealOptions));
console.log("Session Attributes: " + JSON.stringify(intentRequest.sessionAttributes));
// check if the request is a fulfillment or validation and respond accordingly
if (intentRequest.invocationSource === 'FulfillmentCodeHook') {
// match the food category with the options
var i = 0;
for (var k = 0; k < mealOptions.length; k++) {
if (mealOptions[k].category.toLowerCase() === foodType.toLowerCase()) {
i = k;
}
}
counterResponse = counterResponse + mealOptions[i].order + " for " + mealOptions[i].calories + " calories.";
// save session data to continue dialog
sessionAttributes.restaurantName = restaurantName;
sessionAttributes.foodType = foodType;
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: counterResponse }));
} else {
// if there isn't a food type, prompt with buttons for the restaurant
if (validRestaurant && !foodType && !intentRequest.currentIntent.slots.Drink) {
const prompt = "Which type of meal?";
console.log("building prompt for food type options");
for (var i = 0; i < mealOptions.length; i++) {
buttonData.push( { "text":mealOptions[i].category, "value":mealOptions[i].category });
}
const foodTypePrompt = buildValidationResult(false, 'FoodType', prompt);
callback(buttonSlot(sessionAttributes, intentRequest.currentIntent.name,
intentRequest.currentIntent.slots, foodTypePrompt.violatedSlot, prompt, buttonData));
} else if (!validRestaurant) {
// if the request isn't for a restaurant that has recommendations, offer alternatives
console.log("no recommendations for restaurant");
var prompt = "Sorry, I don't have any recommendations for ";
if (!restaurantName) {
prompt = "Here are some restaurants that I have meal ideas for.";
} else {
prompt = prompt + restaurantName + ".";
}
const restaurantPrompt = buildValidationResult(false, 'Restaurant', prompt);
buttonData.push({"text":"McDonalds", "value":"McDonalds"});
buttonData.push({"text":"Subway", "value":"Subway"});
buttonData.push({"text":"Chick-fil-A", "value":"Chick-fil-A"});
callback(buttonSlot(sessionAttributes, intentRequest.currentIntent.name,
intentRequest.currentIntent.slots, restaurantPrompt.violatedSlot, prompt, buttonData));
} else if (intentRequest.currentIntent.slots.Drink) {
// user is complaining about not liking the drink
const drinkMessage = "That's okay, you can always have water. " +
"The key point is to not drink too many calories with your meal.";
callback(close(sessionAttributes, 'Fulfilled', { contentType: 'PlainText', content: drinkMessage }));
} else {
// let Lex framework handle validation prompts
console.log("continue validation");
callback(delegate(sessionAttributes, intentRequest.currentIntent.slots));
}
}
}
// this function determines what the food type options are for a given restaurant
function getHealthyOptions(restaurantName, calorieLimit) {
console.log("Healthy Options Lookup for " + restaurantName + ".");
var mealOptions = [];
if (restaurantName) {
// go through array and find the options for the given restaurant
for (var i = 0; i < healthyOptions.length; i++) {
if (healthyOptions[i].restaurant.toLowerCase() === restaurantName.toLowerCase()) {
mealOptions = healthyOptions[i].mealOptions[0].options;
console.log("found match : " + JSON.stringify(mealOptions));
}
}
}
// if there was no match for the restaurant, default to the first one
if (!mealOptions) {
mealOptions = healthyOptions[0].mealOptions[0].options;
console.log("Defaulting to meal options at " + healthyOptions[0].restaurant + ".");
}
return {
mealOptions
};
}
// this function returns the details of a recent meal request stored in session data
function getMealDetails(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var detailResponse = "";
var buttonData = [];
console.log("Session Attributes: " + JSON.stringify(intentRequest.sessionAttributes));
if (sessionAttributes.foodName || sessionAttributes.extraName) {
if (sessionAttributes.foodName) {
detailResponse = sessionAttributes.foodName + " is " +
sessionAttributes.foodCalories + " calories";
if (sessionAttributes.foodAdjustment) {
detailResponse = detailResponse + ", but " + sessionAttributes.foodAdjustment;
if (Number(sessionAttributes.foodAdjCalories) > 0) {
detailResponse = detailResponse + " adds " + (Number(sessionAttributes.foodAdjCalories))
+ " calories. ";
} else {
detailResponse = detailResponse + " removes " +
(-1 * Number(sessionAttributes.foodAdjCalories)) + " calories. ";
}
} else {
detailResponse = detailResponse + ". ";
}
}
if (sessionAttributes.sauceName) {
detailResponse = detailResponse + sessionAttributes.sauceName + " is " +
sessionAttributes.sauceCalories + " calories. ";
}
if (sessionAttributes.extraName && !sessionAttributes.dressingName) {
detailResponse = detailResponse + sessionAttributes.extraName + " is " +
sessionAttributes.extraCalories + " calories. ";
}
if (sessionAttributes.dressingName) {
detailResponse = detailResponse + sessionAttributes.extraName + " is " +
sessionAttributes.extraCalories + " calories and the " + sessionAttributes.dressingName +
" Dressing adds " + sessionAttributes.dressingCalories + " calories. ";
}
if (sessionAttributes.drinkName) {
detailResponse = detailResponse + sessionAttributes.drinkName + " is " +
sessionAttributes.drinkCalories + " calories. ";
}
if (sessionAttributes.extraName || sessionAttributes.drinkName || sessionAttributes.sauceName) {
detailResponse = detailResponse + "Total Calories are " +
sessionAttributes.totalCalories + ". ";
}
buttonData.push({ "text":"Analyze my Meal", "value":"analyze my meal" });
buttonData.push({ "text":"Different Meal", "value":"Eating at " + sessionAttributes.restaurantName });
buttonData.push({ "text":"New Restaurant", "value":"New restaurant" });
} else if (sessionAttributes.chineseRestaurant) {
detailResponse = sessionAttributes.entreeName + " is " + sessionAttributes.entreeCalories +
" calories, and " + sessionAttributes.entreeSodium + " mg of sodium. " +
sessionAttributes.sideName + " is " + sessionAttributes.sideCalories +
" calories, and " + sessionAttributes.sideSodium + " mg of sodium. ";
if (sessionAttributes.appetizerCalories) {
detailResponse = detailResponse + sessionAttributes.appetizerName + " is " +
sessionAttributes.appetizerCalories +
" calories, and " + sessionAttributes.appetizerSodium + " mg of sodium. ";
}
if (sessionAttributes.drinkName) {
if (sessionAttributes.drinkSize) {
detailResponse = detailResponse + "The " + sessionAttributes.drinkSize + " oz. " +
sessionAttributes.drinkName + " adds " + sessionAttributes.drinkCalories + " calories. ";
} else {
detailResponse = detailResponse + "The " + sessionAttributes.drinkName + " adds " +
sessionAttributes.drinkCalories + " calories. ";
}
}
detailResponse = detailResponse + "Total Calories are " + sessionAttributes.totalCalories +
" and sodium intake is " + sessionAttributes.totalSodium + ".";
buttonData.push({ "text":"Analyze my Meal", "value":"analyze my meal" });
} else {
var detailResponse = "Sorry, first start by telling me more about the meal. ";
"For example, pick an option below";
buttonData.push({ "text":"Eating at Burger King", "value":"Eating at Burger King" });
buttonData.push({ "text":"Soups at Panera", "value":"Soups at Panera" });
buttonData.push({ "text":"Large Cheese Pizza", "value":"large cheese pizza" });
}
callback(buttonResponse(sessionAttributes, detailResponse, buttonData));
}
// this function retrieves the food options for a given restaurant
function getFoodOptions(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes || {};
var buttonData = [];
var restaurant = intentRequest.currentIntent.slots.Restaurant;
var foodType = intentRequest.currentIntent.slots.FoodType;
var botResponse = "Here are the types of " + foodType + " at " + restaurant + ". ";
console.log("Attempting to retrieve types of " + foodType + " at " + restaurant + ".");
var foodItems = [];
// find the restaurant food items for the restaurant provided
if (restaurant.toLowerCase() === "kfc") {
foodItems = chickenChoices[0].foodItems;
restaurant = "KFC";
} else {
for (var i = 0; i < foodChoices.length; i++) {
if (restaurant.toLowerCase() === foodChoices[i].restaurant.toLowerCase()) {
foodItems = foodChoices[i].foodItems;
restaurant = foodChoices[i].restaurant;
}
}
}
// go through the food items, and list those matching the food type
var foodTypeMatch = false;
var foodExamples = [];
for (var j = 0; j < foodItems.length; j++) {
// first make sure a food type exists for the item
if (foodItems[j].foodType) {
if (foodItems[j].foodType.toLowerCase() === foodType.toLowerCase()) {
botResponse = botResponse + foodItems[j].foodName + ", ";
foodExamples.push(foodItems[j].foodName);
foodTypeMatch = true;
}
}
}
// if there are matches for the food type provided - give meaningful message
if (foodTypeMatch) {
botResponse = botResponse + " Want calorie details? Say something like " +
"How many calories in a " + foodExamples[(foodExamples.length-1)] + " at " + restaurant + ".";
// find out how many buttons exist for the food example
var buttonLength = 3;
if (foodExamples.length < 3) {
buttonLength = foodExamples.length;
}
for (var k = 0; k < buttonLength; k++) {
var buttonRequest = "How many calories in a " + foodExamples[k] + " at " + restaurant;
buttonData.push({ "text":foodExamples[k], "value":buttonRequest });
}
callback(buttonResponse(sessionAttributes, botResponse, buttonData));
} else {
botResponse = "Sorry, I don't have information for types of " + foodType + " at " +
restaurant + ".";
callback(close(sessionAttributes, 'Fulfilled',
{ contentType: 'PlainText', content: botResponse }))
}
}
// --------------- Intents -----------------------
/**
* Called when the user specifies an intent for this skill.
*/
function dispatch(intentRequest, callback) {
// console.log(JSON.stringify(intentRequest, null, 2));
console.log(`dispatch userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
const intentName = intentRequest.currentIntent.name;
console.log("Data Provided: " + JSON.stringify(intentRequest));
// Dispatch to the skill's intent handlers
if (intentName === 'Introduction') {
console.log("friendly introduction.");
return getIntroduction(intentRequest, callback);
} else if (intentName === 'WhichRestaurants') {
console.log("list of restaurants requested.");
return getRestaurants(intentRequest, callback);
} else if (intentName === 'EndConversation') {
console.log("wrap-up conversation requested.");
return endConversation(intentRequest, callback);
} else if (intentName === 'Thanks') {
console.log("received thank you from user.");
return endConversation(intentRequest, callback);
} else if (intentName === 'HelpRequest') {
console.log("user requested help.");
return getHelp(intentRequest, callback);
} else if (intentName === 'MoreDetails') {
console.log("user requested details on meal");
return getMealDetails(intentRequest, callback);
} else if (intentName === 'Shock') {
console.log("user uttered a shock response");
return getShockResponse(intentRequest, callback);
} else if (intentName === 'FoodTypeOptions') {
console.log("user requested food types");
return getFoodOptions(intentRequest, callback);
} else if (intentName === 'DailyIntakeAnalysis') {
console.log("user requested daily intake summary");
return getBasicDailyAnalysis(intentRequest, callback);
} else if (intentName === 'MyName') {
console.log("user requested bot name");
return getBotName(intentRequest, callback);
} else if (intentName === 'Complement') {
console.log("user provided a complement");
return replyComplement(intentRequest, callback);
} else if (intentName === 'DeezNuts') {
console.log("user played a joke on the bot");
return replyDeezNuts(intentRequest, callback);
} else if (intentName === 'Critic') {
console.log("user was harsh");
return replyCritic(intentRequest, callback);
} else if (intentName === 'ComingBack') {
console.log("user said they will come back");
return replyComingBack(intentRequest, callback);
} else if (intentName === 'NextTopic') {
console.log("user indicated a pause in the conversation");
return replyNextTopic(intentRequest, callback);
} else if (intentName === 'NewRestaurant') {
console.log("user wants to reset the restaurant that is saved");
return resetRestaurant(intentRequest, callback);
} else if (intentName === 'CalculateBMR') {
console.log("user wants to know their BMR");
return calculateBMR(intentRequest, callback);
} else if (intentName === 'Beer') {
console.log("user asks about beer");
return beerReply(intentRequest, callback);
} else if (intentName === 'DrawingWinner') {
console.log("user replying to drawing");
return drawingReply(intentRequest, callback);
} else if (intentName === 'HealthyChoice') {
console.log("user requesting healthy choice meals");
return getHealthyChoice(intentRequest, callback);
} else if (intentName === 'WeightLossTips') {
console.log("weight loss tip request");
getWeightLossTips(intentRequest, callback);
} else if (intentName === 'LowCalorieMeals') {
console.log("low calorie meal request");
getLowCalorieOption(intentRequest, callback);
} else if (intentName === 'SubOfTheDay') {
console.log("request sub of the day");
getSubOfDay(intentRequest, callback);
} else if (intentName === 'DietCalorieExample') {
console.log("request example of 250 calories");
getCalorieReductionIdea(intentRequest, callback);
}
throw new Error(`Intent with name ${intentName} not supported`);
}
// --------------- Main handler -----------------------
function loggingCallback(response, originalCallback) {
// console.log(JSON.stringify(response, null, 2));
originalCallback(null, response);
}
// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
exports.handler = (event, context, callback) => {
try {
// By default, treat the user request as coming from the America/New_York time zone.
process.env.TZ = 'America/New_York';
console.log(`event.bot.name=${event.bot.name}`);
if (event.bot.name != 'FastFoodChecker') {
console.log('Invalid Bot Name');
}
dispatch(event, (response) => loggingCallback(response, callback));
} catch (err) {
callback(err);
}
};