-
Notifications
You must be signed in to change notification settings - Fork 1
/
indexOLD.js
452 lines (397 loc) · 13.8 KB
/
indexOLD.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
'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 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
let dbPh = ''
let goUNI = getDataFromDB(sender, 'University', dbPh)
let goDB = getDataFromDB(sender, 'Phone', dbPh)
let goCAM = getDataFromDB(sender, 'Campus', dbPh)
let userName = getDataFromDB(sender, 'Name', dbPh)
let prdINFO = getProduct("akghf")
if(userName == null){
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);
}
});
}
if (event.postback) {
let text = JSON.stringify(event.postback)
sendText(sender, "Postback received: "+text.substring(0, 200), token)
continue
}
if(event.message && event.message.text){
let text = event.message.text.toLowerCase()
let guess = event.message.nlp
const greeting = firstEntity(guess, 'greetings');
const intent = firstEntity(guess, 'intent');
saveDataInDatabase(sender, text)
if (text === 'generic') {
sendGenericMessage(sender)
continue
}
if(text.includes("profile")){
let profMsg = '';
if(userName!=null){
profMsg += "\n*Name:* " + userName.value
}
if(goUNI!=null){
profMsg += "\n*University:* " + goUNI.value
}
if(goDB!=null){
profMsg += "\n*Phone #:* " + goDB.value
}
profMsg = profMsg + "\n*Order Count:* 0"
sendText(sender, "We have your profile saved with us: " + profMsg)
}
if (greeting && greeting.confidence > 0.8) {
var k = Math.random()
if(k>0.8){
sendText(sender, "Hello! How you doing?")
}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! :) " )
}
}
if(intent && intent.confidence > 0.8){
if(intent.value == "asking_website"){
sendText(sender, "We don't have a website right now. But we do manage our business on Facebook very well, you can see the shop and contact us at any time you want." )
}
if(intent.value == "asking_email"){
sendText(sender, "You can email us at our email address: purzey2018@gmail.com")
}
if(intent.value == 'slang'){
sendText(sender, ":D :P")
}
if(intent.value == 'product_inquiry'){
sendText(sender, "Your question about the product has been noted. We'll let you know after confirmation")
}
if(intent.value == 'abuse'){
sendText(sender, "Abusing will cause a permanent ban.")
}
if(intent.value == 'order_received'){
sendText(sender, "Have a good day :) Kindly rate our services and share Purzey with your friends.")
}
if(intent.value == 'asking_phone'){
sendText(sender, "Kindly contact Khunshan: 0321 4441444")
}
}
const uni = firstEntity(guess, 'university');
if (uni && uni.confidence > 0.8){
//sendText(sender, "You talked about your university " + uni.value)
}
const prd = firstEntity(guess, 'product');
if (prd && prd.confidence > 0.8){
const prd_t = firstEntity(guess, 'product_type');
let prID = 'noID'
if(prd_t && prd_t.confidence > 0.8)
{
if(prd.value == 'Handsfree' && prd_t.value == 'Samsung'){
prID = 'j5hf'
}
if(prd.value == 'Handsfree' && prd_t.value == 'c7'){
prID = 'c7hf'
}
if(prd.value == 'Handsfree' && prd_t.value == 'AKG'){
prID = 'akghf'
}
//sendText(sender, "You talked about our product: " + prd_t.value + " " + prd.value)
}else{
if(prd.value == 'Handsfree'){
sendText(sender, "You haven't mentioned which handsfree do you want. We have 3 kinds of handsfrees.")
}
//sendText(sender, "You talked about our product: " + prd.value)
}
if(prd.value == 'Mouse Pad'){
prID = 'lgmp'
}
if(prID != 'noID'){
getProduct(prID)
.then((prdINFO) => {
sendText(sender, "The price of " + prdINFO.name + " is " + prdINFO.price + "PKR only.")
})
}
}
const byed = firstEntity(guess, 'bye');
if (byed && byed.confidence > 0.8) {
sendText(sender, "Thank you so much. Bye!")
}
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)
if(!goDB){
saveinDB(sender, 'Phone', phNum.value)
sendText(sender, "We have noted down your Phone number: " + phNum.value + ". Kindly wait while the campus ambassador contacts you.")
}
else{
sendText(sender, "We have already saved your Phone Number: " + goDB.value)
}
}
const timing = firstEntity(guess, 'datetime');
if (timing && timing.confidence > 0.8 && (text.includes("free") || text.includes("slot"))) {
let time = text.substring(timing.start, timing.end)
sendText(sender, "We have noted down your time-slot. Please wait while the campus ambassador confirms this time-slot.")
}
if(text.includes("aoa") || text.includes("salam") || text.includes("aslam") || text.includes("aslamualaikum")){
sendText(sender, "Walaikum-Asalam!")
}
if(text.includes('?')){
//sendText(sender, "Your question has been noted down. We'll reply you in a while.")
}
if(text.includes("itu") || text.includes("information technology") || text.includes("arfa") || text.includes("plan9")){
if(goUNI == null){
saveinDB(sender, 'University', 'ITU')
sendText(sender, "Mubeen Ikram is our campus ambassador at ITU, Lahore. He'll handover your order to you.")
}
else{
sendText(sender, "We have already saved that you are from " + goUNI.value + ".")
}
}
else if(text.includes("comsats")){
if(goUNI == null){
saveinDB(sender, 'University', 'COMSATS')
sendText(sender, "Khunshan Butt is our campus ambassador at COMSATS, Lahore. He'll handover your order to you.")
}else{
sendText(sender, "We have already saved that you are from " + goUNI.value + ".")
}
}
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")) )){
if(goUNI == null){
saveinDB(sender, 'University', 'Fast-NU')
sendText(sender, "Mohsin Hayat is our campus ambassador at FAST-NU, Lahore. He'll handover your order to you.")
}else{
sendText(sender, "We have already saved that you are from " + goUNI.value + ".")
}
}else if(text.includes("pucit") || text.includes("punjab university")){
if(goUNI == null){
saveinDB(sender, 'University', 'PUCIT')
if(text.includes("new")){
saveinDB(sender, 'Campus', 'New')
sendText(sender, "Mustaghees Butt is our campus ambassador at PUCIT, New Campus, Lahore. He'll handover your order to you.")
}else if(text.includes("old")){
saveinDB(sender, 'Campus', 'Old')
sendText(sender, "We are not yet available in PUCIT old campus.")
}else{
sendText(sender, "You haven't mentioned which campus are you from?")
}
}else{
sendText(sender, "We have already saved that you are from " + goUNI.value + ".")
}
}
else if(text.includes("new campus")){
if(goCAM == null){
saveinDB(sender, 'Campus', 'New')
sendText(sender, "Mustaghees Butt is our campus ambassador at PUCIT, New Campus, Lahore. He'll handover your order to you.")
}
}
else if(text.includes("old campus")){
if(goCAM == null){
saveinDB(sender, 'Campus', 'Old')
}
sendText(sender, "We're sorry but we are not available in old campus")
}
const qt = firstEntity(guess, 'quantity');
if (qt && qt.confidence > 0.8) {
sendText(sender, "Noted. You want " + qt.value + " " + qt.product)
}
}
}
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 sendGenericMessage(sender) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "list",
"top_element_style": "compact",
"elements": [
{
"title": "Classic T-Shirt Collection",
"subtitle": "See all our colors",
"image_url": "https://peterssendreceiveapp.ngrok.io/img/collection.png",
"buttons": [
{
"title": "View",
"type": "web_url",
"url": "https://peterssendreceiveapp.ngrok.io/collection",
"messenger_extensions": true,
"webview_height_ratio": "tall",
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"
}
]
},
{
"title": "Classic White T-Shirt",
"subtitle": "See all our colors",
"default_action": {
"type": "web_url",
"url": "https://peterssendreceiveapp.ngrok.io/view?item=100",
"messenger_extensions": false,
"webview_height_ratio": "tall"
}
},
{
"title": "Classic Blue T-Shirt",
"image_url": "https://peterssendreceiveapp.ngrok.io/img/blue-t-shirt.png",
"subtitle": "100% Cotton, 200% Comfortable",
"default_action": {
"type": "web_url",
"url": "https://peterssendreceiveapp.ngrok.io/view?item=101",
"messenger_extensions": true,
"webview_height_ratio": "tall",
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"
},
"buttons": [
{
"title": "Shop Now",
"type": "web_url",
"url": "https://peterssendreceiveapp.ngrok.io/shop?item=101",
"messenger_extensions": true,
"webview_height_ratio": "tall",
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"
}
]
}
],
"buttons": [
{
"title": "View More",
"type": "postback",
"payload": "payload"
}
]
}
}
}
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){
var db = admin.database();
var ref = db.ref("server/messenger");
var custRef = ref.child("customer/" + sender + "/order");
custRef.set({
product: prdID
});
}
function getProduct(prID){
var db = admin.database()
var collectionRef = db.ref('server/products')
var ref = collectionRef.child(prID)
return ref.once('value')
.then((snapshot) => {
return snapshot.val()
})
}