-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
190 lines (164 loc) · 4.82 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
const rp = require('request-promise');
const NodeCache = require('node-cache');
const myCache = new NodeCache();
const async = require("async")
const Rule = require("./lib/rule.js");
const eventVariables = require("./lib/eventVariables.js")
const {
setContextDelimiter,
responseTypes
} = require("./lib/responseTypes.js")
let version = "v5.0";
let verification_token = "";
const pageTokens = {};
const rules = [];
const on = {}
const callFbApi = (senderId, recipientId, response) => {
return new Promise((resolve, reject) => {
if (!pageTokens[recipientId]) {
return reject(`No token for page '${recipientId}' set.`)
}
const request_body = {
"recipient": {
"id": senderId
},
...response
}
const oReturn = {
"method": "POST",
"qs": {
"access_token": pageTokens[recipientId]
},
"uri": `https://graph.facebook.com/${version}/me/messages`,
"body": request_body,
"json": true
}
// console.log(JSON.stringify(oReturn, null, 2))
// return resolve(true);
// Send the HTTP request to the Messenger Platform
return rp(oReturn)
.then(body => {
if (body.error) {
return reject(body.error);
}
return resolve(true);
})
})
}
const Messenger = function(senderId, recipientId, event) {
this.senderId = senderId;
this.recipientId = recipientId;
this.event = event;
this.response = {};
this.run = response => {
return callFbApi(this.senderId, this.recipientId, response)
}
}
Messenger.prototype = {
//activate typing on chat
typing(isTyping) {
return this.run({
"sender_action": isTyping ? "typing_on" : "typing_off"
})
.then(() => this)
},
process() {
return Promise.resolve()
.then(() => this.typing(true))
.then(() => Promise.all(rules.map(rule => rule._process(this.event))))
.then(values => [].concat(...values))
.then(arrsResponses => {
const exclusiveResponse = arrsResponses.filter(resp => resp.response !== false && resp.exclusive)
if (exclusiveResponse.length) {
// console.log("using exclusive", exclusiveResponse[0])
return [exclusiveResponse[0]];
}
return arrsResponses.filter(resp => resp !== false);
})
.then(arrsResponses => arrsResponses.map(resp => resp.response))
.then(arrsResponses => {
// console.log("responses", arrsResponses)
if (arrsResponses.length) {
return new Promise((resolve, reject) => {
return async.eachSeries(arrsResponses, (response, cb) => {
this.run(response)
.then(() => cb())
.catch(err => cb(err))
}, err => {
if (err)
return reject(err);
resolve()
})
})
}
if (arrsResponses.length)
return Promise.all(arrsResponses.map(response => this.run(response)))
return this.typing(false);
})
.catch(err => on.error && on.error(err))
}
}
module.exports = {
responseTypes,
setContextDelimiter,
onEvent(fFunction) {
on.event = fFunction;
},
onError(fFunction) {
on.error = fFunction;
},
createRule(p_sName) {
const rule = new Rule(p_sName);
rules.push(rule)
return rule;
},
//Webhook functions for express
webhook: {
get(req, res) {
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (mode && token) {
if (mode === 'subscribe' && token === verification_token) {
res.status(200).send(challenge);
} else {
res.sendStatus(403);
}
}
},
post(req, res) {
res.status(200).send('ok');
const body = req.body;
// Check the webhook event is from a Page subscription
if (body.object === 'page') {
// Gets the body of the webhook event
const event = body.entry[0].messaging[0];
const messageID = event.message.mid;
if (!event.message.is_echo && !myCache.get(messageID)) {
on.event && on.event(body);
myCache.set(messageID, messageID, 3000);
// Get the sender PSID
const senderId = event.sender.id;
const recipientId = event.recipient.id;
const oMsg = new Messenger(senderId, recipientId, event);
oMsg.process();
}
}
},
},
//add a new page token
pageToken(p_sPageID, p_sToken) {
if (!p_sToken) return pageTokens[p_sPageID];
pageTokens[p_sPageID] = p_sToken;
},
//set the verification token
verificationToken(p_sToken) {
if (!p_sToken) return p_sToken;
verification_token = p_sToken;
},
//set the FB api version
version(p_sVersion) {
if (!p_sVersion) return p_sVersion;
version = p_sVersion;
}
}