-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
654 lines (564 loc) · 23 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
var Botkit = require('botkit');
var request = require('request');
var swearjar = require('swearjar');
var cleanser = require('profanity-cleanser');
var Sibyl = require('./sibyl');
var prefs = new Sibyl();
var userPostbacks = {};
var controller = Botkit.facebookbot({
access_token: process.env.page_access_token,
verify_token: process.env.verify_token,
});
// Imporant to set the dictionaries for cleanser
cleanser.setLocale();
var bot = controller.spawn({
});
// SERVER
controller.setupWebserver(process.env.PORT, function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
var userFirstRun = {};
// user said hello
controller.hears(['hello', '^hi$', '^yo$', '^hey$', 'what\'s up'], 'message_received', function(bot, message) { // NOTE: Change dialog, add user nickname question linked with database
if (userMatch[message.user]) {
bot.reply(userMatch[message.user], 'Matched user: ' + message.text);
} else if (!userFirstRun[message.user]) {
userFirstRun[message.user] = 'done';
bot.reply(message, "Hey there, my name is Alfred. Nice to meet you! Let's have some fun together. Try saying 'quiz', 'chat' or 'help'!");
} else {
bot.reply(message, 'Hello, nice to see you again!');
}
});
// HELP SECTION
controller.hears('^help$', 'message_received', function(bot, message) {
if (userMatch[message.user]) {
bot.reply(userMatch[message.user], 'Matched user: ' + message.text);
} else {
bot.startConversation(message,function(err,convo) {
convo.say("Here are my main commands: \n\n• Say 'quiz' or 'test' if you want to answer some questions to help me find you a chat friend \n\n• Say 'chat' or 'match' if you want to chat with someone");
convo.say("• Say 'stop' if you want to exit a dialogue \n\n• Say 'trivia' if you want to play a game! \n\n• I am also funny, sometimes. Try 'joke' or 'Chuck Norris'. \n\nThat's it, hope it helps!");
});
}
});
//The jokessss
controller.hears(['joke', 'pun', 'dad joke'], 'message_received', function(bot, message) {
if (userMatch[message.user]) {
var address = 'http://tambal.azurewebsites.net/joke/random';
request(address, function(err, result) {
var resultObject = JSON.parse(result.body);
bot.reply(userMatch[message.user], 'Matched user: ' + message.text);
bot.reply(message, 'Here is your joke: ' + resultObject.joke);
bot.reply(userMatch[message.user], 'Here is your joke: ' + resultObject.joke);
})
} else {
var address = 'http://tambal.azurewebsites.net/joke/random';
request(address, function(err, result) {
var resultObject = JSON.parse(result.body);
bot.reply(message,'Here is your joke: ' + resultObject.joke);
})
}
});
//Chuck Norris jokes
controller.hears(['chuck', 'norris', 'noris'], 'message_received', function(bot, message) {
var address = 'https://api.chucknorris.io/jokes/random';
if (userMatch[message.user]) {
request(address, function(err, result) {
var resultObject = JSON.parse(result.body);
bot.reply(userMatch[message.user], 'Matched user: ' + message.text);
bot.reply(userMatch[message.user], resultObject.value);
bot.reply(message, resultObject.value);
});
} else {
request(address, function(err, result) {
var resultObject = JSON.parse(result.body);
bot.reply(message, resultObject.value);
});
}
});
//Trivia game
controller.hears('trivia', 'message_received', function(bot, message) {
bot.startConversation(message, function(err, convo) {
var address = 'http://jservice.io/api/random';
request(address, function(err, result) {
if (err) {
console.log(err)
convo.say('Sorry, there was a problem, please try again.');
}
else {
var resultObject = JSON.parse(result.body);
var question = resultObject[0].question;
var responseTrivia = resultObject[0].answer;
if (responseTrivia.indexOf('<i>') != -1) {
responseTrivia = responseTrivia.slice(3).split('</i>')[0];
} else if (responseTrivia.indexOf('\\') != -1) {
responseTrivia = responseTrivia.replace('\\', '');
}
convo.ask('Here is your question: ' + '*' + question + '*' + '. You have 3 chances!', cancellable(function(response, convo) {
if (response.text === responseTrivia || response.text === responseTrivia.toLowerCase()) {
convo.say('Congratulations, you found the right answer!');
convo.next();
}
else {
secondTry(response, convo, responseTrivia);
convo.next();
}
}));
}
});
});
});
var counter = 2;
function secondTry(response, convo, responseTrivia) {
convo.ask('Wrong answer. Your remaining chances: ' + counter, cancellable(function(response, convo) {
counter --;
if (response.text === responseTrivia || response.text === responseTrivia.toLowerCase() && counter > 0) {
convo.say('Congratulations, you found the right answer!');
convo.next();
} else if ((response.text != responseTrivia || response.text != responseTrivia.toLowerCase()) && counter > 0) {
secondTry(response, convo, responseTrivia);
convo.next();
} else {
convo.say('Sorry, you have lost. The response was: ' + responseTrivia);
counter = 2;
convo.next();
}
}));
}
// PREFERENCES QUIZ
var thingsArray = [
{name:'Lord of the rings', url: 'http://cdn.bgr.com/2014/12/lord-of-the-rings-1-the-fellowship-of-the-ring-movie-poster-2001-1020195991.jpg'},
{name: 'Breaking Bad', url: 'http://www.ultrahdtv.net/wp-content/uploads/2013/01/Breaking-Bad.jpg'},
{name: 'Jurassic Park', url: 'http://arvernebythesea.com/wp-content/uploads/2015/07/jurrasic-park.png'},
{name: 'Electro music', url: 'http://wallpoper.com/images/00/42/41/82/music-daft_00424182.jpg'},
{name: 'Pokemon', url: 'http://www.pokemon20.com/assets/img/global/og-shareimg.jpg'},
{name: 'Titanic', url: 'http://static3.techinsider.io/image/56bcafeb6e97c631008b69e0-3179-2384/im%20on%20top%20of%20the%20world%20titanic.jpg'},
{name: 'Donald Trump', url: 'http://c10.nrostatic.com/sites/default/files/styles/original_image_with_cropping/public/uploaded/donald-trump-grow-up.jpg?itok=n1PW3Myr'},
{name: 'Harry Potter', url: 'http://nerdist.com/wp-content/uploads/2015/06/Wizarding-World-of-Harry-Potter.jpg'},
{name: 'Tom Cruise', url: 'http://cdn.mos.cms.futurecdn.net/85162ce40f2cbd0f3125fa484902af4c-970-80.jpg'},
{name: 'Apple', url: 'http://www.returnofkings.com/wp-content/uploads/2014/03/apple-icon-apple.jpg'},
{name: 'The Big Bang Theory', url: 'http://www.cutcabletoday.com/wp-content/uploads/2015/09/Big-Bang-Theory.jpg'},
{name: 'Hip Hop music', url: 'http://az616578.vo.msecnd.net/files/2016/02/27/635921315531991253560246710_publicenemy.jpg'},
{name: 'Family Guy', url: 'http://www.kdoc.tv/wp-content/uploads/2016/03/fam.jpg'},
{name: 'Google', url: 'http://www.enterprisesaskatchewan.ca/wp-content/uploads/2016/02/Is-Google-Searching-for-the-Next-Big-Thing1.jpg'},
{name: 'Fifty Shades of Grey', url: 'http://z1035.com/wp-content/uploads/2016/01/fifty-shades-grey-.jpg'},
{name: 'Lady Gaga', url: 'http://www.billboard.com/files/styles/article_main_image/public/media/lady-gaga-2015-red-carpet-headshot-billboard-650.jpg'}
];
var userVoted = {};
function sendTest(bot, message) {
var idx = Math.floor(Math.random() * (thingsArray.length)); // random index of array
var movie = thingsArray[idx];
if (!userVoted[message.user]) { // checks if userVoted for current user is created.
userVoted[message.user] = []; // if not, created it and give it an empty array
}
if (userVoted[message.user].indexOf(idx) !== -1) { // if the user already voted on the movie corresponding to the randomly generated index
if (userVoted[message.user].length === thingsArray.length) { // if the userVoted array length is the same as the moviesArray, then no more movie is available for voting
bot.reply(message, 'No more questions, you\'re done!'); // tell the user and exit the function
return;
}
sendTest(bot, message); // call sendMovieTest again to generate a new movie index
} else { // if the user never voted on the current movie, then display the vote choice
userVoted[message.user].push(idx); // push that index number into the userVoted array to make sure it doesn't come back
var randomToken = '' + Math.random();
if (!userPostbacks[message.user]) {
userPostbacks[message.user] = [];
}
userPostbacks[message.user].push(randomToken);
var attachment = {
'type': 'template',
'payload': {
'template_type': 'generic',
'elements':[
{
'title': movie.name,
'image_url': movie.url,
'subtitle': 'Do you like this ?',
'buttons': [
{
'type':'postback',
'title':'Like!',
'payload': 'POSTBACK_like_movie_' + randomToken + '_' + idx
},
{
'type':'postback',
'title':'Dislike...',
'payload':'POSTBACK_dislike_movie_' + randomToken + '_' +idx
},
{
'type': 'postback',
'title': 'STOP',
'payload': 'POSTBACK_stop_movie_' + randomToken
}
]
}
]
}
};
bot.reply(message, {
attachment: attachment,
});
}
}
controller.hears(['test', 'quiz', 'test', 'preferences'], 'message_received', function(bot, message) {
if (userMatch[message.user]) {
bot.reply(userMatch[message.user], 'Matched user: ' + message.text);
}
else {
sendTest(bot, message);
}
});
function checkToken(user, token) {
if (!userPostbacks[user]) {
return false;
}
var idx = userPostbacks[user].indexOf(token);
if (idx === -1) {
return false;
}
userPostbacks[user].splice(idx, 1);
return true;
}
controller.on('facebook_postback', function(bot, message) {
var likeRegex = /^POSTBACK_like_movie_(.+)_(\d+)$/;
var dislikeRegex = /^POSTBACK_dislike_movie_(.+)_(\d+)$/;
var stopRegex = /^POSTBACK_stop_movie_(.+)$/;
var matches = message.payload.match(likeRegex);
if (matches) {
var token = matches[1];
if (!checkToken(message.user, token)) {
return;
}
bot.reply(message, 'Ok, liked!');
prefs.recordLike(message.user, 'movie_'+matches[2]);
sendTest(bot, message);
}
else {
matches = message.payload.match(dislikeRegex);
if (matches) {
token = matches[1];
if (!checkToken(message.user, token)) {
return;
}
bot.reply(message, 'Ok, disliked!');
prefs.recordDislike(message.user, 'movie_'+matches[2]);
sendTest(bot, message);
}
else {
matches = message.payload.match(stopRegex);
if (matches) {
token = matches[1];
if (!checkToken(message.user, token)) {
return;
}
bot.reply(message, 'OK, I will stop asking you questions for now!');
}
}
}
});
// middleware to cancel a conversation
function cancellable(callback) {
var stopPattern = {
pattern: '^(cancel|stop)$',
callback: function(message, convo) {
convo.stop();
}
};
if (Array.isArray(callback)) {
return callback.concat(stopPattern);
}
return [
{
default: true,
callback: callback
},
stopPattern
];
}
var matches = {};
var dontChat = {};
controller.hears('^stop$', 'message_received', function(bot, message) {
var randomToken = '' + Math.random();
if (!userPostbacks[message.user]) {
userPostbacks[message.user] = [];
}
userPostbacks[message.user].push(randomToken);
if (userMatch[message.user]) {
bot.reply(message, 'Ok, I will remove you from the conversation!');
bot.reply(userMatch[message.user], 'You and the other user have been disconnected.');
var matched = userMatch[message.user];
userMatch[message.user] = null;
userMatch[matched.user] = null;
var attachment = {
'type': 'template',
'payload': {
'template_type':'button',
'text': 'Why did you want to leave?',
'buttons': [
{
'type':'postback',
'title':'I have to go..',
'payload':'POSTBACK_chatstop_gtg_'+randomToken
},
{
'type':'postback',
'title':'Didn\'t like the user',
'payload':'POSTBACK_chatstop_dislike_'+randomToken+'_'+matched.user
}
]
}
};
bot.reply(message, {
attachment: attachment,
});
}
});
controller.on('facebook_postback', function(bot, message) {
var gtgRegex = /^POSTBACK_chatstop_gtg_(.+)$/;
var dislikeRegex = /^POSTBACK_chatstop_dislike_(.+)_(\d+)$/;
// or make it into an object
// if (typeof message.payload !== 'string') {
// return;
// }
var matches = message.payload.match(gtgRegex);
if (matches) {
var token = matches[1];
if (!checkToken(message.user, token)) {
return;
}
bot.reply(message, 'Ok, I understand! :)');
}
else {
var matches = message.payload.match(dislikeRegex);
if (matches && matches.length === 2) {
var token = matches[1];
if (!checkToken(message.user, token)) {
return;
}
if (!dontChat[message.user]) {
dontChat[message.user] = [];
}
dontChat[message.user].push(matches[1]);
bot.reply(message, 'Ok, I\'m going to make sure that you don\'t end up in a chat with this person again in the future.');
}
}
});
// CHAT : IF NOT IN CONVO, CALL MATCHING OPTIONS MENU
controller.hears(['^match$', '^chat$', '^friend$'], 'message_received', function(bot, message) {
if (userMatch[message.user]) {
bot.reply(message, 'You are already in a conversation!');
return;
} else {
sendMatchingOptions(bot, message);
}
});
// MATCHING OPTIONS MENU
function sendMatchingOptions(bot, message) {
var randomToken = '' + Math.random();
if (!userPostbacks[message.user]) {
userPostbacks[message.user] = [];
}
userPostbacks[message.user].push(randomToken);
var attachment = {
'type': 'template',
'payload': {
'template_type':'button',
'text': 'How accurately would you like to be matched with another user (based on your quiz preferences)? Keep in mind that a higher match can also mean a longer waiting time!',
'buttons': [
{
'type':'postback',
'title':'Very good match',
'payload': 'POSTBACK_very_good_match_'+randomToken
},
{
'type':'postback',
'title':'OK match',
'payload':'POSTBACK_ok_match_'+randomToken
},
{
'type': 'postback',
'title': 'Randomly',
'payload': 'POSTBACK_random_match_'+randomToken
}
]
}
};
bot.reply(message, {
attachment: attachment,
});
}
// Pools for matches
var wantsVeryGoodMatch = [];
var wantsOkMatch = [];
var wantsWhateverMatch = [];
controller.on('facebook_postback', function(bot, message) {
var veryGoodRegex = /^POSTBACK_very_good_match_(.+)$/;
var okRegex = /^POSTBACK_ok_match_(.+)$/;
var randomRegex = /^POSTBACK_random_match_(.+)$/;
var matches = message.payload.match(veryGoodRegex);
if (matches) {
var token = matches[1];
if (!checkToken(message.user, token)) {
return;
}
var choice = 'wantsVeryGoodMatch';
pushingUserIntoChosenPool(bot, message, wantsVeryGoodMatch, choice);
}
else {
matches = message.payload.match(okRegex);
if (matches) {
token = matches[1];
if (!checkToken(message.user, token)) {
return;
}
choice = 'wantsOkMatch';
pushingUserIntoChosenPool(bot, message, wantsOkMatch, choice);
}
else {
matches = message.payload.match(randomRegex);
if (matches) {
token = matches[1];
if (!checkToken(message.user, token)) {
return;
}
choice = 'wantsWhateverMatch';
pushingUserIntoChosenPool(bot, message, wantsWhateverMatch, choice);
}
}
}
});
// PUSHING USERS INTO THE RIGHT POOL (ACCORDING TO CHOICE)
function pushingUserIntoChosenPool(bot, message, array, choice) {
var userPrefsArray = [];
for (var users in prefs.users) {
userPrefsArray.push(users);
}
if (userPrefsArray.indexOf(message.user) === -1) { // if no prefs, send user to wantsWhateverMatch array
bot.reply(message, 'Sorry. Since I can\'t find any of your preferences, I will have to match you randomly. Please consider taking a quiz if you want better results. :)');
bot.reply(message, 'Please wait while I find you a matching user to chat with!');
choice = 'wantsWhateverMatch';
wantsWhateverMatch.push(message);
findingPairings(bot, message, wantsWhateverMatch, choice);
} else {
bot.reply(message, 'Alright, please wait while I find you a matching user to chat with!');
array.push(message);
findingPairings(bot, message, array, choice);
}
}
// COMPARING LIKES AND DISLIKES, MATCHING WITH SIBYL
var userMatch = {};
function findingPairings(bot, message, array, choice) {
if (array.length > 1) {
var u1 = message.user;
var possiblePairs = [];
array.forEach(function(u2) {
var u2Session = u2;
u2 = u2.user;
if (choice === 'wantsVeryGoodMatch') { // SIBYL RESULT >= 0.6
console.log('THE SIMILARITY BETWEEN ' + u1 + ' and ' + u2 + ' is :' + prefs.getSimilarityBetween(u1, u2));
if ((prefs.getSimilarityBetween(u1, u2) >= 0.6) && (u1 !== u2)) {
var pair = {
id: u2,
score: prefs.getSimilarityBetween(u1, u2),
session: u2Session
};
possiblePairs.push(pair);
}
}
else if (choice === 'wantsOkMatch') { // SIBYL RESULT >= 0.2
console.log('THE SIMILARITY BETWEEN ' + u1 + ' and ' + u2 + ' is :' + prefs.getSimilarityBetween(u1, u2));
if ((prefs.getSimilarityBetween(u1, u2) >= 0.2) && (prefs.getSimilarityBetween(u1, u2) < 0.6) && (u1 !== u2)) {
var pair = {
id: u2,
score: prefs.getSimilarityBetween(u1, u2),
session: u2Session
};
possiblePairs.push(pair);
}
}
else if (choice === 'wantsWhateverMatch') {
if (u2 && (u1 !== u2)) { // MATCH WITH ANY OTHER USER WHO WANTS A RANDOM MATCH
var pair = {
id: u2,
session: u2Session
};
possiblePairs.push(pair);
}
}
});
if (possiblePairs.length > 1) {
possiblePairs.sort(function(a, b) {
return b.score - a.score;
});
matching(bot, message, array, u1, possiblePairs[0].id, possiblePairs[0].session);
}
else if (possiblePairs.length === 1) {
matching(bot, message, array, u1, possiblePairs[0].id, possiblePairs[0].session);
}
} else {
console.log('only one person in match array');
return;
}
}
// actual matching function
function matching(bot, message, array, u1, u2, u2Session) {
if (array.indexOf(message) !== -1) { // remove users from the pool
var index = array.indexOf(message);
array.splice(index, 1);
}
if (array.indexOf(u2Session) !== -1) {
var index = array.indexOf(u2Session);
array.splice(index, 1);
}
userMatch[message.user] = u2Session; // match the selected pairing
userMatch[u2] = message;
bot.reply(message, 'You are now in contact with another user!');
bot.reply(message, 'You can type \'stop\' at any time to exit the conversation.');
bot.reply(userMatch[message.user], 'You are now in contact with another user!');
bot.reply(userMatch[message.user], 'You can type \'stop\' at any time to exit the conversation.');
}
// SWEARJAR
var repliesProfane = ['Watch that mouth of yours!', 'You\'re quite a potty mouth!', 'Let\'s be civilized.', 'Hey, that\'s not nice!']; // more/better replies?
var replacementWords = [':)',':D',':poop:','<(")']; // find more?
var jar = {};
function randomNumber (thingToCheck) {
return Math.round(Math.random() * (thingToCheck.length - 1) + 0);
}
function jarOfShame(message, userJar) {
var index = randomNumber(repliesProfane);
bot.reply(message, repliesProfane[index] + '\nYou owe me ' + (userJar * 2) + '$');
}
// Censoring swears during a convo, replacing them with random emoji.
// Also catches every word that the bot hears, either for sending them in a chat,
// or saying 'I don't understand', when a word doesn't have an assigned command
controller.hears('.*', 'message_received', function(bot, message) {
if (swearjar.profane(message.text)) {
if (jar[message.user] && !/^POSTBACK_/.test(message.text)) { // JAR
jar[message.user] = jar[message.user] + 1;
jarOfShame(message, jar[message.user]);
if (userMatch[message.user] && !/^POSTBACK_/.test(message.text)) { // if matched, also send censored message
var inputString = message.text.toLowerCase();
var replaceWords = randomNumber(replacementWords);
var output = cleanser.replace(inputString, 'word', replacementWords[replaceWords]);
bot.reply(userMatch[message.user], 'Matched user: ' + output);
}
} else {
jar[message.user] = 1;
jarOfShame(message, jar[message.user]);
if (userMatch[message.user] && !/^POSTBACK_/.test(message.text)) { // if matched, also send censored message
var inputString = message.text.toLowerCase();
var replaceWords = randomNumber(replacementWords);
var output = cleanser.replace(inputString, 'word', replacementWords[replaceWords]);
bot.reply(userMatch[message.user], 'Matched user: ' + output);
}
}
}
else {
if (userMatch[message.user] && !/^POSTBACK_/.test(message.text)) {
bot.reply(userMatch[message.user], 'Matched user: ' + message.text); // put nickname instead of matched user if available?
}
else if (!/^POSTBACK_/.test(message.text)) {
bot.reply(message, "I'm sorry, I didn't understand... Say 'help' if you need to know more about me!");
}
}
});