controller.js
1.92 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
let request = require('request'),
template = require('./template'),
config = require('config');
// Views - handle Message, handle Postback
// Handles message events
exports.handleMessage = (sender_psid, received_message) => {
let response;
if(received_message.text){
// Create the payload for a basic text message
response = template.askTemplate()
}
// Sends the reponse message
callSendAPI(sender_psid, response);
}
// Handle postback(=button) events
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 === 'CAT_PICS') {
response = template.imageTemplate('cats', sender_psid);
callSendAPI(sender_psid, response, function(){
callSendAPI(sender_psid, template.askTemplate('Show me more'));
});
} else if (payload === 'DOG_PICS') {
response = template.imageTemplate('dogs', sender_psid);
callSendAPI(sender_psid, response, function(){
callSendAPI(sender_psid, template.askTemplate('Show me more'));
});
} else if(payload === 'GET_STARTED'){
response = template.greetingTemplate();
callSendAPI(sender_psid, response);
}
// Send the message to acknowledge the postback
}
// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
};
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": config.get('facebook.page.access_token') },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
if(cb){
cb();
}
} else {
console.error("Unable to send message:" + err);
}
});
}