-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
700 lines (577 loc) · 21.6 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
const express = require('express');
const bodyParser = require('body-parser');
const ad = require('./helper-functions/airtable-database');
// Actions-on-Google
const {
dialogflow,
actionssdk,
Image,
Table,
Carousel,
Suggestions,
BasicCard
} = require('actions-on-google');
const app = dialogflow({
debug: true
});
// Error handling
app.catch((conv, error) => {
console.error('Error at conv catch --> ', error);
conv.close('I encountered a glitch. Please try again after some time.');
});
// Fallback
app.fallback((conv) => {
conv.ask(`I couldn't understand. Please try again after some time.`);
});
// Initialize
app.intent('Default Welcome Intent', async (conv) => {
// Get all the user names
let names = await ad.getUserNames();
// Set Default Fallback Count
conv.data.fallbackCount = 0;
// Set the context
conv.contexts.set('await-student-name', 1);
conv.ask('Hi, I welcome to OVO quiz!');
conv.ask(new BasicCard({
text: 'Please choose a username: ',
image: new Image({
url: 'https://firebasestorage.googleapis.com/v0/b/ovobot-quiz.appspot.com/o/images%2FOVObot_1024x1024.png?alt=media&token=401b1fba-90c7-4a36-9dd6-183611178d8a',
alt: 'OVO Bot Logo'
}),
display: 'WHITE'
}));
conv.ask(new Suggestions(names.slice(0, 8)));
});
// Step - 1 User provides name
app.intent('Provides-Name', async (conv, params) => {
let studentName = params['person']['name'];
// Get student details
let record = await ad.getUserInfo(studentName);
if (record['status'] == 1) {
conv.data.studentName = studentName;
conv.data.studentID = record['id'];
conv.data.memoLevel = record['memoLevel'];
conv.data.conseptsLevel = record['conseptsLevel'];
conv.data.mathLevel = record['mathLevel'];
conv.data.clockLevel = record['clockLevel'];
// Set question number
let qn = 0;
conv.data.qn = qn;
// Set right answer count
let count = 0;
conv.data.count = count;
conv.contexts.set('await-quiz-type', 1);
conv.ask(`Hello ${studentName}, What would you like to practice today?`);
conv.ask(new Suggestions('Memo', 'Consepts', 'Clock', 'Math', 'E-Shop'));
} else {
conv.close(`Sorry ${studentName}, I did not find your name, please contact Admin.`);
}
});
// Step - 2 Choice is WORD
app.intent('Ask-First-Question', async (conv) => {
// This is to save the question type
conv.data.Type = conv.query.charAt(0).toUpperCase() + conv.query.slice(1);
// Empty question list
let qList = [];
// Generate question list
if (conv.data.Type === 'Memo') {
qList = await ad.getAllQuestionList('Memo', conv.data.memoLevel);
} else if (conv.data.Type === 'Consepts') {
qList = await ad.getAllQuestionList('Consepts', conv.data.conseptsLevel);
} else if (conv.data.Type === 'Math') {
qList = await ad.getAllQuestionList('Math', conv.data.mathLevel);
} else if (conv.data.Type === 'Clock') {
qList = await ad.getAllQuestionList('Clock', conv.data.clockLevel);
}
// Answered question list
let aqList = await ad.getAnsweredQuestionList(conv.data.studentName);
// Un Answered question list
let uaList = qList.filter(x => !aqList.includes(x));
if (uaList.length == 0) {
conv.data.uaList = qList;
} else {
conv.data.uaList = uaList;
}
// Current number for question
let cn = conv.data.qn;
// Current question number
let cqn = conv.data.uaList[cn];
// Get the question
let record = await ad.getNewQuestion(conv.data.Type, cqn);
if (record == 0) {
conv.contexts.set('await-continue-yes', 1);
conv.ask('Sorry, we do not have more question. Please, change the category.');
conv.ask(new Suggestions('Menu'));
} else {
let Answer = record['Answer'];
let Question = record['Question'];
let ImageURL = record['ImageURL'];
let QID = record['QuestionID'];
let Hint = record['Hint'];
let HintImageURL = record['HintImage'];
let HintText = record['HintText'];
conv.contexts.set('await-answer-first', 1);
conv.data.Hint = Hint;
conv.data.HintImageURL = HintImageURL;
conv.data.HintText = HintText
conv.data.Answer = Answer;
conv.data.Question = Question;
conv.data.ImageURL = ImageURL;
conv.data.QID = QID;
conv.ask(Question);
conv.ask(new BasicCard({
image: new Image({
url: ImageURL,
alt: 'Question Image'
}),
display: 'WHITE'
}));
}
});
// Step - 2 Choice is WORD
app.intent('Ask-Question', async (conv) => {
// Current number of question
let cn = conv.data.qn;
// Current question number
let cqn = conv.data.uaList[cn];
if (cqn === undefined) {
// Reset the question number
conv.data.qn = 0;
cn = conv.data.qn;
let qList = [];
// Generate question list
if (conv.data.Type === 'Memo') {
qList = await ad.getAllQuestionList('Memo', conv.data.memoLevel);
} else if (conv.data.Type === 'Consepts') {
qList = await ad.getAllQuestionList('Consepts', conv.data.conseptsLevel);
} else if (conv.data.Type === 'Math') {
qList = await ad.getAllQuestionList('Math', conv.data.mathLevel);
} else if (conv.data.Type === 'Clock') {
qList = await ad.getAllQuestionList('Clock', conv.data.clockLevel);
}
conv.data.uaList = qList;
}
cqn = conv.data.uaList[cn];
// Get the question data
let record = await ad.getNewQuestion(conv.data.Type, cqn);
if (record == 0) {
conv.contexts.set('await-continue-yes', 1);
conv.ask('Sorry, we do not have more question. Please, change the category.');
conv.ask(new Suggestions('Menu'));
} else {
let Answer = record['Answer'];
let Question = record['Question'];
let ImageURL = record['ImageURL'];
let QID = record['QuestionID'];
let Hint = record['Hint'];
let HintImageURL = record['HintImage'];
let HintText = record['HintText'];
conv.contexts.set('await-answer-first', 1);
conv.data.Hint = Hint;
conv.data.HintImageURL = HintImageURL;
conv.data.HintText = HintText;
conv.data.Answer = Answer;
conv.data.Question = Question;
conv.data.ImageURL = ImageURL;
conv.data.QID = QID;
conv.ask(Question);
conv.ask(new BasicCard({
image: new Image({
url: ImageURL,
alt: 'Question Image'
}),
display: 'WHITE'
}));
}
});
// Step - 3 User provides the answer
app.intent('Provides-Answer-First', async (conv) => {
let clapURL = 'https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/emojidex/59/clapping-hands-sign_emoji-modifier-fitzpatrick-type-5_1f44f-1f3fe_1f3fe.png';
let actualAnswer = conv.data.Answer;
let userAnswer = conv.query;
if (userAnswer.toLowerCase() === 'menu') {
conv.followup('menu', {
type: 'menu'
});
}
// Create new record for ImageQuestionProgress
fields = {
'Name': conv.data.studentName,
'QuestionID': conv.data.QID,
'Answered': 1,
'Answer1': userAnswer,
'Answer2': 'NA'
}
// Insert the progress to the table
ad.createProgress(conv.data.studentName, fields)
.then((flag) => {
// Use the flag here
console.log('Status --> ', flag);
console.log('Data inserted into progress table.');
})
.catch((error) => {
console.log('Error at createProgree [First - Answer] --> ', error);
});
// Generate list from actual answeres in case different answeres
let ansTempList = actualAnswer.split(',');
let ansList = [];
ansTempList.forEach(element => {
ansList.push(element.toLowerCase());
});
if (ansList.includes(userAnswer.toLowerCase())) {
// Get the right answer message
let message = await ad.getCongratsMessage('Right Answer');
if (message['Image'] == 0) {
conv.ask(message['Message']);
conv.ask(new BasicCard({
image: new Image({
url: clapURL,
alt: 'Clap Image'
})
}));
} else {
conv.ask(message['Message']);
conv.ask(new BasicCard({
image: new Image({
url: message['ImageURL'],
alt: 'Congratulation Image'
})
}));
}
// Increment the count of right answer
conv.data.count = conv.data.count + 1;
// Increment the question number
conv.data.qn = conv.data.qn + 1;
if (conv.data.count == 3) {
// Update student level
let cLevel = conv.data[`${conv.data.Type.toLowerCase()}Level`];
// Generate the string LevelX
let nLevel = parseInt(cLevel.split('l')[1]) + 1;
if (conv.data.Type === 'Memo') {
fields = {
'Memo': `Level${nLevel}`
}
conv.data.memoLevel = `Level${nLevel}`;
} else if (conv.data.Type === 'Consepts') {
fields = {
'Consepts': `Level${nLevel}`
}
conv.data.conseptsLevel = `Level${nLevel}`;
} else if (conv.data.Type === 'Math') {
fields = {
'Math': `Level${nLevel}`
}
conv.data.mathLevel = `Level${nLevel}`;
} else {
fields = {
'Clock': `Level${nLevel}`
}
conv.data.clockLevel = `Level${nLevel}`;
}
let flag = await ad.updateStudent(conv.data.studentID, fields);
// Get all the questions from new Level
let qList = await ad.getAllQuestionList(conv.data.Type, `Level${nLevel}`);
conv.data.uaList = qList;
// Reset the count
conv.data.count = 0;
// Reset the question number
conv.data.qn = 0;
if (flag == 1) {
// Ask new question here
conv.contexts.set('await-continue-yes', 1);
let messageLevelUp = await ad.getCongratsMessage('Level Up');
if (messageLevelUp['Image'] == 0) {
let m = messageLevelUp['Message'];
conv.ask(m);
conv.ask(new Suggestions('Next Question', 'Menu', 'Show Results'));
} else {
let m = messageLevelUp['Message'];
conv.ask(m);
conv.ask(new Suggestions('Next Question', 'Menu', 'Show Results'));
}
} else {
conv.ask('Sorry, I encountered an error. Try agin after sometime.')
}
} else {
conv.contexts.set('await-continue-yes', 1);
conv.ask(new Suggestions('Next Question', 'Menu', 'Show Results'));
}
} else {
conv.contexts.set('await-answer-second', 1);
if (conv.data.HintText != 0) {
if (conv.data.HintImageURL != 0) {
// Show card with hint image and text
let ssml;
ssml = '<speak>' +
'It is a wrong answer.' +
'<audio src="https://www.soundjay.com/misc/fail-buzzer-01.mp3"></audio>' +
'</speak>';
conv.ask(ssml);
conv.ask(new BasicCard({
image: new Image({
url: conv.data.HintImageURL,
alt: 'Hint Image'
}),
display: 'WHITE',
title: conv.data.HintText
}));
} else {
// Show card with image and text
let ssml;
ssml = '<speak>' +
'It is a wrong answer.' +
'<audio src="https://www.soundjay.com/misc/fail-buzzer-01.mp3"></audio>' +
'</speak>';
conv.ask(ssml);
conv.ask(new BasicCard({
image: new Image({
url: conv.data.ImageURL,
alt: 'Hint Image'
}),
display: 'WHITE',
title: conv.data.HintText
}));
}
} else if (conv.data.Hint != 0) {
// speak the hint
let ssml;
ssml = '<speak>' +
'It is a wrong answer.' +
'<audio src="https://www.soundjay.com/misc/fail-buzzer-01.mp3"></audio>' +
'<break time="200ms"/>' +
conv.data.Hint +
'</speak>';
conv.ask(ssml);
} else {
// Show only that it is a wrong answer
let ssml;
ssml = '<speak>' +
'It is a wrong answer.' +
'<audio src="https://www.soundjay.com/misc/fail-buzzer-01.mp3"></audio>' +
'<break time="200ms"/>' +
'Please try again.' +
'</speak>';
conv.ask(ssml);
}
}
});
// User provides answer second time
app.intent('Provides-Answer-Second', async (conv) => {
let clapURL = 'https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/emojidex/59/clapping-hands-sign_emoji-modifier-fitzpatrick-type-5_1f44f-1f3fe_1f3fe.png';
let actualAnswer = conv.data.Answer;
let userAnswer = conv.query;
if (userAnswer.toLowerCase() === 'menu') {
conv.followup('menu', {
type: 'menu'
});
}
// Update ImageQuestionProgress
fields = {
'Answer2': userAnswer
}
let id = await ad.getProgressByID(conv.data.studentName, conv.data.QID);
if (id == 0) {
console.log('Error at getProcessByID [Answer - Two]')
} else {
ad.updateProgress(conv.data.studentName, id, fields)
.then((flag) => {
// Use the flag here
})
.catch((error) => {
console.log('Error at updateProgress [Answer - Two] --> ', error);
});
}
// Generate list from actual answeres in case different answers
let ansTempList = actualAnswer.split(',');
let ansList = [];
ansTempList.forEach(element => {
ansList.push(element.toLowerCase());
});
if (ansList.includes(userAnswer.toLowerCase())) {
let message = await ad.getCongratsMessage('Right Answer');
if (message['Image'] == 0) {
conv.ask(message['Message']);
conv.ask(new BasicCard({
image: new Image({
url: clapURL,
alt: 'Clap Image'
})
}));
} else {
conv.ask(message['Message']);
conv.ask(new BasicCard({
image: new Image({
url: message['ImageURL'],
alt: 'Congratulation Image'
})
}));
}
// Increment the count of right answer
conv.data.count = conv.data.count + 1;
// Increment the question number
conv.data.qn = conv.data.qn + 1;
if (conv.data.count == 3) {
// Update student level
let cLevel = conv.data[`${conv.data.Type.toLowerCase()}Level`];
// Generate the string LevelX
let nLevel = parseInt(cLevel.split('l')[1]) + 1;
if (conv.data.Type === 'Memo') {
fields = {
'Memo': `Level${nLevel}`
}
conv.data.memoLevel = `Level${nLevel}`;
} else if (conv.data.Type === 'Consepts') {
fields = {
'Consepts': `Level${nLevel}`
}
conv.data.conseptsLevel = `Level${nLevel}`;
} else if (conv.data.Type === 'Math') {
fields = {
'Math': `Level${nLevel}`
}
conv.data.mathLevel = `Level${nLevel}`;
} else {
fields = {
'Clock': `Level${nLevel}`
}
conv.data.clockLevel = `Level${nLevel}`;
}
let flag = await ad.updateStudent(conv.data.studentID, fields);
// Get question list
let qList = await ad.getAllQuestionList(conv.data.Type, `Level${nLevel}`);
conv.data.uaList = qList;
// Reset the count
conv.data.count = 0;
// Reset the question number
conv.data.qn = 0;
if (flag == 1) {
let messageLevelUp = await ad.getCongratsMessage('Level Up');
if (messageLevelUp['Image'] == 0) {
let m = messageLevelUp['Message'];
conv.ask(m);
conv.ask(new Suggestions('Next Question', 'Menu', 'Show Results'));
} else {
let m = messageLevelUp['Message'];
conv.ask(m);
conv.ask(new Suggestions('Next Question', 'Menu', 'Show Results'));
}
} else {
conv.ask('Sorry, I encountered an error. Try agin after sometime.')
}
} else {
conv.contexts.set('await-continue-yes', 1);
conv.ask(new Suggestions('Next Question', 'Menu', 'Show Results'));
}
} else {
// Reset the count
conv.data.count = 0;
// Increase the question number
conv.data.qn = conv.data.qn + 1;
// Ask new question here
conv.contexts.set('await-continue-yes', 1);
conv.ask(`Not quite. The answer is ` + actualAnswer + `.`);
conv.ask(new Suggestions('Next Question', 'Menu', 'Show Results'));
}
});
// E Shop intent
app.intent('E-Shop', (conv) => {
conv.contexts.set('e-shop-conv', 1);
conv.data.checkoutPrice = 0;
conv.ask('Welcome to e-shop! How can I help you?');
});
app.intent('E-Shop-Buy-Items', async (conv, params) => {
conv.contexts.set('e-shop-conv', 1);
let item = params['item'];
let record = await ad.getItemFromEShop(item);
if (record['status'] == 0) {
conv.ask(`${item} is not available, do you want anything else?`);
} else {
let price = record['Price'];
conv.data.checkoutPrice = conv.data.checkoutPrice + price;
conv.ask(`${item} is added, do you want anything else?`)
conv.ask(new BasicCard({
image: new Image({
url: record['ImageURL'],
alt: 'E-Shop Image'
})
}));
}
})
// E Shop checkout intent
app.intent('E-Shop-Checkout', (conv) => {
conv.contexts.set('e-shop-conv', 0);
conv.close(`It takes ${conv.data.checkoutPrice} Euros.`);
});
// Continue yes
app.intent('Continue-Yes', (conv) => {
// Call an event to continue asking a new question
conv.followup('question', {
type: 'Word'
});
});
// Continue no
app.intent('Continue-No', (conv) => {
conv.ask(`Thank you ${conv.data.studentName} for using the app.`);
});
// Cancel button
app.intent('Cancel', (conv) => {
conv.close(`Thank you ${conv.data.studentName} for using the app.`);
});
// Default fallback intent
app.intent('Default Fallback Intent', (conv) => {
conv.data.fallbackCount = conv.data.fallbackCount + 1;
let contexts = conv.contexts.input;
for (const key in contexts) {
if (contexts.hasOwnProperty(key)) {
if (contexts[key]['name'].includes('await-')) {
let vals = contexts[key]['name'].split('/');
getContext = vals[vals.length - 1]
}
}
}
if (conv.data.fallbackCount < 10) {
conv.contexts.set(getContext, 1);
conv.ask('Please say it again.');
} else {
conv.close('Sorry, I am facing trouble hearing you, try again after sometime.');
}
});
// Show result
app.intent('Show Results', async (conv) => {
// Get student result
let result = await ad.getStudentLevels(conv.data.studentName);
// Check the status
if (result['status'] == 1) {
conv.contexts.set('await-quiz-type', 1);
conv.ask('Your result is shown in the table below.');
conv.ask(new Table({
dividers: true,
columns: ['Question Type', 'Level'],
rows: [
['Memo', result['memoLevel']],
['Consepts', result['conseptsLevel']],
['Clock', result['clockLevel']],
['Math', result['mathLevel']],
],
}));
conv.ask(`Okay ${conv.data.studentName}, What would you like to practice now?`);
conv.ask(new Suggestions('Memo', 'Consepts', 'Clock', 'Math', 'E-Shop'));
} else {
conv.contexts.set('await-quiz-type', 1);
conv.ask('Sorry, we did not find your result at this time.');
conv.ask(`Hello ${conv.data.studentName}, What would you like to practice now?`);
conv.ask(new Suggestions('Memo', 'Consepts', 'Clock', 'Math', 'E-Shop'));
}
});
// Webserver
const Webapp = express();
Webapp.use(bodyParser.urlencoded({ extended: true }));
Webapp.use(bodyParser.json());
const PORT = process.env.PORT || 5000;
Webapp.get('/', (req, res) => {
res.send('Hello World.!')
});
Webapp.post('/webhook', app);
Webapp.listen(PORT, () => {
console.log(`Server is running at ${PORT}`);
});