forked from howdyai/botkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
facebook_bot.js
executable file
·589 lines (498 loc) · 19.8 KB
/
facebook_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
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
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
______ ______ ______ __ __ __ ______
/\ == \ /\ __ \ /\__ _\ /\ \/ / /\ \ /\__ _\
\ \ __< \ \ \/\ \ \/_/\ \/ \ \ _"-. \ \ \ \/_/\ \/
\ \_____\ \ \_____\ \ \_\ \ \_\ \_\ \ \_\ \ \_\
\/_____/ \/_____/ \/_/ \/_/\/_/ \/_/ \/_/
This is a sample Facebook bot built with Botkit.
This bot demonstrates many of the core features of Botkit:
* Connect to Facebook's Messenger APIs
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
for a user.
# RUN THE BOT:
Follow the instructions here to set up your Facebook app and page:
-> https://developers.facebook.com/docs/messenger-platform/implementation
Run your bot from the command line:
app_secret=<MY APP SECRET> page_token=<MY PAGE TOKEN> verify_token=<MY_VERIFY_TOKEN> node facebook_bot.js [--lt [--ltsubdomain LOCALTUNNEL_SUBDOMAIN]]
Use the --lt option to make your bot available on the web through localtunnel.me.
# USE THE BOT:
Find your bot inside Facebook to send it a direct message.
Say: "Hello"
The bot will reply "Hello!"
Say: "who are you?"
The bot will tell you its name, where it running, and for how long.
Say: "Call me <nickname>"
Tell the bot your nickname. Now you are friends.
Say: "who am I?"
The bot will tell you your nickname, if it knows one for you.
Say: "shutdown"
The bot will ask if you are sure, and then shut itself down.
Make sure to invite your bot into other channels using /invite @<my bot>!
# EXTEND THE BOT:
Botkit has many features for building cool and useful bots!
Read all about it here:
-> http://howdy.ai/botkit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if (!process.env.page_token) {
console.log('Error: Specify page_token in environment');
process.exit(1);
}
if (!process.env.verify_token) {
console.log('Error: Specify verify_token in environment');
process.exit(1);
}
if (!process.env.app_secret) {
console.log('Error: Specify app_secret in environment');
process.exit(1);
}
var Botkit = require('../lib/Botkit.js');
var os = require('os');
var commandLineArgs = require('command-line-args');
var localtunnel = require('localtunnel');
const ops = commandLineArgs([
{name: 'lt', alias: 'l', args: 1, description: 'Use localtunnel.me to make your bot available on the web.',
type: Boolean, defaultValue: false},
{name: 'ltsubdomain', alias: 's', args: 1,
description: 'Custom subdomain for the localtunnel.me URL. This option can only be used together with --lt.',
type: String, defaultValue: null},
]);
if(ops.lt === false && ops.ltsubdomain !== null) {
console.log("error: --ltsubdomain can only be used together with --lt.");
process.exit();
}
var controller = Botkit.facebookbot({
debug: true,
log: true,
access_token: process.env.page_token,
verify_token: process.env.verify_token,
app_secret: process.env.app_secret,
validate_requests: true, // Refuse any requests that don't come from FB on your receive webhook, must provide FB_APP_SECRET in environment variables
});
var bot = controller.spawn({
});
controller.setupWebserver(process.env.port || 3000, function(err, webserver) {
controller.createWebhookEndpoints(webserver, bot, function() {
console.log('ONLINE!');
if(ops.lt) {
var tunnel = localtunnel(process.env.port || 3000, {subdomain: ops.ltsubdomain}, function(err, tunnel) {
if (err) {
console.log(err);
process.exit();
}
console.log("Your bot is available on the web at the following URL: " + tunnel.url + '/facebook/receive');
});
tunnel.on('close', function() {
console.log("Your bot is no longer available on the web at the localtunnnel.me URL.");
process.exit();
});
}
});
});
/**
* FaceBook Personas API
*/
controller.hears('get all personas', 'message_received', function(bot, message) {
controller.api.personas.get_all_personas()
.then(result => {
bot.startTyping({
channel : message.channel,
persona_id : result.id
});
result.data.forEach((persona) => {
bot.reply(message, {
'text' : 'Message send from ' + persona.name + ' at ' + new Date().toISOString(),
'persona_id' : persona.id
});
});
})
.catch(reason => {
bot.reply(message, "Oops something was wrong");
});
});
controller.hears('delete latest persona', 'message_received', function(bot, message) {
controller.api.personas.get_all_personas()
.then(result => {
if(result.data.length > 0) {
var persona = result.data[result.data.length - 1];
controller.api.personas.delete_persona(persona.id)
.then(result => {
bot.reply(message, 'Done, the persona ' + persona.name + ' is deleted');
});
} else {
bot.reply(message, 'No persona found to delete');
}
})
.catch(reason => {
bot.reply(message, "Oops something was wrong");
});
});
controller.hears(['create persona'], 'message_received', function(bot, message) {
controller.api.personas.create({
'name': 'Botkit',
'profile_picture_url': 'https://pbs.twimg.com/profile_images/803642201653858305/IAW1DBPw_400x400.png'
})
.then(result => {
bot.reply(message, {
'text' : 'Hello from the new created persona :)',
'persona_id' : result.id
});
})
.catch(reason => {
bot.reply(message, "Oops something was wrong");
});
});
/**
* End of FaceBook Personas API
*/
controller.hears(['attachment_upload'], 'message_received', function(bot, message) {
var attachment = {
"type":"image",
"payload":{
"url":"https://pbs.twimg.com/profile_images/803642201653858305/IAW1DBPw_400x400.png",
"is_reusable": true
}
};
controller.api.attachment_upload.upload(attachment, function (err, attachmentId) {
if(err) {
// Error
} else {
var image = {
"attachment":{
"type":"image",
"payload": {
"attachment_id": attachmentId
}
}
};
bot.reply(message, image);
}
});
});
controller.api.nlp.enable();
controller.api.messenger_profile.greeting('Hello! I\'m a Botkit bot!');
controller.api.messenger_profile.get_started('sample_get_started_payload');
controller.api.messenger_profile.menu([{
"locale":"default",
"composer_input_disabled":true,
"call_to_actions":[
{
"title":"My Skills",
"type":"nested",
"call_to_actions":[
{
"title":"Hello",
"type":"postback",
"payload":"Hello"
},
{
"title":"Hi",
"type":"postback",
"payload":"Hi"
}
]
},
{
"type":"web_url",
"title":"Botkit Docs",
"url":"https://github.com/howdyai/botkit/blob/master/readme-facebook.md",
"webview_height_ratio":"full"
}
]
},
{
"locale":"zh_CN",
"composer_input_disabled":false
}
]);
// controller.api.messenger_profile.account_linking('https://www.yourAwesomSite.com/oauth?response_type=code&client_id=1234567890&scope=basic');
// controller.api.messenger_profile.get_account_linking(function (err, accountLinkingUrl) {
// console.log('****** Account linkink URL :', accountLinkingUrl);
// });
// controller.api.messenger_profile.delete_account_linking();
// controller.api.messenger_profile.domain_whitelist('https://localhost');
// controller.api.messenger_profile.domain_whitelist(['https://127.0.0.1', 'https://0.0.0.0']);
// controller.api.messenger_profile.delete_domain_whitelist('https://localhost');
// controller.api.messenger_profile.delete_domain_whitelist(['https://127.0.0.1', 'https://0.0.0.0']);
// controller.api.messenger_profile.get_domain_whitelist(function (err, data) {
// console.log('****** Whitelisted domains :', data);
// });
// returns the bot's messenger code image
controller.hears(['code'], 'message_received,facebook_postback', function(bot, message) {
controller.api.messenger_profile.get_messenger_code(2000, function (err, url) {
if(err) {
// Error
} else {
var image = {
"attachment":{
"type":"image",
"payload":{
"url": url
}
}
};
bot.reply(message, image);
}
});
});
controller.hears(['quick'], 'message_received', function(bot, message) {
bot.reply(message, {
text: 'Hey! This message has some quick replies attached.',
quick_replies: [
{
"content_type": "text",
"title": "Yes",
"payload": "yes",
},
{
"content_type": "text",
"title": "No",
"payload": "no",
}
]
});
});
controller.hears(['^hello', '^hi'], 'message_received,facebook_postback', function(bot, message) {
controller.storage.users.get(message.user, function(err, user) {
if (user && user.name) {
bot.reply(message, 'Hello ' + user.name + '!!');
} else {
bot.reply(message, 'Hello.');
}
});
});
controller.hears(['silent push reply'], 'message_received', function(bot, message) {
reply_message = {
text: "This message will have a push notification on a mobile phone, but no sound notification",
notification_type: "SILENT_PUSH"
}
bot.reply(message, reply_message)
})
controller.hears(['no push'], 'message_received', function(bot, message) {
reply_message = {
text: "This message will not have any push notification on a mobile phone",
notification_type: "NO_PUSH"
}
bot.reply(message, reply_message)
})
controller.hears(['structured'], 'message_received', function(bot, message) {
bot.startConversation(message, function(err, convo) {
convo.ask({
attachment: {
'type': 'template',
'payload': {
'template_type': 'generic',
'elements': [
{
'title': 'Classic White T-Shirt',
'image_url': 'http://petersapparel.parseapp.com/img/item100-thumb.png',
'subtitle': 'Soft white cotton t-shirt is back in style',
'buttons': [
{
'type': 'web_url',
'url': 'https://petersapparel.parseapp.com/view_item?item_id=100',
'title': 'View Item'
},
{
'type': 'web_url',
'url': 'https://petersapparel.parseapp.com/buy_item?item_id=100',
'title': 'Buy Item'
},
{
'type': 'postback',
'title': 'Bookmark Item',
'payload': 'White T-Shirt'
}
]
},
{
'title': 'Classic Grey T-Shirt',
'image_url': 'http://petersapparel.parseapp.com/img/item101-thumb.png',
'subtitle': 'Soft gray cotton t-shirt is back in style',
'buttons': [
{
'type': 'web_url',
'url': 'https://petersapparel.parseapp.com/view_item?item_id=101',
'title': 'View Item'
},
{
'type': 'web_url',
'url': 'https://petersapparel.parseapp.com/buy_item?item_id=101',
'title': 'Buy Item'
},
{
'type': 'postback',
'title': 'Bookmark Item',
'payload': 'Grey T-Shirt'
}
]
}
]
}
}
}, function(response, convo) {
// whoa, I got the postback payload as a response to my convo.ask!
convo.next();
});
});
});
controller.on('facebook_postback', function(bot, message) {
// console.log(bot, message);
bot.reply(message, 'Great Choice!!!! (' + message.payload + ')');
});
controller.hears(['call me (.*)', 'my name is (.*)'], 'message_received', function(bot, message) {
var name = message.match[1];
controller.storage.users.get(message.user, function(err, user) {
if (!user) {
user = {
id: message.user,
};
}
user.name = name;
controller.storage.users.save(user, function(err, id) {
bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
});
});
});
controller.hears(['what is my name', 'who am i'], 'message_received', function(bot, message) {
controller.storage.users.get(message.user, function(err, user) {
if (user && user.name) {
bot.reply(message, 'Your name is ' + user.name);
} else {
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('I do not know your name yet!');
convo.ask('What should I call you?', function(response, convo) {
convo.ask('You want me to call you `' + response.text + '`?', [
{
pattern: 'yes',
callback: function(response, convo) {
// since no further messages are queued after this,
// the conversation will end naturally with status == 'completed'
convo.next();
}
},
{
pattern: 'no',
callback: function(response, convo) {
// stop the conversation. this will cause it to end with status == 'stopped'
convo.stop();
}
},
{
default: true,
callback: function(response, convo) {
convo.repeat();
convo.next();
}
}
]);
convo.next();
}, {'key': 'nickname'}); // store the results in a field called nickname
convo.on('end', function(convo) {
if (convo.status == 'completed') {
bot.reply(message, 'OK! I will update my dossier...');
controller.storage.users.get(message.user, function(err, user) {
if (!user) {
user = {
id: message.user,
};
}
user.name = convo.extractResponse('nickname');
controller.storage.users.save(user, function(err, id) {
bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
});
});
} else {
// this happens if the conversation ended prematurely for some reason
bot.reply(message, 'OK, nevermind!');
}
});
}
});
}
});
});
controller.hears(['shutdown'], 'message_received', function(bot, message) {
bot.startConversation(message, function(err, convo) {
convo.ask('Are you sure you want me to shutdown?', [
{
pattern: bot.utterances.yes,
callback: function(response, convo) {
convo.say('Bye!');
convo.next();
setTimeout(function() {
process.exit();
}, 3000);
}
},
{
pattern: bot.utterances.no,
default: true,
callback: function(response, convo) {
convo.say('*Phew!*');
convo.next();
}
}
]);
});
});
controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'], 'message_received',
function(bot, message) {
var hostname = os.hostname();
var uptime = formatUptime(process.uptime());
bot.reply(message,
':|] I am a bot. I have been running for ' + uptime + ' on ' + hostname + '.');
});
controller.on('message_received', function(bot, message) {
bot.reply(message, 'Try: `what is my name` or `structured` or `call me captain`');
return false;
});
controller.hears(['tags'], 'message_received', function (bot, message) {
controller.api.tags.get_all(function (tags) {
for (var i = 0; i < tags.data.length; i++) {
bot.reply(message, tags.data[i].tag + ': ' + tags.data[i].description);
}
});
});
controller.hears(['send tagged message'], 'message_received', function (bot, message) {
var taggedMessage = {
"text": "Hello Botkit !",
"tag": "RESERVATION_UPDATE"
};
bot.reply(message, taggedMessage);
});
controller.hears(['send messaging type'], 'message_received', function (bot, message) {
var taggedMessage = {
"text": "Hello Botkit !",
"messaging_type": "UPDATE"
};
bot.reply(message, taggedMessage);
});
controller.hears(['insights'], 'message_received', function (bot, message) {
controller.api.insights.get_insights(['page_messages_active_threads_unique', 'page_messages_blocked_conversations_unique'], null, null, function (err, body) {
if (err) {
bot.reply(message, 'Insights error');
} else {
bot.reply(message, JSON.stringify(body.data));
}
});
});
function formatUptime(uptime) {
var unit = 'second';
if (uptime > 60) {
uptime = uptime / 60;
unit = 'minute';
}
if (uptime > 60) {
uptime = uptime / 60;
unit = 'hour';
}
if (uptime != 1) {
unit = unit + 's';
}
uptime = uptime + ' ' + unit;
return uptime;
}