This repository was archived by the owner on Mar 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathindex.js
More file actions
145 lines (133 loc) · 4.46 KB
/
index.js
File metadata and controls
145 lines (133 loc) · 4.46 KB
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
const express = require('express'),
bodyParser = require('body-parser'),
rp = require('request-promise'),
request = require('request'),
path = require("path");
require('dotenv').config();
app = express();
app.use(bodyParser.json());
// Whitelist the domain Name
var request_body;
// Create a request Body.
request_body = {
"whitelisted_domains": [`${process.env.URL}`]
}
// Send the request after setting up the request_body.
var options = {
method: 'POST',
uri: `https://graph.facebook.com/v7.0/me/messenger_profile?access_token=${process.env.PAGE_ACCESS_TOKEN}`,
body: request_body,
json: true
};
try{
rp(options);
} catch (e){
console.log(e);
}
// Setting the Callback URL.
request(
{
uri: `https://graph.facebook.com/v7.0/${process.env.APP_ID}/subscriptions`,
qs: {
access_token: `${process.env.APP_ID}|${process.env.APP_SECRET}`,
object: "page",
callback_url: `${process.env.URL}/webhook`,
verify_token: process.env.VERIFY_TOKEN,
fields: "messages, messaging_postbacks, messaging_optins, message_deliveries",
include_values: "true"
},
method: "POST"
},
(error, _res, body) => {
if (!error) {
console.log("Callback URL:", body);
} else {
console.error("Callback URL have issues:", error);
}
}
);
// Webhook Endpoint
app.post('/webhook', (req, res) => {
let body = req.body;
// Checks this is an event from a page subscription
if (body.object === 'page') {
// Iterates over each entry - there may be multiple if batched
body.entry.forEach(function(entry) {
// Gets the body of the webhook event
if(entry.messaging){
webhook_event = entry.messaging[0];
// Get the sender PSID
let sender_psid = webhook_event.sender.id;
// If optins like "OTN"
if (webhook_event.optin){
console.log(webhook_event);
}
if(webhook_event.message && sender_psid !== `${process.env.PAGE_ID}` && !webhook_event.message.quick_reply){
hanldeMessages(sender_psid, webhook_event);
} else if (webhook_event.postback || (webhook_event.message && webhook_event.message.quick_reply)){
hanldePostback(sender_psid, webhook_event);
}
}
});
// Returns a '200 OK' response to all requests
res.status(200).send('EVENT_RECEIVED');
} else {
// Returns a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});
// Adds support for GET requests to our webhook
app.get('/webhook', (req, res) => {
// Parse the query params
let mode = req.query['hub.mode'];
let token = req.query['hub.verify_token'];
let challenge = req.query['hub.challenge'];
// Checks if a token and mode is in the query string of the request
if (mode && token) {
// Checks the mode and token sent is correct
if (mode === 'subscribe' && token === process.env.VERIFY_TOKEN) {
// Responds with the challenge token from the request
console.log('WEBHOOK_VERIFIED');
res.status(200).send(challenge);
} else {
// Responds with '403 Forbidden' if verify tokens do not match
res.sendStatus(403);
}
}
});
// Handle Messages
function hanldeMessages(sender_psid, webhook_event){
// You can Check for Specific Text and send other response.
console.log(webhook_event);
response = {"text":`You sent Text Message '${webhook_event.message.text}'`};
callSendAPI(sender_psid, response);
}
// Handle Postbacks
function hanldePostback(sender_psid, webhook_event){
// You can Check for Specific Postback and send other response.
console.log(webhook_event);
response = {"text":`You sent Text Message '${webhook_event.postback.title}'`};
callSendAPI(sender_psid, response);
}
// Call Send API Function
function callSendAPI(sender_psid, response){
token = process.env.PAGE_ACCESS_TOKEN;
persona_id = null;
request_body = {
"recipient": {
"id": sender_psid
},
"message": response,
"persona_id":persona_id
}
var options = {
method: 'POST',
uri: `https://graph.facebook.com/v7.0/me/messages?access_token=${token}`,
body: request_body,
json: true
};
rp(options);
console.log("sent");
}
// listen for webhook events //
app.listen(process.env.PORT || 3370, () => console.log('webhook is listening'));