-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
279 lines (251 loc) · 11.4 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
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
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));
/*** Index Page ***/
//Index page
app.get("/", function (req, res) {
res.send("OMDb chatbot is up and running.");
});
/*** Facebook Messenger Handling ***/
//Facebook webhook used for verification
app.get("/webhook", function (req, res) {
if (req.query["hub.verify_token"] === process.env.VERIFICATION_TOKEN) {
console.log("Webhook verified");
res.status(200).send(req.query["hub.challenge"]);
}
else {
console.log("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
if(entry.messaging != undefined) {
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 + "My name is OMDb Movie Bot. 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', 'genre', 'date', 'runtime', 'director', 'cast' or 'rating' for the various details. \n \nBetter, type back 'everything' and I will get you everything about this movie." });
} else if (payload === "Incorrect") {
sendMessage(senderId, { text: "Oops! Sorry about that. Try using the exact title of the movie." });
}
}
function processMessage(event) {
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;
case "everything":
getEntireMovieDetail(senderId);
break;
default:
checkOwnName(senderId, formattedMsg);
}
} else if (message.attachments) {
sendMessage(senderId, { text: "Sorry, I don't understand your request. You can ask me about movies.\n\nOr if you're feeling lucky, type 'who', 'code', 'developer' etc." });
}
}
}
function checkOwnName(senderId, message) {
if(message.indexOf("darpan") !== -1 || message.indexOf("creat") !== -1
|| message.indexOf("develop") !== -1 || message.indexOf("author") !== -1 ) {
sendMessage(senderId, { text: "Hey there, Darpan here.\n\nI noticed that you've mentioned my name. In case if you're wondering, yes I have programmed this bot. Pretty cool, yeah? \n\nYou can know more about me at www.darpandodiya.com"});
}
else if(message.indexOf("who") !== -1 && message.indexOf("you") !== -1) {
sendMessage(senderId, { text: "I'm just a bot. :)\n\nI run on commands of a guy named Darpan. Type Darpan to know more."});
}
else if(message.indexOf("source") !== -1 || message.indexOf("code") !== -1 ) {
sendMessage(senderId, { text: "Yep, I'm open source. Find me on GitHub at: https://github.com/darpandodiya/omdb-fb-bot"});
}
else if(message == "hi" || message == "hello" || message == "hey") {
sendMessage(senderId, { text: "Hey. How're you doing today?"});
}
else if(message == "fine") {
sendMessage(senderId, { text: "Cool. I'm good as well. Though, on a side note, bots are always in good mood anything. :P"});
}
else if(message.indexOf("satyam") !== -1 || message.indexOf("ankit") !== -1) {
sendMessage(senderId, { text: "Yo bitches. The bot is trolling you."});
}
else if(message == "what do you do") {
sendMessage(senderId, { text: "I fetch info about movies. Type back any more name."});
}
else {
findMovie(senderId, 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);
}
});
}
/*** MongoDB & OMDb Handling ***/
var mongoose = require("mongoose");
var db = mongoose.connect(process.env.MONGODB_URI);
var Movie = require("./models/movie");
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] });
}
});
}
function getEntireMovieDetail(userId) {
Movie.findOne({ user_id: userId }, function (err, movie) {
if (err) {
sendMessage(userId, { text: "Something went wrong. Try again" });
} else {
sendMessage(userId, { text: movie["title"] + " : " + movie["year"] + "\n\n"
+ movie["title"] + " is a movie released in " + movie["year"] + ", directed by " + movie["director"] + ".\n\n"
+ "Here's its plot: " + movie["plot"] + + "\n\n"
+ "Genre: " + movie["genre"] + "\n\n"
+ "Cast: " + movie["cast"] + "\n\n"
+ "The movie was rated " + movie["imdb_rating"] + " at IMDb and given " + movie["metascore"] + " Metascore." + "\n\n"
+ "It was produced by " + movie["production"] + ". " + movie["title"] + " earned " + movie["box_office"] + " at the box office." + "\n\n"
+ "Here's its official website: " + movie["website_url"]
});
}
});
}
function findMovie(userId, movieTitle) {
console.log("In findMovie. userId: " + userId + " movieTitle: " + movieTitle);
var requestUrl = "http://www.omdbapi.com/?t=" + movieTitle + "&apikey=7e0bbc93";
console.log(requestUrl);
request(requestUrl, 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,
year: movieObj.Year,
release_date: movieObj.Released,
runtime: movieObj.Runtime,
genre: movieObj.Genre,
director: movieObj.Director,
cast: movieObj.Actors,
plot: movieObj.Plot,
language: movieObj.Language,
country: movieObj.Country,
awards: movieObj.Awards,
poster_url: movieObj.Poster,
metascore: movieObj.Metascore,
imdb_rating: movieObj.imdbRating,
imdb_id: movieObj.imdbID,
box_office: movieObj.BoxOffice,
production: movieObj.Production,
website_url: movieObj.Website,
};
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 + " " + movieObj.Year,
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: "Something went wrong with OMDb API. Please try again. \n\nOr if you're feeling lucky, type 'who', 'code', 'developer' etc." });
}
} else {
sendMessage(userId, { text: "Something went wrong with OMDb API. Please try again. \n\nOr if you're feeling lucky, type 'who', 'code', 'developer' etc." });
}
});
}