-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
209 lines (187 loc) · 6.91 KB
/
app.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
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var db = mongoose.connect(process.env.MONGODB_URI);
var Movie = require("./models/movie");
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) {
// hub.verify_token
if (req.query["hub.verify_token"] === process.env.VARIFICATION_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);
} else if (event.message) {
processMessage(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 + "Hi! I'm a robot that Malthe made. I can tell you various details regarding movies. What movie would you like to know about?";
sendMessage(senderId, {text: message});
});
} else if (payload === "Correct") {
sendMessage(senderId, {text: "Awesome! What would you like to find out? Enter 'plot', 'date', 'runtime', 'director', 'cast' or 'rating' for the various details."});
} else if (payload === "Incorrect") {
sendMessage(senderId, {text: "Oops! Sorry about that. Try using the exact title of the movie"});
}
}
function processMessage(event) {
// Make sure the message wasnt from our selves.
if (!event.message.is_echo) {
var message = event.message;
var senderId = event.sender.id;
console.log("Received message from senderId: " + senderId);
console.log("Message is: " + JSON.stringify(message));
// You may get a text or attachment but not both
if (message.text) {
var formattedMsg = message.text.toLowerCase().trim();
// If we receive a text message, check to see if it matches any special
// keywords and send back the corresponding movie detail.
// Otherwise, search for new movie.
switch (formattedMsg) {
case "plot":
case "date":
case "runtime":
case "director":
case "cast":
case "rating":
getMovieDetail(senderId, formattedMsg);
break;
default:
findMovie(senderId, formattedMsg);
}
} else if (message.attachments) {
sendMessage(senderId, {text: "Sorry, I don't understand your request."});
}
}
}
function findMovie(userId, movieTitle) {
request("http://www.omdbapi.com/?apikey=bd757374&type=movie&t=" + movieTitle, function (error, response, body) {
if (!error && response.statusCode == 200) {
var movieObj = JSON.parse(body);
if (movieObj.Response === "True") {
var query = {user_id: userId};
var update = {
user_id: userId,
title: movieObj.Title,
plot: movieObj.Plot,
date: movieObj.Released,
runtime: movieObj.Runtime,
director: movieObj.Director,
cast: movieObj.Actors,
rating: movieObj.imdbRating,
poster_url:movieObj.Poster
};
var options = {upsert: true};
Movie.findOneAndUpdate(query, update, options, function(err, mov) {
if (err) {
console.log("Database error: " + err);
} else {
message = {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: [{
title: movieObj.Title,
subtitle: "Is this the movie you are looking for?",
image_url: movieObj.Poster === "N/A" ? "http://placehold.it/350x150" : movieObj.Poster,
buttons: [{
type: "postback",
title: "Yes",
payload: "Correct"
}, {
type: "postback",
title: "No",
payload: "Incorrect"
}]
}]
}
}
};
sendMessage(userId, message);
}
});
} else {
console.log(movieObj.Error);
sendMessage(userId, {text: movieObj.Error});
}
} else {
sendMessage(userId, {text: "Something went wrong. Try again."});
}
});
}
function getMovieDetail(userId, field) {
Movie.findOne({user_id: userId}, function(err, movie) {
if(err) {
sendMessage(userId, {text: "Something went wrong. Try again"});
} else {
sendMessage(userId, {text: movie[field]});
}
});
}
// 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);
}
});
}