-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
1382 lines (1288 loc) · 39 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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
//------FIREBASE SETUP ----
/** Firebase **/
var admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.cert({
//project id etc. is to written here.
}),
//storageBucket and database url is to be written here
});
//----------
app.set('port', (process.env.PORT || 5000))
//processing the data
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
//routes
app.get('/', function(req, res){
res.send("Hello World! -Mohsin")
})
let token = "sometokenvalue"
//facebook connect
app.get('/webhook/', function(req, res){
if(req.query['hub.verify_token'] === "mohsinhayat"){
res.send(req.query['hub.challenge'])
}
res.send("Wrong Token")
})
function firstEntity(nlp, name) {
return nlp && nlp.entities && nlp.entities[name] && nlp.entities[name][0];
}
app.post('/webhook/', function(req, res){
let messaging_events = req.body.entry[0].messaging
for(let i = 0; i<messaging_events.length; i++){
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
if (event.postback) {
let text = JSON.stringify(event.postback)
sendMarkSeen(sender)
sendTypingOn(sender)
sendTypingOff(sender)
//sendText(sender, "Postback received: "+text.substring(0, 200), token)
if(event.postback.payload === 'CONTACT_INFO_PAYLOAD'){
sendContactInfo(sender)
}
if(event.postback.payload === 'viewReceipt'){
sendReceipt(sender)
}
if(event.postback.payload === 'viewCart'){
sendCart(sender)
}
if(event.postback.payload.includes("productOrder_")){
let prdo = event.postback.payload.slice(13, event.postback.payload.length)
var itemCount = 0
pushOrder(sender, prdo, 1)
getUserCart(event.sender.id)
.then((prdC) => {
sendText(sender, "You have successfully added \"" + prdo + "\" to your cart. Press Order Multiple times to add more quantity.")
//sendText(sender, JSON.stringify(prdC))
var arr = [];
Object.keys(prdC).forEach(function(key) {
var found = false;
for(var i = 0; i<arr.length; i++){
if(arr[i] === prdC[key].product){
found = true;
break;
}
}
if(!found)
{
itemCount++;
}
arr.push(prdC[key].product);
});
sendCartInfo(sender, itemCount)
})
}
if(event.postback.payload === 'PROFILE_PAYLOAD'){
getUserProfile(event.sender.id)
.then((cuser) => {
let profMsg = '';
if(cuser.Name.value!=null){
profMsg += "\nName: " + cuser.Name.value
}
if(cuser.University.value!=null){
profMsg += "\nUniversity: " + cuser.University.value
}
if(cuser.Phone.value!=null){
profMsg += "\nPhone #: " + cuser.Phone.value
}
profMsg = profMsg + "\nOrder Count: 0"
sendText(sender, "We have your profile saved with us: " + profMsg)
})
}
if(event.postback.payload === 'HISTORY_PAYLOAD'){
sendText(sender, "Ye feature abhi testing k marahil main hai.")
}
if(event.postback.title === 'Get Started'){
//sendText(sender, "Purzey ko choose krnay ka shukria.")
askShuruKrain(sender)
}
if(event.postback.payload === 'shuru'){
//sendText(sender, "Purzey ko choose krnay ka shukria.")
//askShuruKrain(sender)
askUniversity(sender)
}
continue
}
if(event.message.attachments){
//sendText(sender, "Adding: " + event.message.attachments[0].title)
if(event.message.attachments[0].title){
getProduct(event.message.attachments[0].title)
.then((prd) => {
if(prd !== null){
productOffer(sender, prd)
}
})
}
}
if(event.message && event.message.text){
sendMarkSeen(sender)
sendTypingOn(sender)
setTimeout(function() { sendTypingOff(sender) }, 1000)
let text = event.message.text.toLowerCase()
let guess = event.message.nlp
const intent = firstEntity(guess, 'intent')
if(intent && intent.confidence > 0.7){
sendGuesses(sender, intent)
}
const sentiment = firstEntity(guess, 'sentiment')
if(sentiment && sentiment.confidence > 0.8){
if(sentiment.value === 'positive'){
sendText(sender, "Thank you so much :)\nIt means to us a lot.")
}
if(sentiment.value === 'negative'){
sendText(sender, "You've made PurzeyBot sad. :(")
}
}
getUserProfile(event.sender.id)
.then((cuser) => {
if(cuser === null){
askShuruKrain(sender)
var request = require('request');
var usersPublicProfile = 'https://graph.facebook.com/v2.6/' + sender +
'?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token='
+ token;
request({
url: usersPublicProfile,
json: true // parse
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
saveinDB(sender, 'Name', body.first_name + ' ' + body.last_name);
//saveinDB(sender, 'dp', body.profile_pic);
saveinDB(sender, 'Gender', body.gender);
saveinDB(sender, 'University', 'none');
saveinDB(sender, 'Phone', 'none');
saveinDB(sender, 'Progress', 0);
let randomString2 = Math.random().toString(36).substring(7);
var bucket = admin.storage().bucket();
bucket.upload(body.profile_pic, {
destination: 'profilePictures/' + body.first_name + body.last_name + 'DP_' + randomString2,
metadata: {
contentType: 'image/jpeg',
},
gzip: true,
}).then(() => {
var dpUrl = "https://firebasestorage.googleapis.com/v0/b/purzey-b9cbd.appspot.com/o/profilePictures%2F" + body.first_name + body.last_name + "DP_" + randomString2 + "?alt=media";
saveinDB(sender, 'dp', dpUrl);
}).catch(err => {
});
}
});
}else{
//sendText(sender, "Hello Mr. " + cuser.Name.value)
//var newDate = new Date()
//var oldDate = cuser.LastHour.value
//if(oldDate == null){
// oldDate = "Tue Jul 10 2018 15:00:08 GMT+0000 (UTC)"
//}
//saveinDB(sender, 'LastHour', newDate.toString())
if(cuser.dp.value.includes("facebook.com")){
saveProfilePhoto(sender, cuser.Name.value);
}
if(text === 'generic'){
sendGenericMessage(sender)
}
if(text === 'no'){
sendText(sender, "I see.")
}
if(text === 'yes'){
sendText(sender, "Great!")
}
if(text === 'purzeybot'){
sendText(sender, "Hi! Kya khidmat krun aapki?")
setTimeout(function() { whatCanDo(sender) }, 2000)
}
if(cuser.Progress.value === 0){
if(text === "❌"){
saveinDB(sender, 'University', 'none')
saveinDB(sender, 'Progress', cuser.Progress.value + 1)
sendText(sender, "Aapki university save nai ki gyi.")
setTimeout(function() { askMobileNumber(sender) }, 3000)
}
else if(text.includes("itu") || text.includes("information technology") || text.includes("arfa") || text.includes("plan9")){
saveinDB(sender, 'University', 'ITU')
saveinDB(sender, 'Progress', cuser.Progress.value + 1)
sendText(sender, "ITU University save kr li gyi hai.")
sendCAMInfo(sender, "Mubeen Ikram", "+923331421741")
setTimeout(askMobileNumber(sender), 3000)
}
else if(text.includes("comsats")){
saveinDB(sender, 'University', 'COMSATS')
saveinDB(sender, 'Progress', cuser.Progress.value + 1)
sendText(sender, "COMSATS University save kr li gyi hai.")
sendCAMInfo(sender, "Khunshan Butt", "+923214441444")
setTimeout(function() { askMobileNumber(sender) }, 3000)
}
else if(text.includes("fast university") || text.includes("fast lahore") ||
text.includes("fast-nu") || text.includes("nuces") || text.includes("fastnu")
|| (text.includes("fast") && (text.includes("university") || text.includes("uni")) || text === 'fast')){
saveinDB(sender, 'University', 'Fast-NU')
saveinDB(sender, 'Progress', cuser.Progress.value + 1)
sendText(sender, "FAST University save kr li gyi hai.")
sendCAMInfo(sender, "Mohsin Hayat", "+923364256811")
setTimeout(function() { askMobileNumber(sender) }, 3000)
}
else if(text.includes("pucit - new") || text.includes("punjab university")){
saveinDB(sender, 'University', 'PUCIT (New)')
saveinDB(sender, 'Progress', cuser.Progress.value + 1)
sendText(sender, "PUCIT New Campus save kr li gyi hai.")
sendCAMInfo(sender, "Mustaghees Butt", "+923164855152")
setTimeout(function() { askMobileNumber(sender) }, 3000)
}else if(text === "inmay se koi nai" || text === "none"){
saveinDB(sender, 'University', 'no university')
saveinDB(sender, 'Progress', cuser.Progress.value + 1)
sendText(sender, "Aapki University jald shamil kr li jayegi. Filhal 5 universities cover ki ja rhi hain. :)")
setTimeout(function() { askMobileNumber(sender) }, 3000)
}
else{
askUniversity(sender)
}
}
if(cuser.Progress.value === 1){
if(text === "❌"){
saveinDB(sender, 'Phone', 'none')
saveinDB(sender, 'Progress', cuser.Progress.value + 1)
sendText(sender, "Aapka phone nai save kia gya.")
setTimeout(function() { whatCanDo(sender) }, 2000)
}
const phNum = firstEntity(guess, 'phone_number');
if (phNum && phNum.confidence > 0.8 && phNum.value.length > 10 && phNum.value.length < 15) {
//let phn = text.substring(phNum.start, phNum.end)
saveinDB(sender, 'Phone', phNum.value)
saveinDB(sender, 'Progress', cuser.Progress.value + 1)
sendText(sender, "Aapka mobile number darj kr lia gya hai: " + phNum.value + ". Mustaqbil main issi number pr tafseelat di jayengi.")
setTimeout(function() { whatCanDo(sender) }, 2000)
}else if(text !== "❌"){
askMobileNumber(sender)
}
}
const greeting = firstEntity(guess, 'greetings');
if (greeting && greeting.confidence > 0.8) {
var k = Math.random()
if(k>0.8){
sendText(sender, "Hello! Kya khidmat krun aapki?")
}else if(k>0.6){
sendText(sender, "Hey! Welcome to Purzey!")
}else if(k>0.4){
sendText(sender, "AoA! Kya haal hai?")
}else if(k>0.2){
sendText(sender, "Hi! Did you see our shop?")
}else{
sendText(sender, "Hey! :) PurzeyBot se baat kijiye" )
}
}
const byed = firstEntity(guess, 'bye');
if (byed && byed.confidence > 0.8) {
sendText(sender, "Shukria. Khuda Hafiz!")
}
const sentiment = firstEntity(guess, 'sentiment');
if (sentiment && sentiment.confidence > 0.8) {
//sendText(sender, "Shukria. Khuda Hafiz!")
}
if(intent && intent.confidence > 0.7){
if(intent.value == 'asking_selfName'){
sendText(sender, "Aapka naam " + cuser.Name.value + " hai.")
}
if(intent.value == 'asking_delivery'){
sendText(sender, "Aap ko aapki delivery " + cuser.University.value + " main tehh krda time pr pohncha di jayegi. Wait kijiye :)")
}
if(intent.value == 'show_cart'){
sendCart(sender)
}
if(intent.value == 'show_cart'){
sendText(sender, "I'm good. How are you?")
}
if(intent.value == 'asking_whatCanDo'){
sendText(sender, "I can do a lot of stuff. Try ordering something.")
setTimeout(function() { whatCanDo(sender) }, 2000)
}
if(intent.value == 'showProfile'){
let profMsg = '';
if(cuser.Name.value!=null){
profMsg += "\nName: " + cuser.Name.value
}
if(cuser.University.value!=null){
profMsg += "\nUniversity: " + cuser.University.value
}
if(cuser.Phone.value!=null){
profMsg += "\nPhone #: " + cuser.Phone.value
}
profMsg = profMsg + "\nOrder Count: 0"
sendText(sender, "We have your profile saved with us: " + profMsg)
}
if(intent.value == 'asking_deliverytime'){
sendText(sender, "You'll be delivered your order as soon as possible. Let us know your available time slot.")
}
if(intent.value == 'asking_howmanyneuralnetworks'){
sendText(sender, "I have many neural networks. Talk to me more to add more.")
}
if(intent.value == 'asking_ca'){
var CAM = ""
var CAMphn = ""
if(cuser.University.value === "Fast-NU"){
CAM = "Mohsin Hayat"
CAMphn = "+923364256811"
}
if(cuser.University.value === "ITU"){
CAM = "Mubeen Ikram"
CAMphn = "+923331421741"
}
if(cuser.University.value === "COMSATS"){
CAM = "Khunshan Butt"
CAMphn = "+923214441444"
}
if(cuser.University.value === "PUCIT (New)"){
CAM = "Mustaghees Butt"
CAMphn = "+923164855152"
}
if(CAM !== ""){
sendCAMInfo(sender, CAM, CAMphn)
}
if(cuser.University.value === "none"){
sendText(sender, "Aap nay koi university select nai ki hui.")
}
}
if(intent.value == 'asking_howtoorder'){
orderKrain(sender)
}
if(intent.value == 'asking_botName'){
sendText(sender, "Mera naam PurzeyBot hai")
}
if(intent.value == 'asking_botAge'){
sendText(sender, "BOT ki age jaan kr kya krogay bhai?")
}
if(intent.value == 'showproduct_best'){
const gproduct = firstEntity(guess, 'product')
if(gproduct){
if(gproduct.value === 'Samsung handsfree C7'){
getProduct('AKG Earphones')
.then((prd) => {
if(prd !== null){
sendText(sender, "Although sb market se handpicked hain aur achi hain. Hum apko AKG handsfree recommend krtay hain.")
productOffer(sender, prd)
}
})
}
}else{
sendText(sender, "Aap shop se pasand kr k btayiye please.")
}
}
if(intent.value == 'showproduct_cheapest'){
const g2product = firstEntity(guess, 'product')
if(g2product){
if(g2product.value === 'Samsung handsfree C7'){
getProduct('Samsung Handsfree')
.then((prd) => {
if(prd !== null){
sendText(sender, "Sab say sasti handsfree hamaray pas Samsung Handsfree hai.")
productOffer(sender, prd)
}
})
}
}else{
sendText(sender, "Aap shop se pasand kr k btayiye please.")
}
}
}
if(intent && intent.confidence > 0.8){ //PRODUCT GUESS!
if(intent.value === 'order'){
sendText(sender, "Products k naam sahi se mention kijiye. Aik se zyada dfa order pr click krnay se quantity increase hogi")
const productOrder = event.message.nlp.entities['product']
let t32 = ""
for(var key1 in productOrder) {
getProduct(productOrder[key1].value)
.then((prd) => {
if(prd !== null){
productOffer(sender, prd)
}
})
t32 = t32 + productOrder[key1].value + "\n"
}
const prdGuess = firstEntity(guess, 'product');
if(prdGuess && prdGuess.confidence > 0.8){
sendText(sender, "hmmm... 🤔\nDid you mention any of these " + prdGuess.value + "?")
}
//(sender, "You have ordered:\n" + t32)
}
}
if(text.includes("aoa") || text.includes("salam") || text.includes("aslam") || text.includes("aslamualaikum")){
sendText(sender, "Walaikum-Asalam!")
}
}
})
}
}
res.sendStatus(200)
})
function sendText(sender, text){
let messageData = {text: text}
request({
url: "https://graph.facebook.com/v2.6/me/messages",
qs: {access_token : token},
method: "POST",
json: {
recipient: {id: sender},
message: messageData
}
}, function(error, response, body){
if(error){
console.log("sending error")
}else if(response.body.error){
console.log("response body error")
}
})
}
app.listen(app.get('port'), function(){
console.log("RUNNING: port")
})
function saveDataInDatabase(sender, text){
var db = admin.database();
var ref = db.ref("server/messenger");
var senderRef = ref.child("customer " + sender + "/chat");
var chatRef = senderRef.push();
chatRef.set({
msg: text
});
}
function saveinDB(sender, child, data){
var db = admin.database();
var ref = db.ref("server/messenger");
var custRef = ref.child("customer " + sender + "/" + child);
custRef.set({
value: data
});
}
function getDataFromDB(sender, child, data){
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("server/messenger/customer " + sender + "/" + child);
let rData = '';
// Attach an asynchronous callback to read the data at our posts reference
ref.on("value", function(snapshot) {
rData = snapshot.val();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
return rData;
}
function askMobileNumber(sender){
let messageData = {
"text": "Apna mobile number enter kijiye, takay apsay contact krnay main asani ho.",
"quick_replies":[
{
"content_type":"user_phone_number"
},
{
"content_type":"text",
"title":"❌",
"payload":"phone_none",
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function orderKrain(sender) {
let messageData = {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Order krnay k liye hamari shop pr jayen aur koi product select kr k humain msg krain.",
"buttons":[
{
"type":"web_url",
"url":"https://www.facebook.com/purzey/shop",
"title":"Goto Shop",
"webview_height_ratio": "full"
}
]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function whatCanDo(sender){
let messageData = {
"text": "PurzeyBot is here to help.",
"quick_replies":[
{
"content_type":"text",
"title":"I want an aux cable",
"payload":"wantHandsfree",
},
{
"content_type":"text",
"title":"cheapest handsfree?",
"payload":"cheapestHandsfree",
},
{
"content_type":"text",
"title":"show me my profile",
"payload":"showProfile",
},
{
"content_type":"text",
"title":"campus ambassador?",
"payload":"whoIsCA",
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function askUniversity(sender) {
let messageData = {
"text": "Apni university ka naam btayen?",
"quick_replies":[
{
"content_type":"text",
"title":"ITU",
"payload":"uni_ITU",
},
{
"content_type":"text",
"title":"FAST-NU",
"payload":"uni_NU",
},
{
"content_type":"text",
"title":"COMSATS",
"payload":"uni_COM",
},
{
"content_type":"text",
"title":"PUCIT - NEW",
"payload":"uni_PUnew",
},
{
"content_type":"text",
"title":"UMT",
"payload":"uni_UMT",
},
{
"content_type":"text",
"title":"❌",
"payload":"uni_none",
}
]
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function askShuruKrain(sender) {
let messageData = {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Purzey main khushaamdid! Purzey se baat shuru kijiye.",
"buttons":[
{
"type": "postback",
"title": "Shuru Krain",
"payload": "shuru"
}
]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function pushOrder(sender, prdID, qty){
var db = admin.database();
var ref = db.ref("server/messenger");
var custRef = ref.child("customer " + sender + "/order").push();
custRef.set({
product: prdID,
quantity: qty
});
}
function getProduct(prdName){
var db = admin.database()
var collectionRef = db.ref('products')
var ref = collectionRef.child(prdName)
return ref.once('value')
.then((snapshot) => {
return snapshot.val()
})
}
function getUserProfile(senderID){
var db = admin.database()
var msgnrRef = db.ref("server/messenger");
var ref = msgnrRef.child("customer " + senderID)
return ref.once('value')
.then((snapshot) => {
return snapshot.val()
})
}
function productOffer(sender, prd) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": prd.name,
"subtitle": prd.price + ".00rs only",
"image_url": prd.img,
"buttons": [{
"type": "web_url",
"url": prd.link,
"title": "View"
}, {
"type": "postback",
"title": "Order",
"payload": "productOrder_" + prd.name
}],
}]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendCAMInfo(sender, name, phone) {
let messageData = {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Aapki University k campus ambassador " + name + " hain.\n📞 " + phone + " ",
"buttons":[
{
"type":"phone_number",
"title":"Call " + name,
"payload": phone
}
]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendGenericMessage(sender) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "UGREEN Data Cable 3 Meter Long",
"subtitle": "This 3 meter long cable allows you to reach your phone all the way from your bed.",
"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
"buttons": [{
"type": "web_url",
"url": "https://www.facebook.com/commerce/products/1811144608910173/",
"title": "web url"
}, {
"type": "postback",
"title": "Postback",
"payload": "Payload for first element in a generic bubble",
}],
}, {
"title": "Second card",
"subtitle": "Element #2 of an hscroll",
"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
"buttons": [{
"type": "postback",
"title": "Postback",
"payload": "Payload for second element in a generic bubble",
}],
}]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendContactInfo(sender) {
let messageData = {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Hamaray se rabta krnay k liye:\nEmail: [email protected]\nPhone: 03214441444 or 03364256811\n\nYa issi chat k zariye rabta krein.",
"buttons":[
{
"type":"phone_number",
"title":"Call Purzey",
"payload":"+923364256811"
}
]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendTypingOn(sender){
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
sender_action: "typing_on",
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendTypingOff(sender){
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
sender_action: "typing_off",
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendMarkSeen(sender){
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
sender_action: "mark_seen",
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function getUserCart(senderID){
var db = admin.database()
var msgnrRef = db.ref("server/messenger");
var ref = msgnrRef.child("customer " + senderID + "/order")
return ref.once('value')
.then((snapshot) => {
return snapshot.val()
})
}
function sendCartInfo(sender, itemCount){
let send_text = "";
if(itemCount === 1) {
send_text += "one product";
}else{
send_text += "" + itemCount + " products";
}
let messageData = {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"You have " + send_text + " in your cart. Confirm this order to proceed.",
"buttons":[
{
"type": "postback",
"title": "View Cart",
"payload": "viewCart"
},
{
"type": "postback",
"title": "Confirm",
"payload": "viewReceipt"
},
{
"type": "web_url",
"url": "https://www.facebook.com/purzey/shop",
"title": "More"
}
]
}
}
}