-
Notifications
You must be signed in to change notification settings - Fork 26
/
app.js
690 lines (621 loc) · 21.2 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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
/* jshint node: true, devel: true */
'use strict';
const
bodyParser = require('body-parser'),
config = require('config'),
crypto = require('crypto'),
express = require('express'),
https = require('https'),
request = require('request');
var app = express();
app.set('port', 5000);
app.set('view engine', 'ejs');
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use(express.static('public'));
/*
* Open config/default.json and set your config values before running this server.
* You can restart the *node server* without reconfiguring anything. However, whenever
* you restart *ngrok* you will receive a new random url, so you must revalidate your
* webhook url in your App Dashboard.
*/
// App Dashboard > Dashboard > click the Show button in the App Secret field
const APP_SECRET = config.get('appSecret');
// App Dashboard > Webhooks > Edit Subscription > copy whatever random value you decide to use in the Verify Token field
const VALIDATION_TOKEN = config.get('validationToken');
// App Dashboard > Messenger > Settings > Token Generation > select your page > copy the token that appears
const PAGE_ACCESS_TOKEN = config.get('pageAccessToken');
// In an early version of this bot, the images were served from the local public/ folder.
// Using an ngrok.io domain to serve images is no longer supported by the Messenger Platform.
// Github Pages provides a simple image hosting solution (and it's free)
const IMG_BASE_PATH = 'https://rodnolan.github.io/posterific-static-images/';
// make sure that everything has been properly configured
if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN)) {
console.error("Missing config values");
process.exit(1);
}
/*
* Verify that the request came from Facebook. You should expect a hash of
* the App Secret from your App Dashboard to be present in the x-hub-signature
* header field.
*
* https://developers.facebook.com/docs/graph-api/webhooks#setup
*
*/
function verifyRequestSignature(req, res, buf) {
var signature = req.headers["x-hub-signature"];
if (!signature) {
// In DEV, log an error. In PROD, throw an error.
console.error("Couldn't validate the signature.");
} else {
var elements = signature.split('=');
var method = elements[0];
var signatureHash = elements[1];
var expectedHash = crypto.createHmac('sha1', APP_SECRET)
.update(buf)
.digest('hex');
console.log("received %s", signatureHash);
console.log("exepected %s", expectedHash);
if (signatureHash != expectedHash) {
throw new Error("Couldn't validate the request signature.");
}
}
}
/*
* Verify that your validation token matches the one that is sent
* from the App Dashboard during the webhook verification check.
* Only then should you respond to the request with the
* challenge that was sent.
*/
app.get('/webhook', function(req, res) {
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === VALIDATION_TOKEN) {
console.log("[app.get] Validating webhook");
res.status(200).send(req.query['hub.challenge']);
} else {
console.error("Failed validation. Validation token mismatch.");
res.sendStatus(403);
}
});
/*
* All callbacks from Messenger are POST-ed. All events from all subscription
* types are sent to the same webhook.
*
* Subscribe your app to your page to receive callbacks for your page.
* https://developers.facebook.com/docs/messenger-platform/product-overview/setup#subscribe_app
*/
app.post('/webhook', function (req, res) {
console.log("message received!");
var data = req.body;
console.log(JSON.stringify(data));
if (data.object == 'page') {
// send back a 200 within 20 seconds to avoid timeouts
res.sendStatus(200);
// entries from multiple pages may be batched in one request
data.entry.forEach(function(pageEntry) {
// iterate over each messaging event for this page
pageEntry.messaging.forEach(function(messagingEvent) {
let propertyNames = Object.keys(messagingEvent);
console.log("[app.post] Webhook event props: ", propertyNames.join());
if (messagingEvent.message) {
processMessageFromPage(messagingEvent);
} else if (messagingEvent.postback) {
// user replied by tapping a postback button
processPostbackMessage(messagingEvent);
} else {
console.log("[app.post] not prepared to handle this message type.");
}
});
});
}
});
/*
* called when a postback button is tapped
* ie. buttons in structured messages and the Get Started button
*
* https://developers.facebook.com/docs/messenger-platform/webhook-reference/postback-received
*
*/
function processPostbackMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfPostback = event.timestamp;
// the developer-defined field you set when you create postback buttons
var payload = event.postback.payload;
console.log("[processPostbackMessage] from user (%d) " +
"on page (%d) " +
"with payload ('%s') " +
"at (%d)",
senderID, recipientID, payload, timeOfPostback);
respondToHelpRequest(senderID, payload);
}
/*
* Called when a message is sent to your page.
*
*/
function processMessageFromPage(event) {
var senderID = event.sender.id;
var pageID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("[processMessageFromPage] user (%d) page (%d) timestamp (%d) and message (%s)",
senderID, pageID, timeOfMessage, JSON.stringify(message));
if (message.quick_reply) {
console.log("[processMessageFromPage] quick_reply.payload (%s)",
message.quick_reply.payload);
handleQuickReplyResponse(event);
return;
}
// the 'message' object format can vary depending on the kind of message that was received.
// See: https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-received
var messageText = message.text;
if (messageText) {
console.log("[processMessageFromPage]: %s", messageText);
var lowerCaseMsg = messageText.toLowerCase();
switch (lowerCaseMsg) {
case 'help':
// handle 'help' as a special case
sendHelpOptionsAsQuickReplies(senderID);
break;
default:
// otherwise, just echo it back to the sender
sendTextMessage(senderID, messageText);
}
}
}
/*
* Send a message with the four Quick Reply buttons
*
*/
function sendHelpOptionsAsQuickReplies(recipientId) {
console.log("[sendHelpOptionsAsQuickReplies] Sending help options menu");
var messageData = {
recipient: {
id: recipientId
},
message: {
text: "Select a feature to learn more.",
quick_replies: [
{
"content_type":"text",
"title":"Rotation",
"payload":"QR_ROTATION_1"
},
{
"content_type":"text",
"title":"Photo",
"payload":"QR_PHOTO_1"
},
{
"content_type":"text",
"title":"Caption",
"payload":"QR_CAPTION_1"
},
{
"content_type":"text",
"title":"Background",
"payload":"QR_BACKGROUND_1"
}
]
}
};
callSendAPI(messageData);
}
/*
* user tapped a Quick Reply button; respond with the appropriate content
*
*/
function handleQuickReplyResponse(event) {
var senderID = event.sender.id;
var pageID = event.recipient.id;
var message = event.message;
var quickReplyPayload = message.quick_reply.payload;
console.log("[handleQuickReplyResponse] Handling quick reply response (%s) from sender (%d) to page (%d) with message (%s)",
quickReplyPayload, senderID, pageID, JSON.stringify(message));
// respond to the sender's help request by presenting a carousel-style
// set of screenshots of the application in action
// each response includes all the content for the requested feature
respondToHelpRequest(senderID, quickReplyPayload);
}
function respondToHelpRequest(senderID, payload) {
// set useGenericTemplates to false to send image attachments instead of generic templates
var useGenericTemplates = true;
var messageData;
if (useGenericTemplates) {
// respond to the sender's help request by presenting a carousel-style
// set of screenshots of the application in action
// each response includes all the content for the requested feature
messageData = getGenericTemplates(senderID, payload);
} else {
messageData = getImageAttachments(senderID, payload);
}
if (messageData) {
callSendAPI(messageData);
}
}
/*
* This response uses templateElements to present the user with a carousel
* You send ALL of the content for the selected feature and they swipe
* left and right to see it
*
*/
function getGenericTemplates(recipientId, requestForHelpOnFeature) {
console.log("[getGenericTemplates] handling help request for %s", requestForHelpOnFeature);
var templateElements = [];
var sectionButtons = [];
// each button must be of type postback but title
// and payload are variable depending on which
// set of options you want to provide
var addSectionButton = function(title, payload) {
sectionButtons.push({
type: 'postback',
title: title,
payload: payload
});
}
// Since there are only four options in total, we will provide
// buttons for each of the remaining three with each section.
// This provides the user with maximum flexibility to navigate
switch (requestForHelpOnFeature) {
case 'QR_ROTATION_1':
addSectionButton('Photo', 'QR_PHOTO_1');
addSectionButton('Caption', 'QR_CAPTION_1');
addSectionButton('Background', 'QR_BACKGROUND_1');
templateElements.push(
{
title: "Rotation",
subtitle: "portrait mode",
image_url: IMG_BASE_PATH + "01-rotate-landscape.png",
buttons: sectionButtons
},
{
title: "Rotation",
subtitle: "landscape mode",
image_url: IMG_BASE_PATH + "02-rotate-portrait.png",
buttons: sectionButtons
}
);
break;
case 'QR_PHOTO_1':
addSectionButton('Rotation', 'QR_ROTATION_1');
addSectionButton('Caption', 'QR_CAPTION_1');
addSectionButton('Background', 'QR_BACKGROUND_1');
templateElements.push(
{
title: "Photo Picker",
subtitle: "click to start",
image_url: IMG_BASE_PATH + "03-photo-hover.png",
buttons: sectionButtons
},
{
title: "Photo Picker",
subtitle: "Downloads folder",
image_url: IMG_BASE_PATH + "04-photo-list.png",
buttons: sectionButtons
},
{
title: "Photo Picker",
subtitle: "photo selected",
image_url: IMG_BASE_PATH + "05-photo-selected.png",
buttons: sectionButtons
}
);
break;
case 'QR_CAPTION_1':
addSectionButton('Rotation', 'QR_ROTATION_1');
addSectionButton('Photo', 'QR_PHOTO_1');
addSectionButton('Background', 'QR_BACKGROUND_1');
templateElements.push(
{
title: "Caption",
subtitle: "click to start",
image_url: IMG_BASE_PATH + "06-text-hover.png",
buttons: sectionButtons
},
{
title: "Caption",
subtitle: "enter text",
image_url: IMG_BASE_PATH + "07-text-mid-entry.png",
buttons: sectionButtons
},
{
title: "Caption",
subtitle: "click OK",
image_url: IMG_BASE_PATH + "08-text-entry-done.png",
buttons: sectionButtons
},
{
title: "Caption",
subtitle: "Caption done",
image_url: IMG_BASE_PATH + "09-text-complete.png",
buttons: sectionButtons
}
);
break;
case 'QR_BACKGROUND_1':
addSectionButton('Rotation', 'QR_ROTATION_1');
addSectionButton('Photo', 'QR_PHOTO_1');
addSectionButton('Caption', 'QR_CAPTION_1');
templateElements.push(
{
title: "Background Color Picker",
subtitle: "click to start",
image_url: IMG_BASE_PATH + "10-background-picker-hover.png",
buttons: sectionButtons
},
{
title: "Background Color Picker",
subtitle: "click current color",
image_url: IMG_BASE_PATH + "11-background-picker-appears.png",
buttons: sectionButtons
},
{
title: "Background Color Picker",
subtitle: "select new color",
image_url: IMG_BASE_PATH + "12-background-picker-selection.png",
buttons: sectionButtons
},
{
title: "Background Color Picker",
subtitle: "click ok",
image_url: IMG_BASE_PATH + "13-background-picker-selection-made.png",
buttons: sectionButtons
},
{
title: "Background Color Picker",
subtitle: "color is applied",
image_url: IMG_BASE_PATH + "14-background-changed.png",
buttons: sectionButtons
}
);
break;
}
if (templateElements.length < 2) {
console.error("each template should have at least two elements");
}
var messageData = {
recipient: {
id: recipientId
},
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: templateElements
}
}
}
};
return messageData;
}
/*
* This response uses image attachments to illustrate each step of each feature.
* This is less flexible because you are limited in the number of options you can
* provide for the user. This technique is best for cases where the content should
* be consumed in a strict linear order.
*
*/
function getImageAttachments(recipientId, helpRequestType) {
var textToSend = '';
var quickReplies = [
{
"content_type":"text",
"title":"Restart",
"payload":"QR_RESTART"
}, // this option should always be present because it allows the user to start over
{
"content_type":"text",
"title":"Continue",
"payload":""
} // the Continue option only makes sense if there is more content to show
// remove this option when you are at the end of a branch in the content tree
// i.e.: when you are showing the last message for the selected feature
];
// to send an image attachment in a message, just set the payload property of this attachment object
// if the payload property is defined, this will be added to the message before it is sent
var attachment = {
"type": "image",
"payload": ""
};
switch(helpRequestType) {
case 'QR_RESTART' :
sendHelpOptionsAsQuickReplies(recipientId);
return;
break;
// the Rotation feature
case 'QR_ROTATION_1' :
textToSend = 'Click the Rotate button to toggle the poster\'s orientation between landscape and portrait mode.';
quickReplies[1].payload = "QR_ROTATION_2";
break;
case 'QR_ROTATION_2' :
// 1 of 2 (portrait, landscape)
attachment.payload = {
url: IMG_BASE_PATH + "01-rotate-landscape.png"
}
quickReplies[1].payload = "QR_ROTATION_3";
break;
case 'QR_ROTATION_3' :
// 2 of 2 (portrait, landscape)
attachment.payload = {
url: IMG_BASE_PATH + "02-rotate-portrait.png"
}
quickReplies.pop();
quickReplies[0].title = "Explore another feature";
break;
// the Rotation feature
// the Photo feature
case 'QR_PHOTO_1' :
textToSend = 'Click the Photo button to select an image to use on your poster. We recommend visiting https://unsplash.com/random from your device to seed your Downloads folder with some images before you get started.';
quickReplies[1].payload = "QR_PHOTO_2";
break;
case 'QR_PHOTO_2' :
// 1 of 3 (placeholder image, Downloads folder, poster with image)
attachment.payload = {
url: IMG_BASE_PATH + "03-photo-hover.png"
}
quickReplies[1].payload = "QR_PHOTO_3";
break;
case 'QR_PHOTO_3' :
// 2 of 3 (placeholder image, Downloads folder, poster with image)
attachment.payload = {
url: IMG_BASE_PATH + "04-photo-list.png"
}
quickReplies[1].payload = "QR_PHOTO_4";
break;
case 'QR_PHOTO_4' :
// 3 of 3 (placeholder image, Downloads folder, poster with image)
attachment.payload = {
url: IMG_BASE_PATH + "05-photo-selected.png"
}
quickReplies.pop();
quickReplies[0].title = "Explore another feature";
break;
// the Photo feature
// the Caption feature
case 'QR_CAPTION_1' :
textToSend = 'Click the Text button to set the caption that appears at the bottom of the poster.';
quickReplies[1].payload = "QR_CAPTION_2";
break;
case 'QR_CAPTION_2' :
// 1 of 4 (hover, entering caption, mid-edit, poster with new caption)
attachment.payload = {
url: IMG_BASE_PATH + "06-text-hover.png"
}
quickReplies[1].payload = "QR_CAPTION_3";
break;
case 'QR_CAPTION_3' :
// 2 of 4: (hover, entering caption, mid-edit, poster with new caption
attachment.payload = {
url: IMG_BASE_PATH + "07-text-mid-entry.png"
}
quickReplies[1].payload = "QR_CAPTION_4";
break;
case 'QR_CAPTION_4' :
// 3 of 4 (hover, entering caption, mid-edit, poster with new caption)
attachment.payload = {
url: IMG_BASE_PATH + "08-text-entry-done.png"
}
quickReplies[1].payload = "QR_CAPTION_5";
break;
case 'QR_CAPTION_5' :
// 4 of 4 (hover, entering caption, mid-edit, poster with new caption)
attachment.payload = {
url: IMG_BASE_PATH + "09-text-complete.png"
}
quickReplies.pop();
quickReplies[0].title = "Explore another feature";
break;
// the Caption feature
// the Color Picker feature
case 'QR_BACKGROUND_1' :
textToSend = 'Click the Background button to select a background color for your poster.';
quickReplies[1].payload = "QR_BACKGROUND_2";
break;
case 'QR_BACKGROUND_2' :
// 1 of 5 (hover, entering caption, mid-edit, poster with new caption)
attachment.payload = {
url: IMG_BASE_PATH + "10-background-picker-hover.png"
}
quickReplies[1].payload = "QR_BACKGROUND_3";
break;
case 'QR_BACKGROUND_3' :
// 2 of 5 (hover, entering caption, mid-edit, poster with new caption)
attachment.payload = {
url: IMG_BASE_PATH + "11-background-picker-appears.png"
}
quickReplies[1].payload = "QR_BACKGROUND_4";
break;
case 'QR_BACKGROUND_4' :
// 3 of 5 (hover, entering caption, mid-edit, poster with new caption)
attachment.payload = {
url: IMG_BASE_PATH + "12-background-picker-selection.png"
}
quickReplies[1].payload = "QR_BACKGROUND_5";
break;
case 'QR_BACKGROUND_5' :
// 4 of 5 (hover, entering caption, mid-edit, poster with new caption)
attachment.payload = {
url: IMG_BASE_PATH + "13-background-picker-selection-made.png"
}
quickReplies[1].payload = "QR_BACKGROUND_6";
break;
case 'QR_BACKGROUND_6' :
// 5 of 5 (hover, entering caption, mid-edit, poster with new caption)
attachment.payload = {
url: IMG_BASE_PATH + "14-background-changed.png"
}
quickReplies.pop();
quickReplies[0].title = "Explore another feature";
break;
// the Color Picker feature
default :
sendHelpOptionsAsQuickReplies(recipientId);
return;
break;
}
var messageData = {
recipient: {
id: recipientId
},
message: {
text: textToSend,
quick_replies: quickReplies
},
};
if (attachment.payload !== "") {
messageData.message.attachment = attachment;
// text can not be specified when you're sending an attachment
delete messageData.message.text;
}
return messageData;
}
/*
* Send a text message using the Send API.
*
*/
function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText // utf-8, 640-character max
}
};
console.log("[sendTextMessage] %s", JSON.stringify(messageData));
callSendAPI(messageData);
}
/*
* Call the Send API. If the call succeeds, the
* message id is returned in the response.
*
*/
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: 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;
if (messageId) {
console.log("[callSendAPI] message id %s sent to recipient %s",
messageId, recipientId);
} else {
console.log("[callSendAPI] called Send API for recipient %s",
recipientId);
}
} else {
console.error("[callSendAPI] Send API call failed", response.statusCode, response.statusMessage, body.error);
}
});
}
/*
* Start your server
*/
app.listen(app.get('port'), function() {
console.log('[app.listen] Node app is running on port', app.get('port'));
});
module.exports = app;