-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
3792 lines (2923 loc) · 126 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
// https://vast-peak-63221.herokuapp.com/
const serverPath = 'http://localhost:8000/';
//postgres database url
const DATABASE_URL = 'postgres://dcfvnzofeempgk:2c027d6f6788c5b82e4cbb9e9d388254211a61156d1fc1e35312c8c5885958aa@ec2-107-22-167-179.compute-1.amazonaws.com:5432/d3teg1g8u2anm';
const { Client } = require('pg');
//database connection information? database instance
const client = new Client({
connectionString: DATABASE_URL,
ssl: true,
});
client.connect(); //connecting to the database? client database instance
//-------------------------------------------------------------------------------------------------------[EMAIL HANDLING]---
var current_verification_code='0';
var current_facebook_id='';
var current_registrationnumber='';
var generator = require('generate-password');
var nodemailer = require('nodemailer'); //get instance
var transporter = nodemailer.createTransport({ //setting email account details
service: 'gmail',
auth: {
user: '[email protected]',
pass: '39gkjgOJga#)(%@309y3kgb2589rDJLpew'
}
});
function verification_code_generate(){
var password = generator.generate({
length: 10,
numbers: true
});
current_verification_code=password;
//update database
db_query_update_verification_code(current_registrationnumber,'facebook',current_verification_code);
return password;
}
function get_mail_send_verification(email_to,verification_code){
var mail_send_verification = {
from: 'perachatbot@[email protected]',
to: email_to,
subject: 'PeraInfoBot - Facebook Verification!',
text: 'Please click this link to verify your request : '+serverPath+'verify-facebook?regno='+current_registrationnumber+'&client=facebook&verification_code='+verification_code+'&client_id='+current_facebook_id
};
return mail_send_verification;
}
function email_send_verification_code(email_to){
transporter.sendMail(get_mail_send_verification(email_to,verification_code_generate()), function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
/**
to send verification email
email_send_verification_code('[email protected]');
**/
//-------------------------------------------------------------------------------------------------------[FB-REGISTRAION-FUNCTIONS]-------
function getCompatibleEnumber(given_enumber){
return given_enumber.replace('E', 'e').replace(/\//g ,'').trim().toString();
}
function db_query_get_email_from_registrationnumber(user_table_name,confirmed_regnumber){
console.log('======= db_query_get_email_from_registrationnumber =========');
let query = `select primaryemail from ${user_table_name} where registrationnumber='${confirmed_regnumber}';`;
var error, data;
client.query(query, function(err, result) {
if (!err && result.rows.length > 0){
// If no Error get eNumber and query studentInfoTable
let primary_email = result.rows[0].primaryemail;
console.log('primaryemail = ' + primary_email);
return primary_email;
}else {
error = err || `No record found at ${user_table_name}`;
//callback(error, data);
return 'no-result-found';
}
});
}
//this function send a verification email to the given registration number on given table
function db_query_get_email_from_registrationnumber_and_send_verification_email(user_table_name,confirmed_regnumber){
console.log('======= db_query_get_email_from_registrationnumber =========');
let query = `select primaryemail from ${user_table_name} where registrationnumber='${confirmed_regnumber}';`;
var error, data;
client.query(query, function(err, result) {
if (!err && result.rows.length > 0){
// If no Error get eNumber and query studentInfoTable
let primary_email = result.rows[0].primaryemail;
console.log('primaryemail = ' + primary_email);
//now send the email
email_send_verification_code(primary_email);
}else {
error = err || `No record found at ${user_table_name}`;
//callback(error, data);
console.log('error : querying email using registration number');
}
});
}
//add the current facebooid to the database
function db_query_set_current_facebook_id(table_name,confirmed_regnumber,current_facebook_id){
console.log('======= db_query_set_current_facebook_id =========');
let query = `update ${user_table_name} set facebooid='${current_facebook_id}' where registrationnumber='${confirmed_regnumber}';`;
var error, data;
client.query(query, function(err, result) {
if (!err){
console.log('successfully linked the facebooid');
}else {
error = err || `No record found at ${user_table_name}`;
//callback(error, data);
console.log('unsuccessfull - linking facebooid');
}
});
}
//update/insert the verification_code in database
//check for previous entries [regnumber+chatclient]
//if exists-> update else insert
function db_query_update_verification_code(confirmed_regnumber,chatting_client,verification_code){
console.log('======= db_query_update_verification_code =========');
let query = `select exists(select verificationcode from table_chatclient_verification where registrationnumber='${confirmed_regnumber}' and chatclient='${chatting_client}');`;
var error, data;
client.query(query, function(err, result) {
if (!err){
let query_result = result.rows[0].exists;
console.log("record exists : "+query_result);
if('true'==JSON.stringify(query_result)){//exists->update
let query = `update table_chatclient_verification set verificationcode='${verification_code}' where registrationnumber='${confirmed_regnumber}' and chatclient='${chatting_client}';`;
//console.log(query);
var error, data;
client.query(query, function(err, result) {
if (!err){
console.log("verification code updated");
}else {
error = err || `No record found at table`;
//callback(error, data);
console.log('unsuccessfull - db_query_update_verification_code-update error');
}
});
}else{ //insert
var request_time=new Date().toISOString().
replace(/T/, ' '). // replace T with a space
replace(/\..+/, ''); // delete the dot and everything after;
let query = `insert into table_chatclient_verification(requestTime, registrationNumber, chatClient, verificationCode) values('${request_time}','${confirmed_regnumber}','${chatting_client}','${verification_code}');`;
var error, data;
client.query(query, function(err, result) {
if (!err){
console.log("verification code inserted");
}else {
error = err || `No record found at table`;
//callback(error, data);
console.log('unsuccessfull - db_query_update_verification_code-insert error');
}
});
}
}else {
error = err || `No record found at ${user_table_name}`;
//callback(error, data);
console.log('unsuccessfull - db_query_update_verification_code-existance_check');
}
});
}
//select verification code
function db_query_select_verification_code(confirmed_regnumber,chatting_client,verification_code,client_id,response){
console.log('======= db_query_select_verification_code =========');
let query = `(select verificationcode from table_chatclient_verification where registrationnumber='${confirmed_regnumber}' and chatclient='${chatting_client}');`;
var error, data;
client.query(query, function(err, result) {
if (!err){
console.log(result.rows[0]);
let query_result = result.rows[0].verificationcode;
console.log("verificationcode in db : "+query_result+ "sent : "+verification_code);
//verify the code
if(verification_code==query_result){
console.log('verification codes matched - linking started');
//landing page
response.render('pages/verify-facebook-valid');
//link the client
let query = `select exists(select * from table_user_map_chatclients where registrationnumber='${confirmed_regnumber}');`;
var error, data;
client.query(query, function(err, result) {
if (!err){
let query_result = result.rows[0].exists;
console.log("record exists : "+query_result);
if('true'==JSON.stringify(query_result)){//exists->update
let query = `update table_user_map_chatclients set facebookid='${client_id}' where registrationnumber='${confirmed_regnumber}';`;
console.log(query);
var error, data;
client.query(query, function(err, result) {
if (!err){
console.log("clinet link updated");
}else {
error = err || `No record found at table`;
//callback(error, data);
console.log('unsuccessfull - db_query_select_verification_code-link update error');
}
});
}else{ //insert
var request_time=new Date().toISOString().
replace(/T/, ' '). // replace T with a space
replace(/\..+/, ''); // delete the dot and everything after;
let query = `insert into table_user_map_chatClients(registrationnumber, facebookid, whatsappid, viberid, twitterid) values('${confirmed_regnumber}','${client_id}','NONE','NONE','NONE');`;
var error, data;
client.query(query, function(err, result) {
if (!err){
console.log("facebooid inserted");
}else {
error = err || `No record found at table`;
//callback(error, data);
console.log('unsuccessfull - db_query_select_verification_code-insert error');
}
});
}
}else {
error = err || `No record found at ${user_table_name}`;
//callback(error, data);
console.log('unsuccessfull - db_query_select_verification_code-existance_check');
}
});
}else{
console.log('verification codes not matched');
//landing page
response.render('pages/verify-facebook-invalid');
}
}else {
error = err || `No record found at table`;
//callback(error, data);
console.log('unsuccessfull - db_query_select_verification_code-norecord');
response.render('pages/verify-facebook-invalid');
}
});
}
//-------------------------------------------------------------------------------[Nodejs App to support backend of DialogFlow]--------
var express = require('express') //a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.
, bodyParser = require('body-parser'); //this is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
var http = require('http');
var request = require('request');
const path = require('path')
var fs = require('fs'); //to read files
// to format dates
var moment = require('moment');
//nodejs server online port
const PORT = process.env.PORT || 8000;
//Chatbot facebook page, access token
const FB_PAGE_ACCESS_TOKEN = 'EAAFLoV6ANvIBADadfOI0WWJ0ZBSd3cAO5Vm5GCpDYrjw4MPKu8OIh5tyv9hwHzoATCQGdM2z2xck4Mmg3kW4V8yzGQVvLCULnNC5nkGn9kLZBrQJZCPGPYZAWAFBlZB0FqBgEUYC7crwJfiQ5MuUEaViBZBzZCDq2TitfieKLuduAZDZD';
// Map of Semesters to the DB Tables
const MAP_SEMESTER_TO_DB = [
"table_current_semester_year1",
"table_current_semester_year2",
"table_current_semester_year3",
"table_current_semester_year4",
"table_current_semester_shortsem5",
"table_current_semester_shortsem6"
];
// General Elective bucket limits
const CREDITS_BUCKET_ART = 2;
const CREDITS_BUCKET_MANAGEMENT = 5;
const CREDITS_BUCKET_SOCIAL = 2;
// Array to keep GE courses
var courseManagementBucket=[], courseArtBucket=[], courseSocialBucket=[], courseCommonBucket=[];
// Array to hold the week days
var weekday=new Array(7);
weekday[0]="Monday";
weekday[1]="Tuesday";
weekday[2]="Wednesday";
weekday[3]="Thursday";
weekday[4]="Friday";
weekday[5]="Saturday";
weekday[6]="Sunday";
// Time variables
var query_by_time_current_time, query_by_time_previous_starttime, query_by_time_previous_endtime, table_to_query, query_by_time_date;
// Date variables
var query_by_day_current_day, query_by_day_next_day, query_by_day_previous_day;
// Not Registered Error Message
var registerNow = {
'data':{
"facebook": [{
"text": "Looks like you are not registered yet",
"quick_replies":[
{
"content_type":"text",
"title":"Register Now",
"payload":"Get started"
}
]
}]
}
}
var app = express(); //getting an express instance , app?
app.use(bodyParser.json());
app.set('view engine', 'pug'); // set a view engine to show reults in web browser
app.get('/', (req, res) => res.render('pages/index'));
//incomming request, resulting response
app.post('/', function(request, res){
let action = request.body.result.action; //getting the value of the action of incomming request
console.log(action);
/*
=============================================================================
Fisrt Instance user connect to the bot with Facbook Platform
Ask for the role from the user
=============================================================================
*/
if(action == 'ACTION_FB_REG_GETTINGSTARTED'){
var facebookID = request.body.originalRequest.data.sender.id;//the facebook id
console.log(facebookID);
// chech wether this is a registered user
let query = `Select registrationnumber FROM table_user_map_chatclients WHERE facebookid='${facebookID}';`;
client.query(query, function(err, result) {
if (!err && result.rows.length > 0){
// registered User
let firstMsg = ['Hi', 'Hey'];
let randomIndex = Math.floor(Math.random() * firstMsg.length);
let choosenMsg1 = firstMsg[randomIndex];
let secondMsg = ['How can I help you?',
'What do you want to know?'];
randomIndex = Math.floor(Math.random() * secondMsg.length);
let choosenMsg2 = secondMsg[randomIndex];
res.send(JSON.stringify({'messages':
[{"type": 0, "speech": choosenMsg1},
{"type": 0, "speech": choosenMsg2}]}
))
}else {
// Not registered, send introduction message
//getFacebookData function was implemented in this js file.
getFacebookData(facebookID, function(err, data){
var firstName = data.first_name; //first name, from the facebook account
var firstMsg = `Hi ${firstName}`;
res.send(JSON.stringify({'messages':
[{"type": 0, "speech": firstMsg},
{"type": 0, "speech": "I'm an Informational Chatbot for Pera Efac"},
{'title': 'To get started, tell me your role',
'replies': ['Lecturer', 'Instructor', 'Student'], 'type': 2}]}
))
});
}
});
}
if(action == 'ACTION_FB_REG_ROLE_STUDENT_ENUMBER_CONFIRMED'){ //-----------------------------------------[FB_REG_SEND_VERIFICATION]-------
var facebookID = request.body.originalRequest.data.sender.id; //the facebook id
var confirmed_regnumber=request.body.result.parameters.eNumber;//get the confirmed enumber
current_facebook_id=facebookID; //update the current facebook id
console.log('confirmed enumber : '+getCompatibleEnumber(confirmed_regnumber));
current_registrationnumber=getCompatibleEnumber(confirmed_regnumber);
//sending the verification code
db_query_get_email_from_registrationnumber_and_send_verification_email('table_user_student_feels',current_registrationnumber);
console.log('The facebook id: '+facebookID+' ; sent the confirmation email');
}
/*
=============================================================================
Actions used to Query Timetables using the time and date
date, time variables are defined GLOBAL to all the time related Actions
inorder to use in user asks (next and previous) followed by first query
=============================================================================
*/
// Need to query the DB using the time for the first time
if(action == 'ACTION_QUERY_BY_TIME_1'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
query_by_time_current_time = request.body.result.parameters.time; // time user asking
// date user asking, if not use current date
if(request.body.result.parameters.date){
query_by_time_date = moment(request.body.result.parameters.date).format('dddd');
}else {
query_by_time_date = moment(new Date()).format('dddd');
}
queryByDateAndTime(query_by_time_date, query_by_time_current_time, facebookID, function (err, data) {
if(!err){
// Extract values from data and send to user + update our reference values moment("12:15 AM", ["h:mm A"]).format("HH:mm");
query_by_time_previous_endtime = data.endtime;
query_by_time_previous_starttime = data.starttime;
let starttime = moment(data.starttime, "HH:mm:ss").format('hh:mm A');
let endtime = moment(data.endtime, "HH:mm:ss").format('hh:mm A');
var reply = {'messages':
[{"type": 0, "speech": 'You have,'},
{"type": 0, "speech": `*${data.courseid}* from _${starttime}_ to _${endtime}_`}]}
res.send(JSON.stringify(reply))
}else{
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
// Need to query the DB using the time for the second time (A next followed by 1st query)
if(action == 'ACTION_QUERY_BY_TIME_NEXT'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
console.log(query_by_time_previous_endtime);
queryByTimeNext(query_by_time_date, query_by_time_previous_endtime, facebookID, function (err, data) {
if(!err){
// Extract values from data and send to user + update our reference values
query_by_time_previous_endtime = data.endtime;
query_by_time_previous_starttime = data.starttime;
let starttime = moment(data.starttime, "HH:mm:ss").format('hh:mm A');
let endtime = moment(data.endtime, "HH:mm:ss").format('hh:mm A');
var reply = {'messages':
[{"type": 0, "speech": 'You have,'},
{"type": 0, "speech": `*${data.courseid}* from _${starttime}_ to _${endtime}_`}]}
res.send(JSON.stringify(reply))
}else {
if(err == `That's all for ${query_by_time_date}`){
let nextDay;
getNextDay(query_by_time_date, function (data) {
nextDay = data;
});
res.send(JSON.stringify({'messages':
[{'title': err,
'replies': [`Show ${nextDay} Timetable`], 'type': 2}]}
))
}else if (err == 'NOT_REGISTERED') {
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
// Need to query the DB using the time for the second time (A previous followed by 1st query)
if(action == 'ACTION_QUERY_BY_TIME_PREVIOUS'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
console.log(query_by_time_previous_starttime);
queryByTimePrevious(query_by_time_date, query_by_time_previous_starttime, facebookID, function (err, data) {
if(!err){
// Extract values from data and send to user + update our reference values
query_by_time_previous_endtime = data.endtime;
query_by_time_previous_starttime = data.starttime;
let starttime = moment(data.starttime, "HH:mm:ss").format('hh:mm A');
let endtime = moment(data.endtime, "HH:mm:ss").format('hh:mm A');
var reply = {'messages':
[{"type": 0, "speech": 'You have,'},
{"type": 0, "speech": `*${data.courseid}* from _${starttime}_ to _${endtime}_`}]}
res.send(JSON.stringify(reply))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
/*
=============================================================================
Actions used to Query Timetables using only the day
Date variables are defined GLOBAL to all the time related Actions
inorder to use in user asks (next and previous) followed by first query
=============================================================================
*/
// Need to query the DB using the day for the first time
if(action == 'ACTION_QUERY_BY_DAY_1'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
if(request.body.result.parameters.day){
query_by_day_current_day = moment(request.body.result.parameters.day).format('dddd');
}else {
query_by_day_current_day = moment(new Date()).format('dddd');
}
console.log('Current day = ' + query_by_day_current_day);
getPreviousDay(query_by_day_current_day, function (data) {
query_by_day_previous_day = data;
});
getNextDay(query_by_day_current_day, function (data) {
query_by_day_next_day = data;
});
queryByDay(query_by_day_current_day, facebookID, function (err, data) {
if(!err){
// Extract values from data and send to user + update our reference values
res.send(JSON.stringify(data))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
// Need to query the DB using the day for the second time
if(action == 'ACTION_QUERY_BY_DAY_NEXT'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
query_by_day_current_day = query_by_day_next_day; // day user asking
getPreviousDay(query_by_day_current_day, function (data) {
query_by_day_previous_day = data;
});
getNextDay(query_by_day_current_day, function (data) {
query_by_day_next_day = data;
});
queryByDay(query_by_day_current_day, facebookID, function (err, data) {
if(!err){
// Extract values from data and send to user + update our reference values
res.send(JSON.stringify(data))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
// Need to query the DB using the day for the second time
if(action == 'ACTION_QUERY_BY_DAY_PREVIOUS'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
query_by_day_current_day = query_by_day_previous_day; // day user asking
getPreviousDay(query_by_day_current_day, function (data) {
query_by_day_previous_day = data;
});
getNextDay(query_by_day_current_day, function (data) {
query_by_day_next_day = data;
});
queryByDay(query_by_day_current_day, facebookID, function (err, data) {
if(!err){
// Extract values from data and send to user + update our reference values
res.send(JSON.stringify(data))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
/*
=============================================================================
Actions used to query timetables using the courseID and date
=============================================================================
*/
// Need to query the DB using the courseID and date
if(action == 'ACTION_QUERY_BY_COURSEID_AND_DATE'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
if (request.body.result.parameters.CourseID) {
query_by_courseID_specified_courseID = request.body.result.parameters.CourseID; // courseID specified by user
query_by_courseID_specified_day = moment(request.body.result.parameters.date).format('dddd'); // day specified by user
queryByCourseID_Date(query_by_courseID_specified_courseID, query_by_courseID_specified_day,facebookID, function (err, data) {
if(!err){
// Extract values from data and send to user
res.send(JSON.stringify(data))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}else {
let courseIdNotFound = ['I think you have made a mistake in the courseID',
'Check the courseID and try again',
`I don't have that course. Check it again`];
let randomIndex = Math.floor(Math.random() * courseIdNotFound.length);
let choosenMsg = courseIdNotFound[randomIndex];
res.send(JSON.stringify({'messages': [{"type": 0, "speech": ':('},
{"type": 0, "speech": choosenMsg}]}
))
}
}
if(action == 'ACTION_QUERY_BY_COURSEID_AND_DATE_NEXT'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
let courseID = request.body.result.parameters.courseID; // courseID specified by user
let day = moment(request.body.result.parameters.date).format('dddd'); // day specified by user
let queryDay;
getNextDay(day, function (data) {
queryDay = data;
});
queryByCourseIDNextDay(courseID, queryDay, facebookID, function (err, data) {
if(!err){
// Extract values from data and send to user
let msg = `You have *${courseID}* on ${data.timetabledate}`;
res.send(JSON.stringify({'messages': [{"type": 0, "speech": msg}]}))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
/*
=============================================================================
Actions used to query timetables using the courseID
=============================================================================
*/
// Need to query the DB using the courseID
if(action == 'ACTION_QUERY_BY_COURSEID'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
// check if the courseID is present in parameters
if(request.body.result.parameters.CourseID){
query_by_courseID_specified_courseID = request.body.result.parameters.CourseID; // courseID specified by user
queryByCourseID(query_by_courseID_specified_courseID,facebookID, function (err, data) {
if(!err){
console.log(data);
// Extract values from data and send to user
res.send(JSON.stringify(data))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}else {
let courseIdNotFound = ['I think you have made a mistake in the courseID',
'Check the courseID and try again',
`I don't have that course. Check it again`];
let randomIndex = Math.floor(Math.random() * courseIdNotFound.length);
let choosenMsg = courseIdNotFound[randomIndex];
res.send(JSON.stringify({'messages': [{"type": 0, "speech": ':('},
{"type": 0, "speech": choosenMsg}]}
))
}
}
/*
=============================================================================
Actions used to Query the Timetables by next Lecture (What do i have next ?)
=============================================================================
*/
if(action == 'ACTION_QUERY_BY_NEXT_LECTURE'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
let date = moment(new Date()).format('dddd');
let time = new moment().format("HH:mm");
queryByNextLecture(date, time, facebookID, function (err, data) {
if(!err){
let starttime = moment(data.starttime, "HH:mm:ss").format('hh:mm A');
let endtime = moment(data.endtime, "HH:mm:ss").format('hh:mm A');
var reply = {'messages':
[{"type": 0, "speech": `At *${starttime}* on *${data.timetabledate}*`},
{"type": 0, "speech": `you have *${data.courseid}* until _${endtime}_`}]}
res.send(JSON.stringify(reply))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
/*
=============================================================================
Actions used to Query Timetables bu saying before or After
What do i have before the lunch ?
=============================================================================
*/
if (action == 'ACTION_QUERY_BY_BEFORE') {
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
var queryDay, queryTime;
if(request.body.result.parameters.date){
queryDay = moment(request.body.result.parameters.date).format('dddd');
}else {
queryDay = moment(new Date()).format('dddd');
}
if(request.body.result.parameters.time){
queryTime = request.body.result.parameters.time;
}else if (request.body.result.parameters.intervals) {
queryTime = request.body.result.parameters.intervals;
}else {
}
queryByBefore(facebookID, queryDay, queryTime, function (err, data) {
if(!err){
res.send(JSON.stringify(data))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
})
}
if (action == 'ACTION_QUERY_BY_AFTER') {
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
var queryDay, queryTime;
if(request.body.result.parameters.date){
queryDay = moment(request.body.result.parameters.date).format('dddd');
}else {
queryDay = moment(new Date()).format('dddd');
}
if(request.body.result.parameters.time){
queryTime = request.body.result.parameters.time;
}else if (request.body.result.parameters.intervals) {
queryTime = request.body.result.parameters.intervals;
}else {
}
queryByAfter(facebookID, queryDay, queryTime, function (err, data) {
if(!err){
res.send(JSON.stringify(data))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
})
}
/*
=============================================================================
Actions used to Query the Full Timetables
=============================================================================
*/
if(action == 'ACTION_QUERY_FULL'){
let facebookID = request.body.originalRequest.data.sender.id; // facebook id
queryFullTimeTable(facebookID, function (err, data) {
if(!err){
let path = serverPath + data;
var data = {
'data':{
"facebook": [{
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text":'Full Time Table',
"buttons": [{
"type":"web_url",
"url":`${path}`,
"title":"Show"
}]
}
}
}]
}
}
console.log(path);
//var reply = {'messages': [{"type": 0, "speech": path}]}
res.send(JSON.stringify(data))
}else {
if(err == 'NOT_REGISTERED'){
res.send(JSON.stringify(registerNow))
}else {
res.send(JSON.stringify({'messages': [{"type": 0, "speech": err}]}))
}
}
});
}
/*
=============================================================================
Actions used to give course Info
=============================================================================
*/
if(action == 'ACTION_COURSE_INFO'){
/*
Check if the course is a valid
*/
if(request.body.result.parameters.CourseID){
let courseID = request.body.result.parameters.CourseID; // course id
generalCourseInfo(courseID, function (err, data) {
if(!err){
let path = serverPath + 'course-detail?courseid=' + courseID;
var bucket = 'Categorized under,\n';
if(data.courseart){
bucket += 'Arts and Humanities\n';
}
if(data.coursemanagement){
bucket += 'Management and Economics\n';
}
if(data.coursesocial){
bucket += 'Political and Social Sciences\n';
}
var title = data.courseid + " - " + data.coursename
var description = `Credits = ${data.coursecredits}\n${bucket}`
var data = {
'data':{
"facebook": [{
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements":[{
"title": title,
"subtitle": description,
"buttons":[{