-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
770 lines (631 loc) Β· 25.3 KB
/
index.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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
'use strict'
var redis = require('redis')
var redisClient = redis.createClient(6379, "ec2-35-160-109-188.us-west-2.compute.amazonaws.com")
redisClient.on("connect", function(){console.log('connected')})
var https = require('https')
var PAGE_TOKEN = "EAAPaEOjibZBkBAPRV91xJyQzh4hCdo1MD1QIwZBgMkNEI2ah9FQObF9QTvSJ5ulVaLRX5L5Jdvr1tGL5S895dQX77BwDR2UbTxbZBgZBw3gSA1yEIXujMYDWobzDlhs76NHuZCfklMEN06ghXRWzttlTLWxrahcRFfRn0ZAuZCizgZDZD"
var VERIFY_TOKEN = "my_awesome_token"
// load from causes.txt instead
var causes = [
{
title: "Gun Rights",
image_url:"https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg",
subtitle: "The right for people to own arms.",
buttons: [
{
type: "postback",
title: "Choose Gun Rights",
payload: "UserSelectedCause.Gun Rights"
},
{
type: "web_url",
url: "https://en.wikipedia.org/wiki/Tree#/media/File:Ash_Tree_-_geograph.org.uk_-_590710.jpg",
title: "Wikipedia"
},
{
type: "web_url",
url: "https://en.wikipedia.org/wiki/Tree#/media/File:Ash_Tree_-_geograph.org.uk_-_590710.jpg",
title: "Visit Website"
}]
},
{
title: "Abortion Rights",
image_url:"https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg",
subtitle: "The right to freely have an abortion.",
buttons: [
{
type: "postback",
payload: "UserSelectedCause.Abortion Rights",
title: "Choose Abortion Rights"
},
{
type: "web_url",
url: "https://en.wikipedia.org/wiki/Tree#/media/File:Ash_Tree_-_geograph.org.uk_-_590710.jpg",
title: "Wikipedia"
},
{
type: "web_url",
url: "https://en.wikipedia.org/wiki/Tree#/media/File:Ash_Tree_-_geograph.org.uk_-_590710.jpg",
title: "Visit Website"
}]
},
{
title: "Presidential Elections",
image_url:"https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg",
subtitle: "The US Presidential Election",
buttons: [
{
type: "postback",
payload: "UserSelectedCause.Presidential Elections",
title: "Choose Presidential Elections"
},
{
type: "web_url",
url: "https://en.wikipedia.org/wiki/Tree#/media/File:Ash_Tree_-_geograph.org.uk_-_590710.jpg",
title: "Wikipedia"
},
{
type: "web_url",
url: "https://en.wikipedia.org/wiki/Tree#/media/File:Ash_Tree_-_geograph.org.uk_-_590710.jpg",
title: "Visit Website "
}]
},
{
title: "Some Other Hot Cause",
image_url:"https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg",
subtitle: "The blah blah blah",
buttons: [
{
type: "postback",
payload: "UserSelectedCause.Some Other Cause",
title: "Choose Some Other Cause"
},
{
type: "web_url",
url: "https://en.wikipedia.org/wiki/Tree#/media/File:Ash_Tree_-_geograph.org.uk_-_590710.jpg",
title: "Wikipedia"
},
{
type: "web_url",
url: "https://en.wikipedia.org/wiki/Tree#/media/File:Ash_Tree_-_geograph.org.uk_-_590710.jpg",
title: "Visit Website "
}]
}
]
var graph =
{"NONE":
{"DonationTrade": {nextVertex: "donationTradeStarted", f: function(options) {
var stateVariables = {state: options.state, cause: options.cause, alignment: options.alignment}
quickReplies(options.sender,
"Hello. Care to do a donation trade?",
["Yes", "No", "Huh?"],
"donationTradeStarted")
stateVariables.state = "donationTradeStarted"
return stateVariables
}}
},
"donationTradeStarted":
{"Yes": {nextVertex: "CauseSelection", f: function(options) {
var stateVariables = {state: options.state, cause: options.cause, alignment: options.alignment}
sendTextMessage(options.sender, "Please select a cause that you care about")
carousel(options.sender, causes, "CauseSelection")
// quickReplies(options.sender,
// "Fantastic. Now choose the cause you care most about. And do be honest.",
// ["Gun Rights", "Abortion Rights"],
// "CauseSelection")
stateVariables.state = "CauseSelection"
return stateVariables
}},
"No": {nextVertex: "NONE", f: function(options) {
var stateVariables = {state: options.state, cause: options.cause, alignment: options.alignment}
sendTextMessage(options.sender, "In that case, I must bid you farewell. If you ever want to " +
"engage in a donation trade just write 'donation trade'. Farewell!")
stateVariables.state = ""
stateVariables.cause = ""
stateVariables.alignment = ""
return stateVariables
}},
"Huh?": {nextVertex: "donationTradeStarted", f: function(options) {
var stateVariables = {state: options.state, cause: options.cause, alignment: options.alignment}
sendTextMessage(options.sender, "Let me do my best to explain donation trading. When two people disagree strongly " +
"about a hot bed cause like abortion or gun rights, instead of donating to causes that cancel each other out, they can " +
"both donate to highly effective charities that they find agreeable. " +
"In a way, they are agreeing to disagree and work towards a common good.")
// This is the way to automatically hop to another point in the graph.
// I need to have a pause between this line and the next step. Otherwise, it interferes with Facebook's instant reply buttons
return graph["NONE"]["DonationTrade"].f({sender: options.sender,
state: options.state,
cause: options.cause,
alignment: options.alignment})
}}
},
"CauseSelection":
{"Cause": {nextVertex: "AlignmentSelection", f: function(options) {
var stateVariables = {state: options.state, cause: options.cause, alignment: options.alignment}
quickReplies(options.sender,
"Extraordinary choice. Tell me, how do you really feel about it?",
["Very For", "Neutral", "Very Against"],
"AlignmentSelection")
stateVariables.state = "AlignmentSelection"
stateVariables.cause = options.answer
return stateVariables
}}
},
"AlignmentSelection":
{"Alignment": {nextVertex: "ConfirmTrade", f: function(options) {
var stateVariables = {state: options.state, cause: options.cause, alignment: options.alignment}
sendButtons(options.sender,
"Confirm Trade",
"Do you want to post the trade?",
["Yes", "No"],
"ConfirmTrade")
stateVariables.state = "ConfirmTrade"
stateVariables.alignment = options.answer
return stateVariables
}}
},
"ConfirmTrade":
{"Yes": {nextVertex: "", f: function(options) {
var stateVariables = {state: options.state, cause: options.cause, alignment: options.alignment}
var matchFound = false
sendTextMessage(options.sender, "ββββββTrade Postedββββββ")
console.log("Lrange Started")
redisClient.lrange('MoralTrade:awaitingMatches', 0, -1, function(err, matches) {
// matches = matches.map(function(x){JSON.parse(x)}) is equivalent to the 3 lines below
for (var i = 0; i < matches.length; i++) {
matches[i] = JSON.parse(matches[i])
}
console.log("Matches: " + matches)
// One idea for the future: The total list of alignments should be a huge list of different
// alignments and you specify how many different alignments you want for the application.
var alignments = ["Very For", "Neutral", "Very Against"]
var oppositeAlignment = alignments[(alignments.length-1) - alignments.indexOf(options.alignment)]
console.log("1: " + options.alignment)
console.log("2: " + alignments.indexOf(options.alignment))
console.log("2: " + oppositeAlignment)
console.log("loop started***")
for (var i = 0; i < matches.length; i++) {
console.log("Remove: " + JSON.stringify(matches[i]))
console.log("Matches[i]: " + matches[i])
console.log("Matches keys: " + Object.keys(matches[i]))
console.log("loop: " + i)
console.log("match.cause: " + matches[i].cause)
console.log("options.cause: " + options.cause)
console.log("match.alignment: " + matches[i].alignment)
console.log("opposite alignment: " + oppositeAlignment)
if (matches[i].cause == options.cause && matches[i].alignment == oppositeAlignment) {
console.log("We have a match!")
// For some reason, when a match is found, there is an extra entry in the DB...
redisClient.lrem('MoralTrade:awaitingMatches', 1, JSON.stringify(matches[i]))
// sendTextMessage(options.sender, "You got a match!!!") // The person who is currently posting the trade
sendTextMessage(matches[i].sender, "You got a match!!!") // The person who posted the trade earlier
// Initiate payments workflow
matchFound = true
break
}
}
})
console.log("Lrange ended")
if (!matchFound) {
redisClient.lpush(["MoralTrade:awaitingMatches", JSON.stringify({sender: options.sender, cause: options.cause, alignment: options.alignment})])
}
stateVariables.state = "" //Should be MatchFinding
stateVariables.cause = ""
stateVariables.alignment = ""
return stateVariables
// The next state will be match finding and then after that finances...
}}
},
"ERROR":
{"ERROR": {nextVertex: "", f: function(options) {
sendTextMessage(options.sender, "Sorry, I didn't catch that.")
if (options.state == "NONE") {
// sendTextMessage(options.sender, "")
var newStateVariables = graph["NONE"]["DonationTrade"].f({sender: options.sender,
state: options.state,
cause: options.cause,
alignment: options.alignment})
return newStateVariables
} else if (options.cause == "") {
// set state to cause selection
var newStateVariables = graph["donationTradeStarted"]["Yes"].f({sender: options.sender,
state: options.state,
cause: options.cause,
alignment: options.alignment})
return newStateVariables
} else if (options.alignment == "") {
// set state to alignment selection
var newStateVariables = graph["CauseSelection"]["Cause"].f({sender: options.sender,
state: options.state,
cause: options.cause,
alignment: options.alignment})
return newStateVariables
} else {
// Set state to confirmation
sendTextMessage(options.sender, "Ready to go. Do you want to confirm?")
var newStateVariables = graph["AlignmentSelection"]["Alignment"].f({sender: options.sender,
state: options.state,
cause: options.cause,
alignment: options.alignment})
return newStateVariables
}
}}
}
}
// Turn this into a function
exports.handler = (event, context, callback) => {
// process GET request
if(event.params && event.params.querystring){
var queryParams = event.params.querystring
var rVerifyToken = queryParams['hub.verify_token']
if (rVerifyToken === VERIFY_TOKEN) {
var challenge = queryParams['hub.challenge']
callback(null, parseInt(challenge))
} else{
callback(null, 'Error, wrong validation token')
}
// process POST request
} else{
var messagingEvents = event.entry[0].messaging
for (var i = 0; i < messagingEvents.length; i++) {
var messagingEvent = messagingEvents[i]
var sender = messagingEvent.sender.id
var userInput = ""
setGreetingText(sender)
////////////////////////
// The goal is to have 3 sections
// 1) Receive Inputs. inputs = an array of all inputs including button and text inputs.
// 2) Determine intent of all inputs.
// 3) Select next state based on strongest intent.
////////////////////////////////////
// Receive Inputs
// If any event happens
if (messagingEvent.message) {
// sendTextMessage(sender, "Event")
}
// If a user sends text
if (messagingEvent.message && messagingEvent.message.text) {
var text = messagingEvent.message.text
userInput = text
// If the user sends text by clicking a quick reply button
if (messagingEvent.message.quick_reply) {
// Need a try statement here
userInput = messagingEvent.message.quick_reply.payload.split(".")[1]
}
callback(null, "Done")
}
// If a user clicks a button
if (messagingEvent.postback) {
userInput = messagingEvent.postback.payload.split(".")[1]
console.log("Reached")
console.log(userInput)
}
console.log("intent processing started")
////////////////////////////////////
// Intent Processing
// This would be a good use case for wit.ai
var answer = userInput
if (userInput != "") {
switch (userInput) {
case "donation trade":
case "dt":
case "Donation Trade":
case "Trade":
case "Donation trade":
answer = "DonationTrade"
break
case "Yes":
case "yes":
case "si":
case "yup":
case "y":
answer = "Yes"
break
case "No":
case "no":
case "n":
case "nope":
case "Nope":
answer = "No"
break
case "Gun Rights":
case "Guns":
case "guns":
case "gun":
// case "":
// case "":
answer = "Gun Rights"
break
case "Abortion Rights":
case "abortions":
// case "":
// case "":
// case "":
answer = "Abortion Rights"
break
case "Elections":
case "Presidential Elections":
// case "":
// case "":
// case "":
answer = "Presidential Elections"
break
case "Very For":
// case "":
// case "":
// case "":
// case "":
answer = "Very For"
break
case "Neutral":
// case "":
// case "":
// case "":
// case "":
answer = "Neutral"
break
case "Very Against":
// case "":
// case "":
// case "":
// case "":
answer = "Very Against"
break
default:
// answer = "00000000000000000"
}
}
console.log("intent processing cleared")
////////////////////////////////////
// State Selection
// sendTextMessage(sender, "Program running")
if (answer != "") {
// Get state
// sender: 1108136689268764
// redisClient.set("MoralTrade:" + sender, JSON.stringify({sender:1108136689268764, state:"", cause: "", alignment: ""}))
console.log("Sender: " + sender)
redisClient.get("MoralTrade:" + sender, function(err, reply) {
// I think the issue with testing is that when you try to get MoralTrade:ID, for a new ID, the values are nil.
// so try to console.log(userData) for a random ID as sender and see what it says. Let that value be XXX.
// If (userData == XXX) { init the values to blank ie ""}
var userData = JSON.parse(reply);
console.log("USER DATA:" + JSON.stringify(userData))
// userData = null in the case of a new user using the bot
if (userData == null) {
userData = {sender: sender, state: "", cause: "", alignment: ""}
}
//These are the stateVariables that control the flow of the program
var state = userData.state
var cause = userData.cause
var alignment = userData.alignment
var vertex
var listOfCauses = ["Presidential Elections", "Gun Rights", "Abortion Rights"]
var listOfAlignments = ["Very For", "Neutral", "Very Against"]
if (inList(listOfCauses, answer)) {
vertex = "Cause"
} else if (inList(listOfAlignments, answer)) {
vertex = "Alignment"
} else {
vertex = answer
}
// state = "" in the case of the start of a donation trade (either new user or restarting)
if (state == "" || state == undefined) {
state = "NONE"
}
console.log("State:" + state)
console.log("answer:" + answer)
console.log("Graph:" + JSON.stringify(graph))
if (inList(Object.keys(graph[state]), vertex)) {
// This is the fundamental graph operation
var stateVariables = graph[state][vertex].f({sender: sender,
state: state,
cause: cause,
alignment: alignment,
answer: answer})
// state = graph[state][answer].nextVertex
state = stateVariables.state
cause = stateVariables.cause
alignment = stateVariables.alignment
} else {
console.log("error hit")
var stateVariables = graph["ERROR"]["ERROR"].f({sender: sender,
state: state,
cause: cause,
alignment: alignment,
answer: answer})
console.log("stateVariables" + stateVariables)
state = stateVariables.state
cause = stateVariables.cause
alignment = stateVariables.alignment
}
console.log("Setting started")
redisClient.set("MoralTrade:" + sender, JSON.stringify({"sender": sender, "state": state, "cause": cause, "alignment": alignment}))
console.log("Setting ended")
});
}
////////////////////////////////////
}
callback(null, event)
}
}
function sendTextMessage(sender, text) {
var json = {
recipient: {id: sender},
message: {text: text},
}
var body = JSON.stringify(json)
var path = '/v2.6/me/messages?access_token=' + PAGE_TOKEN
var options = {
host: "graph.facebook.com",
path: path,
method: 'POST',
headers: {'Content-Type': 'application/json'}
}
httpRequestHelper(body, options)
}
// Called with carousel(sender, causes, "")
function carousel(sender, options, state) {
var json = {
recipient: { id:sender },
message: {
attachment: {
type: "template",
payload: {
template_type: "generic",
elements: []
}
}
}
}
// In the future it might be a link to a wikipedia article, infographics, how many people have donated, maybe a way to contact
// People who voted a certain way... etc.
for (var i = 0; i < options.length; i++) {
json.message.attachment.payload.elements.push(options[i])
}
var body = JSON.stringify(json)
var path = '/v2.6/me/messages?access_token=' + PAGE_TOKEN
var options = {
host: "graph.facebook.com",
path: path,
method: 'POST',
headers: {'Content-Type': 'application/json'}
}
httpRequestHelper(body, options)
}
function sendButtons(sender, title, subtitle, buttons, state) {
var json = {
recipient: {id: sender},
message: {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": title,
"subtitle": subtitle,
"buttons": [],
}]
}
}
},
}
for (var i = 0; i < buttons.length; i++) {
json.message.attachment.payload.elements[0].buttons.push({"type": "postback",
"title": buttons[i],
"payload": state + "." + buttons[i]}
)
}
var body = JSON.stringify(json)
var path = '/v2.6/me/messages?access_token=' + PAGE_TOKEN
var options = {
host: "graph.facebook.com",
path: path,
method: 'POST',
headers: {'Content-Type': 'application/json'}
}
httpRequestHelper(body, options)
}
function quickReplies(sender, titleText, quickReplies, state) {
var json = {
recipient: {id: sender},
"message":{
"text": titleText,
"quick_replies":[]
}
}
for (var i = 0; i < quickReplies.length; i++) {
json.message.quick_replies.push({content_type: "text",
title: quickReplies[i],
payload: state + "." + quickReplies[i]}
)
}
var body = JSON.stringify(json)
var path = '/v2.6/me/messages?access_token=' + PAGE_TOKEN
var options = {
host: "graph.facebook.com",
path: path,
method: 'POST',
headers: {'Content-Type': 'application/json'}
}
var callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk
})
response.on('end', function () {
})
}
var req = https.request(options, callback)
req.on('error', function(e) {
console.log('problem with request: '+ e)
})
req.write(body)
req.end()
}
function setGreetingText(sender) {
var json = {
setting_type:"greeting",
greeting:{
"text":"Timeless apparel for the masses."
}
}
var body = JSON.stringify(json)
var path = '/v2.6/me/thread_settings?access_token=' + PAGE_TOKEN
var options = {
host: "graph.facebook.com",
path: path,
method: 'POST',
headers: {'Content-Type': 'application/json'}
}
httpRequestHelper(body, options)
}
function setTyping(sender, setting) {
var json = {
recipient: {id: sender},
sender_action: "typing_" + setting,
}
var body = JSON.stringify(json)
var path = '/v2.6/me/messages?access_token=' + PAGE_TOKEN
var options = {
host: "graph.facebook.com",
path: path,
method: 'POST',
headers: {'Content-Type': 'application/json'}
}
httpRequestHelper(body, options)
}
function httpRequestHelper(body, options) {
var callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk
})
response.on('end', function () {
})
}
var req = https.request(options, callback)
req.on('error', function(e) {
console.log('problem with request: '+ e)
})
req.write(body)
req.end()
}
function inList(list, el) {
// Another way to do inList:
// [1,2,3,4,5].reduce(function(x, y) {return (x === true || y == 0)}, false)
// list.reduce(function(x, y) {return (x === true || y == el)}, false)
var i = 0
while (i < list.length) {
if (list[i] === el) {
return true
}
i += 1
}
return false
}
//π π π€ ββββββ
// MVP:
// - Add a greeting
// Planned Features
// - Intelligent intent processing
// - Multiple responses and a method for randomly choosing them.