-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
1149 lines (1072 loc) · 45.4 KB
/
index.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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const Alexa = require('alexa-sdk');
//======================================================================================
// Variables
//======================================================================================
//Replace with your app ID (OPTIONAL). You can find this value at the top of your skill's page on http://developer.amazon.com.
//Make sure to enclose your value in quotes, like this: var APP_ID = "amzn1.ask.skill.bb4045e6-b3e8-4133-b650-72923c5980f1";
const APP_ID = undefined;
// Threshold of the max wrong answers
// If there are more wrong answers than the threshold the call a doctor
const EMERGENCY_QUESTION_THRESHOLD = 3;
const EMERGENCY_SELECT_THRESHOLD = 2;
const EMERGENCY_DESCRIBE_THRESHOLD = 2;
const EMERGENCY_UNDERSTANDING_THRESHOLD = 3;
// How many questions of the questionnaire should be asked
const MAX_QUESTIONS = 2;//8;
// How many image select questions should be asked
const MAX_SELECT_QUESTIONS = 2;//;
// How many image describe questions should be asked
const MAX_DESCRIBE_QUESTIONS = 4;//;
// Answers if the answer was right or wrong
const speechConsCorrect = ["Ok", "Vielen Dank", "Verstanden"];
const speechConsWrong = ["Ok", "Vielen Dank", "Verstanden"];
// This is the welcome message for when a user starts the skill without a specific intent.
const WELCOME_MESSAGE = "Herzlich Willkommen bei Apoplex! <break time=\"300ms\"/> " +
"Sagen Sie Start um den Test zu beginnen.";
// This is the message a user will hear when they start a quiz.
const START_QUIZ_MESSAGE = 'OK. Ich werde Ihnen nun einige Fragen stellen.' +
'Bitte beantworten Sie diese mit Ja oder Nein. <break time=\"1s\"/>';
// This is the message a user will hear when they are in the select section of the skill
const START_QUIZ_SELECT_MESSAGE = 'Ich werde Ihnen nun einige Bilder zeigen und jeweils eine Frage dazu stellen.' +
'Bitte drücken Sie dann auf das passende Bild.<break time=\"1s\"/>';
// This is the message a user will hear when they are in the describe section of the skill
const START_QUIZ_DESCRIBE_MESSAGE = 'Ich werde Ihnen nun jeweils ein Bild zeigen.<break time=\"0.5s\"/>';
// The user will hear the emergency understanding message if they have said not yes or no
const EMERGENCY_UNDERSTANDING_MESSAGE = "Es scheint so als ob Ich Sie nicht verstehen kann." +
"Dies könnte an einer Beeinträchtigung Ihrer Ausdrucksfähigkeit liegen. Bitte kontaktieren Sie umgehend einen Arzt!";
// This is the message a user will hear when they try to cancel or stop the skill, or when they finish a quiz.
const EXIT_SKILL_MESSAGE = "Vielen Dank für die Verwendung von Apoplex";
// This is the message a user will hear after they ask (and hear) about a specific data element.
// const REPROMPT_SPEECH = "Können Sie das bitte wiederholen?";
// This is the message a user will hear when they ask Alexa for help in your skill.
const HELP_MESSAGE = "Sagen Sie Start um den Test zu beginnen.";
// These next four values are for the Alexa cards that are created when a user asks about one of the data elements.
// This only happens outside of a quiz.
// If you don't want to use cards in your skill, set the USE_IMAGES_FLAG to false.
// If you set it to true, you will need an image for each
//item in your data.
const USE_IMAGES_FLAG = true;
const IMAGE_FALLBACK = "https://s3.eu-central-1.amazonaws.com/apoplex/start.jpg";
//======================================================================================
// EXTERNAL QUESTIONS
//======================================================================================
//======================================================================================
// Questions
//======================================================================================
const questions = require("./questions/questions-questionnaire.json").questions;
//======================================================================================
// Select Questions
//======================================================================================
const selectQuestions = require("./questions/questions-select.json").questions;
//======================================================================================
// Describe Image
//======================================================================================
const describeQuestions = require("./questions/questions-describe.json").questions;
//======================================================================================
// The skill
//======================================================================================
let counter = 0;
// The different stats of the skill
const states = {
START: "_START",
QUIZ: "_QUIZ",
DESCRIBEQUIZ: "_DESCRIBEQUIZ",
SELECTQUIZ: "_SELECTQUIZ",
};
// The default handlers
const handlers = {
"LaunchRequest": function () {
this.handler.state = states.START;
this.emitWithState("Start");
},
"QuizIntent": function () {
this.handler.state = states.QUIZ;
this.emitWithState("Quiz");
},
"AnswerIntent": function () {
this.handler.state = states.START;
this.emitWithState("AnswerIntent");
},
"AMAZON.HelpIntent": function () {
this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
},
"Unhandled": function () {
this.handler.state = states.START;
this.emitWithState("Start");
},
"AMAZON.PreviousIntent": function () {
this.handler.state = states.START;
this.emitWithState("Start");
},
"AMAZON.NextIntent": function () {
this.handler.state = states.START;
this.emitWithState("Start");
}
};
// The initial handlers
const startHandlers = Alexa.CreateStateHandler(states.START, {
"Start": function () {
this.response.speak(WELCOME_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
},
"AnswerIntent": function () {
// Ask proactive questions
this.response.speak("Sagen Sie Start um loszulegen").listen("Weiter gehts!");
this.emit(":responseReady");
},
"QuizIntent": function () {
this.handler.state = states.QUIZ;
this.attributes["STATE"] = this.handler.state;
console.log("IN QUIZ INTENT " + this.handler.state);
console.log("IN QUIZ INTENT " + JSON.stringify(this.attributes));
this.emitWithState("Quiz");
},
"AMAZON.StopIntent": function () {
this.response.speak(EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.CancelIntent": function () {
this.response.speak(EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.HelpIntent": function () {
this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
},
"Unhandled": function () {
this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.PreviousIntent": function () {
this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.NextIntent": function () {
this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
}
});
// The questionnaire quiz handler
const quizHandlers = Alexa.CreateStateHandler(states.QUIZ, {
"Quiz": function () {
this.attributes["response"] = "";
this.attributes["counter"] = 0;
this.attributes["answerNotUnderstoodCounter"] = 0;
this.emitWithState("AskQuestion");
},
"AskQuestion": function () {
console.log("in askQuestion: " + JSON.stringify(this.attributes));
// Add the welcome message if the
if (this.attributes["counter"] === 0 && this.attributes["answerNotUnderstoodCounter"] === 0) {
this.attributes["response"] = START_QUIZ_MESSAGE + " ";
}
// Get the current item of the questions
let item = questions[this.attributes["counter"]];
// Store correct answers in session attributes
this.attributes["questionItem"] = item;
this.attributes["question"] = item.question;
this.attributes["questionType"] = item.questionType;
// Generate the answer list
// YES / NO
let answerList = item.answers;
// Get the question
let question = getQuestion(item);
let speech = this.attributes["response"] + question;
// check if we can use the display
if (USE_IMAGES_FLAG) {
// Shuffle the answers
let shuffledMultipleChoiceList = shuffle(answerList);
// Generate the list items
let listItems = shuffledMultipleChoiceList.map((x) => {
return {
"token": x,
"textContent": {
"primaryText":
{
"text": x,
"type": "PlainText"
}
}
}
});
// Generate the content
let content = {
"hasDisplaySpeechOutput": speech,
"hasDisplayRepromptText": question,
"noDisplaySpeechOutput": speech,
"noDisplayRepromptText": question,
"simpleCardTitle": getCardTitle(item),
"simpleCardContent": getTextDescription(item),
"listTemplateTitle": (this.attributes["counter"] + 1) + " : " + getCardTitle(item),
"templateToken": "MultipleChoiceListView",
"askOrTell": ":ask",
"listItems": listItems,
"hint": "Bitte sagen Sie Ja oder Nein.",
"sessionAttributes": this.attributes
};
// Set the background image if there is one
content["backgroundImageLargeUrl"] = getBackgroundImage(item);
console.log("ASK Question event: " + JSON.stringify(this.event));
// Render the template
renderTemplate.call(this, content);
} else {
this.response.speak(speech).listen(question);
this.emit(":responseReady");
}
},
"ElementSelected": function () {
// We will look for the value in this.event.request.token in the AnswerIntent call to getSlotValues
console.log("in ElementSelected QUIZ state");
this.emitWithState("AnswerIntent");
},
"Emergency": function () {
this.response.speak(EMERGENCY_UNDERSTANDING_MESSAGE);
this.emit(":tell");
},
"AnswerIntent": function () {
let response = "";
let item = this.attributes["questionItem"];
let questionType = this.attributes["questionType"];
let reqValue = getSlotValues(this.event);
console.log(reqValue);
// Get the right and the wrong answer
// YESNO -> YES
// NOYES -> NO
let rightAnswer = getRightAnswer(questionType);
// YESNO -> NO
// NOYES -> YES
let wrongAnswer = getWrongAnswer(questionType);
// Correct answer
if (rightAnswer === reqValue) {
response = getSpeechCon(true);
this.attributes["score"]++;
}
// Wrong answer
else if (wrongAnswer === reqValue) {
response = getSpeechCon(false);
} else {
// Not understood
this.attributes["answerNotUnderstoodCounter"]++;
// If alexa can not understand to often
// Go to emergency state
if (this.attributes["answerNotUnderstoodCounter"] > EMERGENCY_UNDERSTANDING_THRESHOLD) {
this.emitWithState("Emergency");
} else {
console.log("Not understood");
response = 'Ich habe Sie leider nicht verstanden.' +
'Bitte beantworten Sie die Frage nur mit Ja oder Nein.' +
'Ich wiederhole nun die Frage für Sie.<break time="1s"/>';
this.attributes["response"] = response;
// Subtract state if correct answer
if (this.attributes["answerNotUnderstoodCounter"] > 0) {
this.attributes["answerNotUnderstoodCounter"]--;
}
this.emitWithState("AskQuestion");
}
}
// If all is fine go further
this.attributes["counter"]++;
// If the questions are not finished go to the next question
if (this.attributes["counter"] < MAX_QUESTIONS) {
this.attributes["response"] = response;
this.emitWithState("AskQuestion");
} else {
// If the score is higher than the threshold
if (this.attributes["score"] > EMERGENCY_QUESTION_THRESHOLD) {
response = "Bitte kontaktieren Sie umgehend einen Arzt!";
} else {
// Check if the device supports a display
// If so then go to the next sections (display needed for photo selection and description tasks)
if (supportsDisplay.call(this) || isSimulator.call(this)) {
this.handler.state = states.SELECTQUIZ;
this.attributes['STATE'] = this.handler.state;
console.log("IN QUIZ INTENT " + this.handler.state);
console.log("IN QUIZ INTENT " + JSON.stringify(this.attributes));
this.emitWithState("Quiz");
} else {
// If the device has no display
// Terminate here
response = "Es scheint alles in Ordnung zu sein.";
}
}
if (supportsDisplay.call(this) || isSimulator.call(this)) {
//this device supports a display
let content = {
"hasDisplaySpeechOutput": response + " " + EXIT_SKILL_MESSAGE,
"bodyTemplateContent": response,
"templateToken": "FinalScoreView",
"askOrTell": ":tell",
"sessionAttributes": this.attributes
};
if (USE_IMAGES_FLAG) {
content["backgroundImageUrl"] = getBackgroundImage(item);
}
renderTemplate.call(this, content);
} else {
this.response.speak(response + " " + EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
}
}
},
"AMAZON.StartOverIntent": function () {
this.emitWithState("Quiz");
},
"AMAZON.StopIntent": function () {
this.response.speak(EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.CancelIntent": function () {
this.response.speak(EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.HelpIntent": function () {
this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
},
"Unhandled": function () {
this.emitWithState("AnswerIntent");
},
"AMAZON.PreviousIntent": function () {
this.emitWithState("AnswerIntent");
},
"AMAZON.NextIntent": function () {
this.emitWithState("AnswerIntent");
}
});
// The select quiz handler
const selectQuizHandlers = Alexa.CreateStateHandler(states.SELECTQUIZ, {
"Quiz": function () {
this.attributes["response"] = "";
this.attributes["selectCounter"] = 0;
this.attributes["selectScore"] = 0;
this.attributes["answerNotUnderstoodCounter"] = 0;
this.emitWithState("AskQuestion");
},
"AskQuestion": function () {
console.log("in askQuestion: " + JSON.stringify(this.attributes));
if (this.attributes["selectCounter"] === 0) {
this.attributes["response"] = START_QUIZ_SELECT_MESSAGE + " ";
}
// Get the item from the list
let item = selectQuestions[this.attributes["selectCounter"]];
// store correct answers in session attributes
this.attributes["questionItem"] = item;
this.attributes["question"] = item.question;
this.attributes["questionType"] = item.questionType;
this.attributes["rightAnswer"] = item.rightAnswer;
// Create list of possible answers to display on Echo Show (3 wrong, 1 right).
let answerList = item.answers;
//console.log("answerList: "+JSON.stringify(answerList));
let question = getQuestion(item);
let speech = this.attributes["response"] + question;
// Shuffle the images
let listItems = shuffle(answerList);
// Generate the content
let content = {
"hasDisplaySpeechOutput": speech,
"hasDisplayRepromptText": question,
"noDisplaySpeechOutput": speech,
"noDisplayRepromptText": question,
"simpleCardTitle": getCardTitle(item),
"simpleCardContent": getTextDescription(item),
"listTemplateTitle": (this.attributes["selectCounter"] + 1) + " : " + getCardTitle(item),
//"listTemplateContent" : getTextDescription(item),
"templateToken": "SelectListView",
"askOrTell": ":ask",
"listItems": listItems,
"hint": "Bitte drücken Sie auf das richtige Bild.",
"sessionAttributes": this.attributes
};
if (USE_IMAGES_FLAG) {
content["backgroundImageLargeUrl"] = getBackgroundImage(item);
}
console.log("ASK Question event: " + JSON.stringify(this.event));
// Render the template
renderTemplate.call(this, content);
},
"ElementSelected": function () {
// We will look for the value in this.event.request.token in the AnswerIntent call to getSlotValues
console.log("in ElementSelected QUIZ state");
this.emitWithState("AnswerIntent");
},
"Emergency": function () {
this.response.speak(EMERGENCY_UNDERSTANDING_MESSAGE);
this.emit(":tell");
},
"AnswerIntent": function () {
let response = "";
let item = this.attributes["questionItem"];
let reqValue = getSlotValues(this.event);
let rightAnswer = this.attributes["rightAnswer"];
console.log("Selected answer:", reqValue);
console.log("Real answer", rightAnswer);
// Correct answer
if (rightAnswer === reqValue) {
response = getSpeechCon(true);
} else {
response = getSpeechCon(false);
this.attributes["selectScore"]++;
}
this.attributes["selectCounter"]++;
// If the questions are not finished go to the next question
if (this.attributes["selectCounter"] < MAX_SELECT_QUESTIONS) {
this.attributes["response"] = response;
this.emitWithState("AskQuestion");
} else {
// If the score is higher than the threshold
if (this.attributes["selectScore"] > EMERGENCY_SELECT_THRESHOLD) {
response = "Bitte kontaktieren Sie umgehend einen Arzt!";
} else {
// Jump to the next quiz section
// Go to Describe
this.handler.state = states.DESCRIBEQUIZ;
this.attributes['STATE'] = this.handler.state;
console.log("IN QUIZ INTENT " + this.handler.state);
console.log("IN QUIZ INTENT " + JSON.stringify(this.attributes));
this.emitWithState("Quiz");
}
if (supportsDisplay.call(this) || isSimulator.call(this)) {
//this device supports a display
let content = {
"hasDisplaySpeechOutput": response + " " + EXIT_SKILL_MESSAGE,
"bodyTemplateContent": response,
"templateToken": "FinalScoreView",
"askOrTell": ":tell",
"sessionAttributes": this.attributes
};
if (USE_IMAGES_FLAG) {
content["backgroundImageUrl"] = getBackgroundImage(item);
}
renderTemplate.call(this, content);
} else {
this.response.speak(response + " " + EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
}
}
},
"AMAZON.StartOverIntent": function () {
this.emitWithState("Quiz");
},
"AMAZON.StopIntent": function () {
this.response.speak(EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.CancelIntent": function () {
this.response.speak(EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.HelpIntent": function () {
this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
},
"Unhandled": function () {
this.emitWithState("AnswerIntent");
},
"AMAZON.PreviousIntent": function () {
this.emitWithState("AnswerIntent");
},
"AMAZON.NextIntent": function () {
this.emitWithState("AnswerIntent");
}
});
// The describe quiz handler
const describeQuizHandlers = Alexa.CreateStateHandler(states.DESCRIBEQUIZ, {
"Quiz": function () {
this.attributes["response"] = "";
this.attributes["describeCounter"] = 0;
this.attributes["describeScore"] = 0;
this.attributes["answerNotUnderstoodCounter"] = 0;
this.emitWithState("AskQuestion");
},
"AskQuestion": function () {
console.log("in askQuestion: " + JSON.stringify(this.attributes));
if (this.attributes["describeCounter"] === 0) {
this.attributes["response"] = START_QUIZ_DESCRIBE_MESSAGE + " ";
}
let item = describeQuestions[this.attributes["describeCounter"]];
// store correct answers in session attributes
this.attributes["questionItem"] = item;
this.attributes["question"] = item.question;
this.attributes["questionType"] = item.questionType;
this.attributes["rightAnswer"] = item.rightAnswer;
//console.log("answerList: "+JSON.stringify(answerList));
let question = getQuestion(item);
let speech = this.attributes["response"] + question;
// Generate the content
let content = {
"hasDisplaySpeechOutput": speech,
"hasDisplayRepromptText": question,
"noDisplaySpeechOutput": speech,
"noDisplayRepromptText": question,
"simpleCardTitle": getCardTitle(item),
"simpleCardContent": getTextDescription(item),
"listTemplateTitle": (this.attributes["describeCounter"] + 1) + " : " + getCardTitle(item),
//"listTemplateContent" : getTextDescription(item),
"templateToken": "DescribeView",
"askOrTell": ":ask",
"image": item.image,
"hint": "Bitte drücken Sie auf das richtige Bild.",
"sessionAttributes": this.attributes
};
// Set the background image
if (USE_IMAGES_FLAG) {
content["backgroundImageLargeUrl"] = getBackgroundImage(item);
}
console.log("ASK Question event: " + JSON.stringify(this.event));
// Render the template
renderTemplate.call(this, content);
},
"ElementSelected": function () {
// We will look for the value in this.event.request.token in the AnswerIntent call to getSlotValues
console.log("in ElementSelected QUIZ state");
this.emitWithState("AnswerIntent");
},
"Emergency": function () {
this.response.speak(EMERGENCY_UNDERSTANDING_MESSAGE);
this.emit(":tell");
},
"AnswerIntent": function () {
let response = "";
let item = this.attributes["questionItem"];
let reqValue = getSlotValues(this.event);
let rightAnswer = this.attributes["rightAnswer"];
//
console.log("Selected answer:", reqValue);
console.log("Real answer", rightAnswer);
// Correct answer
if (rightAnswer === reqValue) {
response = getSpeechCon(true);
this.attributes["describeScore"]++;
} else {
response = getSpeechCon(false);
}
this.attributes["describeCounter"]++;
// If the questions are not finished go to the next question
if (this.attributes["describeCounter"] < MAX_DESCRIBE_QUESTIONS) {
this.attributes["response"] = response;
this.emitWithState("AskQuestion");
} else {
// If the score is higher than the threshold
if (this.attributes["describeScore"] < EMERGENCY_DESCRIBE_THRESHOLD) {
response = "Bitte kontaktieren Sie umgehend einen Arzt!";
} else {
response = "Es scheint alles in Ordnung zu sein.";
}
// Check if the support
if (supportsDisplay.call(this) || isSimulator.call(this)) {
//this device supports a display
let content = {
"hasDisplaySpeechOutput": response + " " + EXIT_SKILL_MESSAGE,
"bodyTemplateContent": response,
"templateToken": "FinalScoreView",
"askOrTell": ":tell",
"sessionAttributes": this.attributes
};
if (USE_IMAGES_FLAG) {
content["backgroundImageUrl"] = getBackgroundImage(item);
}
renderTemplate.call(this, content);
} else {
this.response.speak(response + " " + EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
}
}
},
"AMAZON.StartOverIntent": function () {
this.emitWithState("Quiz");
},
"AMAZON.StopIntent": function () {
this.response.speak(EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.CancelIntent": function () {
this.response.speak(EXIT_SKILL_MESSAGE);
this.emit(":responseReady");
},
"AMAZON.HelpIntent": function () {
this.response.speak(HELP_MESSAGE).listen(HELP_MESSAGE);
this.emit(":responseReady");
},
"Unhandled": function () {
this.emitWithState("AnswerIntent");
},
"AMAZON.PreviousIntent": function () {
this.emitWithState("AnswerIntent");
},
"AMAZON.NextIntent": function () {
this.emitWithState("AnswerIntent");
}
});
//==============================================================================
//===================== Export the handler =====================================
//==============================================================================
exports.handler = (event, context) => {
const alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
alexa.registerHandlers(handlers, startHandlers, quizHandlers, selectQuizHandlers, describeQuizHandlers);
alexa.execute();
};
//==============================================================================
//===================== Echo Show Helper Functions ============================
//==============================================================================
// Help function
function getQuestion(item) {
return item.question;
}
// Get the right answer - YES / NO QUESTIONS
function getRightAnswer(questionType) {
switch (questionType) {
case "YESNO":
return "ja";
case "NOYES":
return "nein";
default:
return questionType
}
}
// Get the wrong answers - YES / NO QUESTIONS
function getWrongAnswer(questionType) {
switch (questionType) {
case "YESNO":
return "nein";
case "NOYES":
return "ja";
default:
return questionType
}
}
//This is what your card title will be. For our example, we use the name of the state the user requested.
function getCardTitle(item) {
return item.question;
}
//This is the small version of the card image. We use our data as the naming convention for our images so that we can dynamically
//generate the URL to the image. The small image should be 720x400 in dimension.
function getSmallImage(item) {
if (item.imageSmallUrl) {
return item.imageSmallUrl;
}
return IMAGE_FALLBACK;
}
//This is the large version of the card image. It should be 1200x800 pixels in dimension.
function getLargeImage(item) {
if (item.imageSmallUrl) {
return item.imageSmallUrl;
}
return IMAGE_FALLBACK;
}
// backgroundImage for Echo Show body templates
function getBackgroundImage(item) {
if (item.imageSmallUrl) {
return item.imageSmallUrl;
}
return IMAGE_FALLBACK;
}
function getSlotValues(event) {
//are there
let isSlot =
event.request &&
event.request.intent &&
event.request.intent.slots;
//are there tokens
let isToken =
event.request &&
event.request.token;
if (isSlot) {
let slots = event.request.intent.slots;
for (let slot in slots) {
if (slots[slot].value && slots[slot].value != undefined) {
return slots[slot].value.toString().toLowerCase();
}
}
}
if (isToken) {
return event.request.token.toString().toLowerCase();
}
return "";
}
function shuffle(array) {
let currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function getRandomSymbolSpeech(symbol) {
return "<say-as interpret-as='spell-out'>" + symbol + "</say-as>";
}
function getSpeechCon(type) {
if (type) {
return "<say-as interpret-as='interjection'>" + speechConsCorrect[getRandom(0, speechConsCorrect.length - 1)] + "! </say-as><break strength='strong'/>";
} else {
return "<say-as interpret-as='interjection'>" + speechConsWrong[getRandom(0, speechConsWrong.length - 1)] + " </say-as><break strength='strong'/>";
}
}
function formatCasing(key) {
key = key.split(/(?=[A-Z])/).join(" ");
return key;
}
function getTextDescription(item) {
var text = "";
for (var key in item) {
text += formatCasing(key) + ": " + item[key] + "\n";
}
return text;
}
function supportsDisplay() {
return this.event.context &&
this.event.context.System &&
this.event.context.System.device &&
this.event.context.System.device.supportedInterfaces &&
this.event.context.System.device.supportedInterfaces.Display;
}
function isSimulator() {
let isSimulator = !this.event.context; //simulator doesn't send context
return false;
}
function renderTemplate(content) {
console.log("renderTemplate" + content.templateToken);
//learn about the various templates
//https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/display-interface-reference#display-template-reference
//
let response = {};
switch (content.templateToken) {
case "WelcomeScreenView":
//Send the response to Alexa
this.context.succeed(response);
break;
case "FinalScoreView":
// "hasDisplaySpeechOutput" : response + " " + EXIT_SKILL_MESSAGE,
// "bodyTemplateContent" : getFinalScore(this.attributes["quizscore"], this.attributes["counter"]),
// "templateToken" : "FinalScoreView",
// "askOrTell": ":tell",
// "hint":"start a quiz",
// "sessionAttributes" : this.attributes
// "backgroundImageUrl"
response = {
"version": "1.0",
"response": {
"directives": [
{
"type": "Display.RenderTemplate",
"backButton": "HIDDEN",
"template": {
"type": "BodyTemplate6",
//"title": content.bodyTemplateTitle,
"token": content.templateToken,
"textContent": {
"primaryText": {
"type": "RichText",
"text": "<font size = '7'>" + content.bodyTemplateContent + "</font>"
}
}
}
}, {
"type": "Hint",
"hint": {
"type": "PlainText",
"text": content.hint
}
}
],
"outputSpeech": {
"type": "SSML",
"ssml": "<speak>" + content.hasDisplaySpeechOutput + "</speak>"
},
"reprompt": {
"outputSpeech": {
"type": "SSML",
"ssml": ""
}
},
"shouldEndSession": content.askOrTell == ":tell",
},
"sessionAttributes": content.sessionAttributes
};
if (content.backgroundImageUrl) {
//when we have images, create a sources object
let sources = [
{
"size": "SMALL",
"url": content.backgroundImageUrl
},
{
"size": "LARGE",
"url": content.backgroundImageUrl
}
];
//add the image sources object to the response
response["response"]["directives"][0]["template"]["backgroundImage"] = {};
response["response"]["directives"][0]["template"]["backgroundImage"]["sources"] = sources;
}
//Send the response to Alexa
this.context.succeed(response);
break;
case "ItemDetailsView":
response = {
"version": "1.0",
"response": {
"directives": [
{
"type": "Display.RenderTemplate",
"template": {
"type": "BodyTemplate3",
"title": content.bodyTemplateTitle,
"token": content.templateToken,
"textContent": {
"primaryText": {
"type": "RichText",
"text": "<font size = '5'>" + content.bodyTemplateContent + "</font>"
}
},
"backButton": "HIDDEN"
}
}
],
"outputSpeech": {
"type": "SSML",
"ssml": "<speak>" + content.hasDisplaySpeechOutput + "</speak>"
},
"reprompt": {
"outputSpeech": {
"type": "SSML",
"ssml": "<speak>" + content.hasDisplayRepromptText + "</speak>"
}
},
"shouldEndSession": content.askOrTell == ":tell",
"card": {
"type": "Simple",
"title": content.simpleCardTitle,
"content": content.simpleCardContent
}
},
"sessionAttributes": content.sessionAttributes
};
if (content.imageSmallUrl && content.imageLargeUrl) {
//when we have images, create a sources object
//TODO switch template to one without picture?
let sources = [
{
"size": "SMALL",
"url": content.imageSmallUrl
},
{
"size": "LARGE",
"url": content.imageLargeUrl
}
];
//add the image sources object to the response
response["response"]["directives"][0]["template"]["image"] = {};
response["response"]["directives"][0]["template"]["image"]["sources"] = sources;
}
//Send the response to Alexa
console.log("ready to respond (ItemDetailsView): " + JSON.stringify(response));
this.context.succeed(response);
break;
case "MultipleChoiceListView":
console.log("listItems " + JSON.stringify(content.listItems));
response = {
"version": "1.0",
"response": {
"directives": [
{
"type": "Display.RenderTemplate",
"template": {
"type": "ListTemplate1",
"title": content.listTemplateTitle,
"token": content.templateToken,
"listItems": content.listItems,
"backgroundImage": {
"sources": [
{
"size": "SMALL",
"url": content.backgroundImageSmallUrl
},
{
"size": "LARGE",
"url": content.backgroundImageLargeUrl
}
]
},
"backButton": "HIDDEN"
}
}
],
"outputSpeech": {
"type": "SSML",
"ssml": "<speak>" + content.hasDisplaySpeechOutput + "</speak>"
},
"reprompt": {
"outputSpeech": {
"type": "SSML",
"ssml": "<speak>" + content.hasDisplayRepromptText + "</speak>"
}
},
"shouldEndSession": content.askOrTell === ":tell",
"card": {
"type": "Simple",
"title": content.simpleCardTitle,
"content": content.simpleCardContent
}
},
"sessionAttributes": content.sessionAttributes
};
if (content.backgroundImageLargeUrl) {
//when we have images, create a sources object