-
Notifications
You must be signed in to change notification settings - Fork 221
/
receive.js
434 lines (396 loc) · 12.4 KB
/
receive.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
/**
* Copyright 2021-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Messenger For Original Coast Clothing
* https://developers.facebook.com/docs/messenger-platform/getting-started/sample-apps/original-coast-clothing
*/
"use strict";
const Curation = require("./curation"),
Order = require("./order"),
Lead = require("./lead"),
Response = require("./response"),
Care = require("./care"),
Survey = require("./survey"),
GraphApi = require("./graph-api"),
i18n = require("../i18n.config"),
config = require("./config");
module.exports = class Receive {
constructor(user, webhookEvent, isUserRef) {
this.user = user;
this.webhookEvent = webhookEvent;
this.isUserRef = isUserRef;
}
// Check if the event is a message or postback and
// call the appropriate handler function
handleMessage() {
let event = this.webhookEvent;
let responses;
try {
if (event.message) {
let message = event.message;
if (message.quick_reply) {
responses = this.handleQuickReply();
} else if (message.attachments) {
responses = this.handleAttachmentMessage();
} else if (message.text) {
responses = this.handleTextMessage();
}
} else if (event.postback) {
responses = this.handlePostback();
} else if (event.referral) {
responses = this.handleReferral();
} else if (event.optin) {
responses = this.handleOptIn();
} else if (event.pass_thread_control) {
responses = this.handlePassThreadControlHandover();
}
} catch (error) {
console.error(error);
responses = {
text: `An error has occured: '${error}'. We have been notified and \
will fix the issue shortly!`
};
}
if (Array.isArray(responses)) {
let delay = 0;
for (let response of responses) {
this.sendMessage(response, delay * 2000, this.isUserRef);
delay++;
}
} else {
this.sendMessage(responses, this.isUserRef);
}
}
// Handles messages events with text
handleTextMessage() {
console.log(
"Received text:",
`${this.webhookEvent.message.text} for ${this.user.psid}`
);
let event = this.webhookEvent;
// check greeting is here and is confident
let greeting = this.firstEntity(event.message.nlp, "greetings");
let message = event.message.text.trim().toLowerCase();
let response;
if (
(greeting && greeting.confidence > 0.8) ||
message.includes("start over")
) {
response = Response.genNuxMessage(this.user);
} else if (Number(message)) {
response = Order.handlePayload("ORDER_NUMBER");
} else if (message.includes("#")) {
response = Survey.handlePayload("CSAT_SUGGESTION");
} else if (message.includes(i18n.__("care.help").toLowerCase())) {
let care = new Care(this.user, this.webhookEvent);
response = care.handlePayload("CARE_HELP");
} else {
response = [
Response.genText(
i18n.__("fallback.any", {
message: event.message.text
})
),
Response.genText(i18n.__("get_started.guidance")),
Response.genQuickReply(i18n.__("get_started.help"), [
{
title: i18n.__("menu.suggestion"),
payload: "CURATION"
},
{
title: i18n.__("menu.help"),
payload: "CARE_HELP"
},
{
title: i18n.__("menu.product_launch"),
payload: "PRODUCT_LAUNCH"
}
])
];
}
return response;
}
// Handles mesage events with attachments
handleAttachmentMessage() {
let response;
// Get the attachment
let attachment = this.webhookEvent.message.attachments[0];
console.log("Received attachment:", `${attachment} for ${this.user.psid}`);
response = Response.genQuickReply(i18n.__("fallback.attachment"), [
{
title: i18n.__("menu.help"),
payload: "CARE_HELP"
},
{
title: i18n.__("menu.start_over"),
payload: "GET_STARTED"
}
]);
return response;
}
// Handles mesage events with quick replies
handleQuickReply() {
// Get the payload of the quick reply
let payload = this.webhookEvent.message.quick_reply.payload;
return this.handlePayload(payload);
}
// Handles postbacks events
handlePostback() {
let postback = this.webhookEvent.postback;
// Check for the special Get Starded with referral
let payload;
if (postback.referral && postback.referral.type == "OPEN_THREAD") {
payload = postback.referral.ref;
} else if (postback.payload) {
// Get the payload of the postback
payload = postback.payload;
}
if (payload.trim().length === 0) {
console.log("Ignore postback with empty payload");
return null;
}
return this.handlePayload(payload.toUpperCase());
}
// Handles referral events
handleReferral() {
// Get the payload of the postback
let type = this.webhookEvent.referral.type;
if (type === "LEAD_COMPLETE" || type === "LEAD_INCOMPLETE") {
let lead = new Lead(this.user, this.webhookEvent);
return lead.handleReferral(type);
}
if (type === "OPEN_THREAD") {
let payload = this.webhookEvent.referral.ref.toUpperCase();
if (payload.trim().length === 0) {
console.log("Ignore referral with empty payload");
return null;
}
return this.handlePayload(payload);
}
console.log("Ignore referral of invalid type");
}
// Handles optins events
handleOptIn() {
let optin = this.webhookEvent.optin;
// Check for the special Get Starded with referral
let payload;
if (optin.type === "notification_messages") {
payload = "RN_" + optin.notification_messages_frequency.toUpperCase();
this.sendRecurringMessage(optin.notification_messages_token, 5000);
return this.handlePayload(payload);
}
return null;
}
handlePassThreadControlHandover() {
let new_owner_app_id =
this.webhookEvent.pass_thread_control.new_owner_app_id;
let previous_owner_app_id =
this.webhookEvent.pass_thread_control.previous_owner_app_id;
let metadata = this.webhookEvent.pass_thread_control.metadata;
if (config.appId === new_owner_app_id) {
console.log("Received a handover event, but is not for this app");
return;
}
const lead_gen_app_id = 413038776280800; // App id for Messenger Lead Ads
if (previous_owner_app_id === lead_gen_app_id) {
console.log(
"Received a handover event from Lead Generation Ad will handle Referral Webhook Instead"
);
return;
}
// We have thread control but no context on what to do, default to New User Experience
return Response.genNuxMessage(this.user);
}
handlePayload(payload) {
console.log("Received Payload:", `${payload} for ${this.user.psid}`);
let response;
// Set the response based on the payload
if (
payload === "GET_STARTED" ||
payload === "DEVDOCS" ||
payload === "GITHUB"
) {
response = Response.genNuxMessage(this.user);
} else if (
payload.includes("CURATION") ||
payload.includes("COUPON") ||
payload.includes("PRODUCT_LAUNCH")
) {
let curation = new Curation(this.user, this.webhookEvent);
response = curation.handlePayload(payload);
} else if (payload.includes("CARE")) {
let care = new Care(this.user, this.webhookEvent);
response = care.handlePayload(payload);
} else if (payload.includes("ORDER")) {
response = Order.handlePayload(payload);
} else if (payload.includes("CSAT")) {
response = Survey.handlePayload(payload);
} else if (payload.includes("CHAT-PLUGIN")) {
response = [
Response.genText(i18n.__("chat_plugin.prompt")),
Response.genText(i18n.__("get_started.guidance")),
Response.genQuickReply(i18n.__("get_started.help"), [
{
title: i18n.__("care.order"),
payload: "CARE_ORDER"
},
{
title: i18n.__("care.billing"),
payload: "CARE_BILLING"
},
{
title: i18n.__("care.other"),
payload: "CARE_OTHER"
}
])
];
} else if (payload.includes("BOOK_APPOINTMENT")) {
response = [
Response.genText(i18n.__("care.appointment")),
Response.genText(i18n.__("care.end"))
];
} else if (payload === "RN_WEEKLY") {
response = {
text: `[INFO]The following message is a sample Recurring Notification for a weekly frequency. This is usually sent outside the 24 hour window to notify users on topics that they have opted in.`
};
} else if (payload.includes("WHOLESALE_LEAD")) {
let lead = new Lead(this.user, this.webhookEvent);
response = lead.handlePayload(payload);
} else {
response = {
text: `This is a default postback message for payload: ${payload}!`
};
}
return response;
}
handlePrivateReply(type, object_id) {
let welcomeMessage =
i18n.__("get_started.welcome") +
" " +
i18n.__("get_started.guidance") +
". " +
i18n.__("get_started.help");
let response = Response.genQuickReply(welcomeMessage, [
{
title: i18n.__("menu.suggestion"),
payload: "CURATION"
},
{
title: i18n.__("menu.help"),
payload: "CARE_HELP"
},
{
title: i18n.__("menu.product_launch"),
payload: "PRODUCT_LAUNCH"
}
]);
let requestBody = {
recipient: {
[type]: object_id
},
message: response
};
GraphApi.callSendApi(requestBody);
}
sendMessage(response, delay = 0, isUserRef) {
// Check if there is delay in the response
if (response === undefined || response === null) {
return;
}
if ("delay" in response) {
delay = response["delay"];
delete response["delay"];
}
// Construct the message body
let requestBody = {};
if (isUserRef) {
// For chat plugin
requestBody = {
recipient: {
user_ref: this.user.psid
},
message: response
};
} else {
requestBody = {
recipient: {
id: this.user.psid
},
message: response
};
}
// Check if there is persona id in the response
if ("persona_id" in response) {
let persona_id = response["persona_id"];
delete response["persona_id"];
if (isUserRef) {
// For chat plugin
requestBody = {
recipient: {
user_ref: this.user.psid
},
message: response,
persona_id: persona_id
};
} else {
requestBody = {
recipient: {
id: this.user.psid
},
message: response,
persona_id: persona_id
};
}
}
// Mitigate restriction on Persona API
// Persona API does not work for people in EU, until fixed is safer to not use
delete requestBody["persona_id"];
setTimeout(() => GraphApi.callSendApi(requestBody), delay);
}
sendRecurringMessage(notificationMessageToken, delay) {
console.log("Received Recurring Message token");
let requestBody = {},
response,
curation;
//This example will send summer collection
curation = new Curation(this.user, this.webhookEvent);
response = curation.handlePayload("CURATION_BUDGET_50_DINNER");
// Check if there is delay in the response
if (response === undefined) {
return;
}
requestBody = {
recipient: {
notification_messages_token: notificationMessageToken
},
message: response
};
setTimeout(() => GraphApi.callSendApi(requestBody), delay);
}
firstEntity(nlp, name) {
return nlp && nlp.entities && nlp.entities[name] && nlp.entities[name][0];
}
handleReportLeadSubmittedEvent() {
let requestBody = {
custom_events: [
{
_eventName: "lead_submitted"
}
],
advertiser_tracking_enabled: 1,
application_tracking_enabled: 1,
page_id: config.pageId,
page_scoped_user_id: this.user.psid,
logging_source: "messenger_bot",
logging_target: "page"
};
try {
GraphApi.callAppEventApi(requestBody);
} catch (error) {
console.error("Error while reporting lead submitted", error);
}
}
};