-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
executable file
·567 lines (498 loc) · 16.7 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
"use strict";
const dialogflow = require("dialogflow");
const config = require("./constant");
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
const uuid = require("uuid");
const dialogflowService = require("./services/dialogflow-service");
const fbService = require("./services/fb-service");
const db = require("./db");
const UserModel = require("./models/users");
const hp = require("./services/handover-protocol");
const _sendQuickReply = require("./services/quick-reply");
const _ = require('./services/car.services')
const yes_no = [{
content_type: "text",
title: "Yes",
payload: "yes trade in"
},
{
content_type: "text",
title: "no",
payload: "no trade in"
}
]
const contactType = [{
content_type: "text",
title: "Phone",
payload: "Phone"
}, {
content_type: "text",
title: "email",
payload: "email"
},
{
content_type: "text",
title: "SMS",
payload: "SMS"
}
]
const carOptions = [{
content_type: "text",
title: "Purchase 🚗",
payload: "purchase"
},
{
content_type: "text",
title: "lease",
payload: "lease"
}]
app.set("port", process.env.PORT || 5000);
app.set('view engine', 'ejs');
//verify request came from facebook
//serve static files in the public directory
app.use(express.static(__dirname + "/public"));
app.use("/public", express.static(__dirname + "/public"));
// Process application/x-www-form-urlencoded
app.use(
bodyParser.urlencoded({
extended: false
})
);
// Process application/json
app.use(bodyParser.json());
const credentials = {
client_email: config.GOOGLE_CLIENT_EMAIL,
private_key: config.GOOGLE_PRIVATE_KEY
};
const sessionClient = new dialogflow.SessionsClient({
projectId: config.GOOGLE_PROJECT_ID,
credentials
});
const sessionIds = new Map();
const usersMap = new Map();
// Index route
app.get("/", function (req, res) {
res.send("Hello world, I am a chat bot alive");
});
// for Facebook verification
app.get("/webhook/", function (req, res) {
console.log("request");
if (
req.query["hub.mode"] === "subscribe" &&
req.query["hub.verify_token"] === config.FB_VERIFY_TOKEN
) {
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Failed validation. Make sure the validation tokens match.");
res.sendStatus(403);
}
});
/*
* All callbacks for Messenger are POST-ed. They will be sent to the same
* webhook. Be sure to 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) {
var data = req.body;
// Make sure this is a page subscription
if (data.object == "page") {
// Iterate over each entry
// There may be multiple if batched
data.entry.forEach(function (pageEntry) {
var pageID = pageEntry.id;
var timeOfEvent = pageEntry.time;
// Iterate over each messaging event
if (pageEntry.standby) {
// iterate webhook events from standby channel
pageEntry.standby.forEach(event => {
const psid = event.sender.id;
const message = event.message;
if (
message &&
message.quick_reply &&
message.quick_reply.payload == "take_from_inbox"
) {
var responseText = "Bot is back in control";
fbService.sendTextMessage(psid, responseText);
// sendQuickReply(psid, text, title, payload);
hp.takeThreadControl(psid);
}
});
} else if (pageEntry.messaging) {
pageEntry.messaging.forEach(function (messagingEvent) {
if (messagingEvent.optin) {
fbService.receivedAuthentication(messagingEvent);
} else if (messagingEvent.message) {
receivedMessage(messagingEvent);
} else if (messagingEvent.delivery) {
fbService.receivedDeliveryConfirmation(messagingEvent);
} else if (messagingEvent.postback) {
receivedPostback(messagingEvent);
} else if (messagingEvent.read) {
fbService.receivedMessageRead(messagingEvent);
} else if (messagingEvent.account_linking) {
fbService.receivedAccountLink(messagingEvent);
} else {
console.log(
"Webhook received unknown messagingEvent: ",
messagingEvent
);
}
});
}
});
// Assume all went well.
// You must send back a 200, within 20 seconds
res.sendStatus(200);
}
});
function setSessionAndUser(senderID) {
if (!sessionIds.has(senderID)) {
sessionIds.set(senderID, uuid.v1());
}
}
async function receivedMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
await setSessionAndUser(senderID);
//console.log("Received message for user %d and page %d at %d with message:", senderID, recipientID, timeOfMessage);
//console.log(JSON.stringify(message));
var isEcho = message.is_echo;
var messageId = message.mid;
var appId = message.app_id;
var metadata = message.metadata;
// You may get a text or attachment but not both
var messageText = message.text;
var messageAttachments = message.attachments;
var quickReply = message.quick_reply;
const psid = event.sender.id;
if (quickReply && quickReply.payload == "pass_to_inbox") {
// quick reply to pass to Page inbox was clicked
var page_inbox_app_id = 263902037430900;
var text = "Bot is transfering Control to Our Admin";
var title = "Resume bot";
var payload = "take_from_inbox";
await _sendQuickReply(psid, text, title, payload);
await hp.passThreadControl(psid, page_inbox_app_id);
return false;
} else if (event.pass_thread_control) {
// thread control was passed back to bot manually in Page inbox
var responseText = "Query Solved.";
await _sendQuickReply(psid, responseText);
}
if (isEcho) {
fbService.handleEcho(messageId, appId, metadata);
return;
} else if (quickReply) {
handleQuickReply(senderID, quickReply, messageId);
return;
}
if (messageText) {
//send message to DialogFlow
dialogflowService.sendTextQueryToDialogFlow(
sessionIds,
handleDialogFlowResponse,
senderID,
messageText
);
} else if (messageAttachments) {
fbService.handleMessageAttachments(messageAttachments, senderID);
}
}
function handleQuickReply(senderID, quickReply, messageId) {
var quickReplyPayload = quickReply.payload;
console.log(quickReplyPayload);
switch (quickReplyPayload) {
// case "yes trade in":
// dialogflowService.sendEventToDialogFlow(sessionIds, handleDialogFlowResponse, senderID, "trade-in-yes")
// break;
// case "no trade in":
// dialogflowService.sendEventToDialogFlow(sessionIds, handleDialogFlowResponse, senderID, "trade-in-no")
// break;
default:
dialogflowService.sendTextQueryToDialogFlow(
sessionIds,
handleDialogFlowResponse,
senderID,
quickReplyPayload
);
break;
}
}
async function handleDialogFlowAction(
sender,
action,
messages,
contexts,
parameters
) {
console.log("--------------", action, "-------------------");
// console.log("----------------------------------------------------------");
// console.log(parameters.fields);
// console.log("----------------------------------------------------------");
// console.log(JSON.stringify(contexts, null, 2));
// console.log("----------------------------------------------------------");
switch (action) {
case "get-basics":
case "get-basics-used-car":
_.getBasic(sender)
break;
case "user-select-car":
var { cars, carmodel, year, insurance } = parameters.fields;
if (fbService.isDefined(contexts[0].parameters.fields['used-car']) && !insurance.stringValue) {
fbService.sendTextMessage(sender, "Would you like a Financing Quote on this Vehicle ehh?")
} else if (insurance.stringValue && fbService.isDefined(contexts[0].parameters.fields['used-car'])) {
fbService.sendQuickReply(sender, "Do you have a Trade-In ?", yes_no)
}
else if ((cars.stringValue || year.original.stringValue || carmodel.stringValue) && !insurance.stringValue) {
let bool = config.cars.some(x => x.toLowerCase() == cars.stringValue.toLowerCase())
bool ? fbService.sendQuickReply(sender, `Great. Would you like to Lease or Purchase ${cars.stringValue}?`, carOptions) : fbService.sendTextMessage(sender, `${cars.stringValue} is not seemes to be car make. :(`)
}
fbService.handleMessages(messages, sender);
break;
case "user-purchase":
case "user-lease":
_.purcahseOrLease(sender)
break;
case "trade-in-yes":
_.tradeYes(sender)
break;
case "trade-in-no":
fbService.sendQuickReply(sender, "how would you like to get connacted?", contactType)
dialogflowService.sendEventToDialogFlow(sessionIds, handleDialogFlowResponse, sender, "getconnect")
break;
case "original-purchase-yes":
if (parameters.fields.km.numberValue) {
fbService.sendQuickReply(sender, "how would you like to get connacted?", contactType)
dialogflowService.sendEventToDialogFlow(sessionIds, handleDialogFlowResponse, sender, "getconnect")
}
fbService.handleMessages(messages, sender);
break;
case "original-purchase-no":
console.log(parameters.fields);
var { majorbrake, cars, insurance, km } = parameters.fields;
if (majorbrake.stringValue && cars.stringValue && insurance.stringValue && km.numberValue) {
fbService.sendQuickReply(sender, "how would you like to get connacted?", contactType)
dialogflowService.sendEventToDialogFlow(sessionIds, handleDialogFlowResponse, sender, "getconnect")
}
fbService.handleMessages(messages, sender);
break;
case "contact":
_.contact(sender)
break;
case "service":
var { date, time, email, AppointmentType } = parameters.fields
if (date && time && email && AppointmentType) {
var data = { date, time, email, AppointmentType }
}
fbService.handleMessages(messages, sender);
break;
case "getconnect":
var { mail, mobile } = parameters.fields;
if (parameters.fields['connect-type'].stringValue == 'email') {
fbService.sendTextMessage(sender, `what is your email?`)
}
if (parameters.fields['connect-type'].stringValue == 'sms' || parameters.fields['connect-type'].stringValue == 'phone') {
fbService.sendTextMessage(sender, `what is your mobile number?`)
}
console.log(parameters.fields);
if (mail.stringValue || mobile.stringValue) {
fbService.sendTextMessage(sender, `Thanks for reaching out. yovip will be intouch shortly.`)
}
fbService.handleMessages(messages, sender);
break;
default:
fbService.handleMessages(messages, sender);
}
}
function handleMessages(messages, sender) {
var timeoutInterval = 1100;
var previousType;
var cardTypes = [];
var timeout = 0;
for (var i = 0; i < messages.length; i++) {
if (
previousType == "card" &&
(messages[i].message != "card" || i == messages.length - 1)
) {
timeout = (i - 1) * timeoutInterval;
setTimeout(handleCardMessages.bind(null, cardTypes, sender), timeout);
cardTypes = [];
timeout = i * timeoutInterval;
setTimeout(handleMessage.bind(null, messages[i], sender), timeout);
} else if (messages[i].message == "card" && i == messages.length - 1) {
cardTypes.push(messages[i]);
timeout = (i - 1) * timeoutInterval;
setTimeout(handleCardMessages.bind(null, cardTypes, sender), timeout);
cardTypes = [];
} else if (messages[i].message == "card") {
cardTypes.push(messages[i]);
} else {
timeout = i * timeoutInterval;
setTimeout(handleMessage.bind(null, messages[i], sender), timeout);
}
previousType = messages[i].message;
}
}
function handleDialogFlowResponse(sender, response) {
var responseText = response.fulfillmentMessages.fulfillmentText;
var messages = response.fulfillmentMessages;
var action = response.action;
var contexts = response.outputContexts;
var parameters = response.parameters;
fbService.sendTypingOff(sender);
if (fbService.isDefined(action)) {
handleDialogFlowAction(sender, action, messages, contexts, parameters);
} else if (fbService.isDefined(messages)) {
fbService.handleMessages(messages, sender);
} else if (responseText == "" && !fbService.isDefined(action)) {
//dialogflow could not evaluate input.
fbService.sendTextMessage(
sender,
"I'm not sure what you want. Can you be more specific yovip?"
);
} else if (fbService.isDefined(responseText)) {
fbService.sendTextMessage(sender, responseText);
}
}
async function resolveAfterXSeconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, x * 1000);
});
}
async function greetUserText(userId) {
await request({
uri: "https://graph.facebook.com/v3.2/" + userId,
qs: {
access_token: config.FB_PAGE_TOKEN
}
},
async function (error, response, body) {
if (!error && response.statusCode == 200) {
var user = JSON.parse(body);
var query = {
"FbData.id": user.id
},
update = {
dUpdatedDate: new Date()
},
options = {
upsert: true,
new: true,
setDefaultsOnInsert: true
};
// Find the document
UserModel.findOneAndUpdate(query, update, options).then(result => {
result.sFbData = user;
result.save().then(async (success) => {
var responseText = `Hi! Nice to meet you ${user.first_name}. I'm yovip. Christian's Assistant.`
var url = "https://scontent.xx.fbcdn.net/v/t1.15752-0/p280x280/42686629_507772776365057_3601089422088470528_n.jpg?_nc_cat=100&_nc_ad=z-m&_nc_cid=0&_nc_ht=scontent.xx&oh=446eec72884bb512b788203bd9c8e22d&oe=5CF2E920"
fbService.sendTextMessage(user.id, responseText)
var responseText2 = "What can i help you with today?";
var qr = [{
content_type: "text",
title: "N Car 🚗",
payload: "New Car"
},
{
content_type: "text",
title: "UsCar purchase🚗",
payload: "Used Car"
}, {
content_type: "text",
title: "Sche Servic 🧰",
payload: "Schedule Service"
}, {
content_type: "text",
title: "Refer Progra 💸",
payload: "Referral Program"
}, {
content_type: "text",
title: "Con 🤙",
payload: "Contact"
}
];
fbService.sendImageMessage(user.id, url).then(() => {
setTimeout(() => {
fbService.sendQuickReply(user.id, responseText2, qr)
}, 1000);
})
});
});
}
}
);
}
/*
* Postback Event
*
* This event is called when a postback is tapped on a Structured Message.
* https://developers.facebook.com/docs/messenger-platform/webhook-reference/postback-received
*
*/
async function receivedPostback(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfPostback = event.timestamp;
setSessionAndUser(senderID);
// The 'payload' param is a developer-defined field which is set in a postback
// button for Structured Messages.
var payload = event.postback.payload;
console.log(payload)
switch (payload) {
case "FACEBOOK_WELCOME":
greetUserText(senderID);
break;
case "Contact Us":
case "REFERRALS":
case "ABOUT":
_.contact(senderID)
break;
case "USED_CAR":
dialogflowService.sendTextQueryToDialogFlow(
sessionIds,
handleDialogFlowResponse,
senderID,
payload
);
break;
case "NEW_CAR":
dialogflowService.sendTextQueryToDialogFlow(
sessionIds,
handleDialogFlowResponse,
senderID,
payload
);
break;
case "SERVICE":
dialogflowService.sendTextQueryToDialogFlow(
sessionIds,
handleDialogFlowResponse,
senderID,
payload
"service"
);
break;
default:
//unindentified payload
fbService.sendTextMessage(
senderID,
"I'm not sure what you want. Can you be more specific yovip?"
);
break;
}
console.info("Received postback");
}
// Spin up the server
app.listen(app.get("port"), function () {
console.info("Magic Started on", app.get("port"));
});