controller.js
2.64 KB
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
let request = require('request'),
template = require('./template');
// Handles message events
exports.handleMessage = (sender_psid, received_message) => {
}
exports.handlePostback = (sender_psid, received_postback) => {
let response;
// Get the payload for the postback
let payload = received_postback.payload;
// Set the response based on the postback payload
if(payload === 'Greeting'){
response = template.greetingTemplate();
callSendAPI(sender_psid, response);
}else if(payload.substr(0,14)=== 'CHOICE_BY_PROF'){
handlePostback_choiceByProf(sender_psid, received_postback);
}else if(payload.substr(0,14)=== 'CHOICE_BY_LECT'){
handlePostback_choiceByLect(sender_psid, recieved_postback);
}else if(payload.substr(0,14) ==='CHOICE_BY_HELP'){
handlePostback_help(sender_psid, recieved_postback);
}
}
const handlePostback_choiceByProf = (sender_psid, received) => {
let response;
let stat = received.payload.substr(14);
if(stat === 'stat_0'){
response = template.getProfNameTemplate(received);
}else if(stat === 'stat_1'){
response = template.choiceLectOfProfTemplate(received);
}else if(stat === 'stat_2'){
response = template.rateTemplate(received);
}
callSendAPI(sender_psid, response);
}
const handlePostback_choiceByLect = (sender_psid, recieved) => {
let response;
let stat = recieved.payload.substr(14);
if(stat === 'stat_0'){
response = template.getLectNameTemplate(received);
}else if(stat === 'stat_1'){
response = template.choiceLectTemplate(received);
}else if(stat === 'stat_2'){
response = template.choiceProfOfLectTemplate(received);
}else if(stat === 'stat_3'){
response = template.rateTemplate(received);
}else if(stat === 'stat_4'){
response = template.goToChoiceByProfTemplate(received);
}
callSendAPI(sender_psid, response);
}
const handlePostback_help = (sender_psid, received) => {
let response;
let stat = received.payload.substr(14);
if(stat === 'stat_0'){
response = template.howToTemplate(received);
}else if(stat === 'stat_1'){
response = template.goToGreetTemplate(received);
}
callSendAPI(sender_psid, response);
}
// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {
console.log('response:'+response);
// Send the HTTP request to the Messenger Platform
request({
"url": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": process.env.PAGE_ACCESS_TOKEN },
"method": "POST",
"json": {
recipient: {id: sender_psid},
message: response
}
}, (err, res, body) => {
if (err) {
console.error("Unable to send message:" + err);
}
});
}