app.js
2.51 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
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));
// Server index page
app.get("/", function (req, res) {
res.send("Deployed!");
});
// Facebook Webhook
// Used for verification
app.get("/webhook", function (req, res) {
if (req.query["hub.verify_token"] === "process.env.VERIFICATION_TOKEN") {
console.log("Verified webhook");
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Verification failed. The tokens do not match.");
res.sendStatus(403);
}
});
// All callbacks for Messenger will be POST-ed here
app.post("/webhook", function (req, res) {
// Make sure this is a page subscription
if (req.body.object == "page") {
// Iterate over each entry
// There may be multiple entries if batched
req.body.entry.forEach(function(entry) {
// Iterate over each messaging event
entry.messaging.forEach(function(event) {
if (event.postback) {
processPostback(event);
}
});
});
res.sendStatus(200);
}
});
function processPostback(event) {
var senderId = event.sender.id;
var payload = event.postback.payload;
if (payload === "Greeting") {
// Get user's first name from the User Profile API
// and include it in the greeting
request({
url: "https://graph.facebook.com/v2.6/" + senderId,
qs: {
access_token: process.env.PAGE_ACCESS_TOKEN,
fields: "first_name"
},
method: "GET"
}, function(error, response, body) {
var greeting = "";
if (error) {
console.log("Error getting user's name: " + error);
} else {
var bodyObj = JSON.parse(body);
name = bodyObj.first_name;
greeting = "Hi " + name + ". ";
}
var message = greeting + "My name is SP Movie Bot. I can tell you various details regarding movies. What movie would you like to know about?";
sendMessage(senderId, {text: message});
});
}
}
// sends message to user
function sendMessage(recipientId, message) {
request({
url: "https://graph.facebook.com/v2.6/me/messages",
qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
method: "POST",
json: {
recipient: {id: recipientId},
message: message,
}
}, function(error, response, body) {
if (error) {
console.log("Error sending message: " + response.error);
}
});
}