This repository has been archived by the owner on Feb 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbot.js
330 lines (295 loc) · 9.75 KB
/
bot.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//
// This is main file containing code implementing the Express server and functionality for the Express echo bot.
//
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const path = require('path');
const crypto = require('crypto');
var messengerButton = "<html><head><title>Facebook Messenger Bot</title></head><body><h1>Facebook Messenger Bot</h1>This is a bot based on Messenger Platform QuickStart. For more details, see their <a href=\"https://developers.facebook.com/docs/messenger-platform/guides/quick-start\">docs</a>.<script src=\"https://button.glitch.me/button.js\" data-style=\"glitch\"></script><div class=\"glitchButton\" style=\"position:fixed;top:20px;right:20px;\"></div></body></html>";
// The rest of the code implements the routes for our Express server.
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Webhook validation
app.get('/webhook', function(req, res) {
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === process.env.VERIFY_TOKEN) {
console.log("Validating webhook");
res.status(200).send(req.query['hub.challenge']);
} else {
console.error("Failed validation. Make sure the validation tokens match.");
res.sendStatus(403);
}
});
// Display the web page
app.use('/', express.static('build'));
// Message processing
app.post('/webhook', function (req, res) {
console.log(req.body);
var data = req.body;
// Make sure this is a page subscription
if (data.object === 'page') {
// Iterate over each entry - there may be multiple if batched
data.entry.forEach(function(entry) {
var pageID = entry.id;
var timeOfEvent = entry.time;
// Iterate over each messaging event
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
} else if (event.postback) {
receivedPostback(event);
} else {
console.log("Webhook received unknown event: ", event);
}
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know
// you've successfully received the callback. Otherwise, the request
// will time out and we will keep trying to resend.
return res.sendStatus(200);
}
return res.status(404).json({ message: 'Invalid body' });
});
// Incoming events handling
function receivedMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
// If we receive a text message, check to see if it matches a keyword
// and send back the template example. Otherwise, just echo the text we received.
switch (messageText) {
case 'Test':
case 'test':
callFindAPI(senderID);
break;
case 'generic':
sendGenericMessage(senderID);
break;
case 'Upcoming':
sendUpcomingEvents(senderID);
break;
default:
sendTextMessage(senderID, messageText + '? How dare you!?');
}
} else if (messageAttachments) {
sendTextMessage(senderID, "Message with attachment received");
}
}
function receivedPostback(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfPostback = event.timestamp;
// The 'payload' param is a developer-defined field which is set in a postback
// button for Structured Messages.
var payload = event.postback.payload;
console.log("Received postback for user %d and page %d with payload '%s' " +
"at %d", senderID, recipientID, payload, timeOfPostback);
// When a postback is called, we'll send a message back to the sender to
// let them know it was successful
sendTextMessage(senderID, "Postback called");
}
//////////////////////////
// Sending helpers
//////////////////////////
function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function sendUpcomingEvents(recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: [{
title: "Intro to Looker",
subtitle: "HQ-Faff",
item_url: "https://beta2.meetup.com/hq-faff/events/239166532/",
image_url: "https://a248.e.akamai.net/secure.meetupstatic.com/photo_api/event/rx500x600/dt7700c8xff7900/sgc1b4a5c271/451682323.jpeg",
buttons: [{
type: "web_url",
url: "http://beta2.meetup.com/hq-faff/events/239166532/",
title: "RSVP"
}, {
type: "postback",
title: "Call Postback",
payload: "Suggest",
}],
}, {
title: "Hope Is Found In The Darkside",
subtitle: "New York Rebellion and Hope",
item_url: "https://beta2.meetup.com/New-York-Rebellion-and-Hope/events/239511681/",
image_url: "https://a248.e.akamai.net/secure.meetupstatic.com/photo_api/event/rx500x600/dtff005axffae00/sgaad0c8105b/460399292.jpeg",
buttons: [{
type: "web_url",
url: "https://beta2.meetup.com/New-York-Rebellion-and-Hope/events/239511681/",
title: "RSVP"
}, {
type: "postback",
title: "Suggest",
payload: "callback",
}]
}]
}
}
}
};
callSendAPI(messageData);
}
function sendGenericMessage(recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: [{
title: "rift",
subtitle: "Next-generation virtual reality",
item_url: "https://www.oculus.com/en-us/rift/",
image_url: "http://messengerdemo.parseapp.com/img/rift.png",
buttons: [{
type: "web_url",
url: "https://www.oculus.com/en-us/rift/",
title: "Open Web URL"
}, {
type: "postback",
title: "Call Postback",
payload: "Payload for first bubble",
}],
}, {
title: "touch",
subtitle: "Your Hands, Now in VR",
item_url: "https://www.oculus.com/en-us/touch/",
image_url: "http://messengerdemo.parseapp.com/img/touch.png",
buttons: [{
type: "web_url",
url: "https://www.oculus.com/en-us/touch/",
title: "Open Web URL"
}, {
type: "postback",
title: "Call Postback",
payload: "Payload for second bubble",
}]
}]
}
}
}
};
callSendAPI(messageData);
}
function buildGenericMessage(recipientId, elements) {
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: elements,
}
}
}
};
callSendAPI(messageData);
}
function generateDuotone(keyPhoto, photoGradient) {
if (!keyPhoto) {
return process.env.HOST_URL + '/fallback_blue.png';
}
var duotone = 'dt' + photoGradient.dark_color + 'x' + photoGradient.light_color;
var spec = 'event/rx500x600/' + duotone + '/';
var base = 'https://a248.e.akamai.net/secure.meetupstatic.com/photo_api/';
var duotoneUrl = base + spec + keyPhoto.id + '.jpeg';
return duotoneUrl;
}
function callFindAPI(recipientId) {
request({
uri: 'https://api.dev.meetup.com/find/upcoming_events',
qs: {
key: process.env.MEETUP_API_TOKEN,
fields: 'group_photo_gradient,group_key_photo',
page: '6',
ordering: 'time',
},
method: 'GET',
json: true,
}, function (error, response, body) {
if (error) {
console.error("Unable to send message.");
console.error(response);
console.error(error);
} else {
var upcomingEvents = body.events.map(event => ({
title: event.name,
subtitle: event.group.name,
item_url: event.link,
image_url: generateDuotone(event.group.key_photo, event.group.photo_gradient),
buttons: [{
type: 'web_url',
title: 'RSVP',
url: event.link,
}, {
type: 'postback',
title: 'Suggest',
payload: 'Payload Callback',
}]
}));
buildGenericMessage(recipientId, upcomingEvents);
}
});
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: process.env.PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
// Set Express to listen out for HTTP requests
var server = app.listen(process.env.PORT || 3000, function () {
console.log("Listening on port %s", server.address().port);
});