-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
361 lines (326 loc) · 10.1 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
/* jshint node: true, devel: true */
"use strict";
const _ = require("lodash");
const cors = require("cors");
const express = require("express");
const request = require("request");
const emoji = require("emoji");
const bodyParser = require("body-parser");
const app = express();
let quoteID = 0;
const baseupServ = require("./providers/baseup.service");
const facebookServ = require("./providers/facebook.service");
const facebookConst = require("./settings/facebook.constants");
const inspirationConst = require("./settings/inspiration.constants");
const representativeConst = require("./settings/representative.constants");
app.use(cors());
app.set("port", process.env.PORT || 5000);
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.get("/", (req, res) => {
res.send("HELLO HI");
});
app.get("/webhooks", (req, res) => {
if (req.query["hub.verify_token"] === facebookConst.VALIDATION_TOKEN) {
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Failed validation. Make sure the validation tokens match.");
res.sendStatus(403);
}
});
app.post("/send-message", (req, res) => {
const reqBody = req.body;
const dataString = {
messaging_type: "RESPONSE",
recipient: {
id: reqBody.psid
},
message: {
text: reqBody.message
}
};
request({
url: `https://graph.facebook.com/v2.9/me/messages?access_token=${
facebookConst.PAGE_ACCESS_TOKEN
}`,
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(dataString)
},
(error, response, body) => {
if (error) {
res.status(400).send(error);
} else if (response.error) {
res.status(400).send(JSON.parse(body));
} else {
res.status(200).send(JSON.parse(body));
}
res.end();
}
);
});
app.post("/webhooks", (req, res) => {
const body = req.body;
if (body.object === "page") {
body.entry.forEach(bodyEntry => {
bodyEntry.messaging.forEach(webhook_event => {
const sender_psid = webhook_event.sender.id;
if (webhook_event.message) {
handleMessage(sender_psid, webhook_event.message);
} else if (webhook_event.postback) {
handlePostback(sender_psid, webhook_event.postback);
} else if (webhook_event.account_linking) {
handleAccountLinking(sender_psid, webhook_event.account_linking);
}
});
});
res.status(200).send("EVENT_RECEIVED");
} else {
res.sendStatus(404);
}
});
function handleMessage(sender_psid, received_message) {
let random = [];
let message = "";
const text = received_message.text;
const quickreply = received_message.quick_reply;
const getPSID = /(what\sis\smy\spsid\splease|get\spsid\splease)/gim;
if (quickreply) {
switch (quickreply.payload) {
case "CHECK_PARTNERS":
handleGetPartners(sender_psid, quickreply.payload);
break;
case "MAKE_APPOINTMENT":
handleGetPartners(sender_psid, quickreply.payload);
break;
case "OTHER_CONCERNS":
message =
"Someone from our team will get in touch with you shortly. Hold on tight!";
facebookServ.sendMessage(sender_psid, message).then(() => {
let count = 0;
const functionSendConcerns = () => {
// console.log(representativeConst[count]);
facebookServ
.notifyHumanOperators(
sender_psid,
representativeConst[count].psid
)
.then(() => {
count++;
if (count < representativeConst.length) {
functionSendConcerns();
}
});
};
functionSendConcerns();
});
break;
case "DONE":
message = "Always Happy to serve you. Hope you have a great day!";
facebookServ.sendMessage(sender_psid, message);
break;
case "SUBSCRIBE":
facebookServ.sendLogin(sender_psid);
break;
case "START_OVER":
facebookServ.sendMainQuickReply(sender_psid);
break;
case "NEED_INSPIRATION":
random =
inspirationConst[Math.floor(Math.random() * inspirationConst.length)];
quoteID = random.id;
message = random.quote;
facebookServ.sendMessage(sender_psid, message, "inpirationQR");
break;
case "MORE_INSPIRATION":
const sendInpiration = () => {
random =
inspirationConst[
Math.floor(Math.random() * inspirationConst.length)
];
if (random.id !== quoteID) {
quoteID = random.id;
message = random.quote;
facebookServ.sendMessage(sender_psid, message, "inpirationQR");
} else {
sendInpiration();
}
};
sendInpiration();
break;
default:
facebookServ.sendMainQuickReply(sender_psid);
}
} else {
if (text) {
const isEmojiSpan = /<[a-z][\s\S]*>/i.test(emoji.unifiedToHTML(text));
const ishaircutEmoji = emoji
.unifiedToHTML(text)
.includes('title="haircut"');
if (text === "what is my psid please") {
facebookServ.sendMessage(sender_psid, `Your PSID is ${sender_psid}`);
} else if (isEmojiSpan && ishaircutEmoji) {
console.log('EMOJI');
handleGetPartners(sender_psid, "MAKE_APPOINTMENT");
} else {
facebookServ.sendMainQuickReply(sender_psid);
}
} else {
facebookServ.sendMainQuickReply(sender_psid);
}
}
}
function handlePostback(sender_psid, received_postback) {
const title = received_postback.title;
const payload = received_postback.payload;
if (title === "Book Appointment") {
handleGetBranch(sender_psid, payload, "Book");
} else if (title === "Check Branch") {
handleGetBranch(sender_psid, payload, "View Details");
} else if (title === "View Details") {
handleGetBranchDetails(sender_psid, payload);
} else if (payload === "GET_STARTED") {
facebookServ.sendMainQuickReply(sender_psid);
}
}
function handleAccountLinking(sender_psid, received_account_linking) {
const status = received_account_linking.status;
const authCode = received_account_linking.authorization_code;
if (status === "linked") {
baseupServ.getAuthBaseupUser(authCode).then(authResponse => {
const metaData = authResponse.metadata;
const fullname = `${authResponse.first_name} ${authResponse.last_name}`;
metaData.psid = sender_psid;
const attributes = {
metadata: metaData
};
baseupServ
.storeUserPSID(authCode, authResponse.id, attributes)
.then(updateResponse => {
facebookServ.sendMainQuickReply(sender_psid, "welcome");
});
});
}
}
function handleGetBranchDetails(psid, details) {
const data = JSON.parse(details);
const message = `Here are the details: \n Name: ${data.name} \n Address: ${
data.address
} \n Phone: ${data.phone} \n Alias: ${data.alias}`;
facebookServ.sendMessage(psid, message, "mainQR");
}
function handleGetBranch(psid, payload, type) {
baseupServ
.getBranches(payload.toLowerCase())
.then(result => {
const replies = [{
title: result[0].account.name,
subtitle: `${result[0].account.address}, ${result[0].account.city} ${
result[0].account.province
}`
}];
for (const val of result) {
const button =
type === "Book" ? {
type: "web_url",
title: type,
url: `${facebookConst.BASE_URL}/widget/${val.account.slug}/${
val.id
}/?messenger=${psid}`
} : {
type: "postback",
title: type,
payload: JSON.stringify({
name: val.name,
address: val.address,
phone: val.phone,
alias: val.alias
})
};
replies.push({
title: val.alias,
subtitle: val.address,
buttons: [button]
});
}
const dividend = replies.length % 4 === 1 ? 3 : 4;
const chunk = _.chunk(replies, dividend);
let chunkCount = 0;
const functionSendBranch = () => {
facebookServ.sendBranch(psid, chunk[chunkCount]).then(() => {
chunkCount++;
if (chunkCount < chunk.length) {
functionSendBranch();
}
});
};
functionSendBranch();
})
.catch(error => {
console.log("BRANCH ERROR: ", JSON.stringify(error));
});
}
function handleGetPartners(psid, payload) {
baseupServ
.getBusinesses()
.then(result => {
const businesses = [];
const filterActive = result.filter(value => {
return (
value.id === "2" ||
value.id === "43" ||
value.id === "44" ||
value.id === "48" ||
value.id === "55"
);
});
for (const val of filterActive) {
const title =
payload === "MAKE_APPOINTMENT" ? "Book Appointment" : "Check Branch";
const data = {
title: val.name,
buttons: [{
type: "postback",
title,
payload: val.slug
}]
};
if (val.address) {
data.subtitle = `${val.address}, ${val.city} ${val.province}`;
}
// if (val.business_logo) {
// data.image_url = `${facebookConst.BASE_URL}/${val.business_logo}`;
// }
businesses.push(data);
}
let chunkCount = 0;
const chunk = _.chunk(businesses, 10);
const functionSendBusiness = () => {
facebookServ
.sendPartners(psid, chunk[chunkCount])
.then(() => {
chunkCount++;
if (chunkCount < chunk.length) {
functionSendBusiness();
}
})
.catch(() => {
console.log("Send Partner Error");
});
};
functionSendBusiness();
})
.catch(error => {
console.log("BUSINESS ERROR: ", JSON.stringify(error));
});
}
app.listen(app.get("port"), () => {
console.log("Node app is running on port", app.get("port"));
});
module.exports = app;