-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
257 lines (239 loc) · 7.86 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
let jwt = require('jsonwebtoken');
const utils = require('./utils');
const bodyParser = require('body-parser');
class MessengerxSdk {
/**
*Creates an instance of MessengerxSdk.
* @param {*} api_token The api token generated when you create a new bot in https://portal.messengerx.io
* @param {*} env The MessengerX environment you wish to use. Default will be dev. If your bot is published, use 'prod'
* @param {*} app The express server object.
* @memberof MessengerxSdk
*/
constructor(api_token, env, app) {
this.api_token = api_token || new Error('missing api token');
this.env = env || 'dev';
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
})
);
}
//////////////////////////
// Sending helpers
//////////////////////////
/**
*
*
* @param {*} req Express request object
* @param {*} messageText Text you wish to respond to user
* @returns
* @memberof MessengerxSdk
*/
async sendTextMessage(req, messageText) {
const userID = this.getUserFromRequest(req);
if (!userID || userID == null) return new Error('Invalid request!');
var messageData = {
users: [userID],
message: {
text: messageText,
},
};
return utils.post(this.env, messageData, utils.services.message, this.api_token);
}
/**
*
*
* @param {*} req Express request object
* @param {*} messageText Text you wish to respond to user
* @param {*} buttons Buttons you want to display to the user. Expects an object with 3 properties: title: Display Text, type: postback | web_url, payload: text to be sent to bot.
* Format : {
* "title": "Hi",
* "type": "postback",
* "payload": "hi"
* }
* @param {*} quickReplies Quick replies you want to display to the user. Expects an object with 3 properties: title: Display Text, content_type: text, payload: text to be sent to bot.
* @returns
* @memberof MessengerxSdk
*/
async sendButtonsOrQuickRepliesMessage(req, messageText, buttons, quickReplies) {
if (!req) return new Error('missing request object');
if (!messageText) messageText = '';
if (!buttons) buttons = [];
if (!quickReplies) quickReplies = [];
if (messageText === '' && buttons.length === 0 && quickReplies.length === 0)
return new Error('cannot send empty message.');
try {
const userID = this.getUserFromRequest(req);
if (!userID || userID == null) return new Error('Invalid request! Missing User.');
let errs = [];
//more validation
if (buttons.length > 0) {
buttons.map(function (l) {
if (l.type !== 'postback' && l.type !== 'web_url') throw Error(`invalid button type: ${l.type}`);
if (!l.title) throw Error('Missing button title');
if (!l.url && !l.payload) throw Error('Missing button / url payload');
});
}
var messageData = {
users: [userID],
message: {
text: messageText,
},
};
if (buttons.length > 0) {
messageData.message = {
attachment: {
type: 'template',
payload: {
template_type: 'button',
text: messageText,
buttons: buttons,
},
},
};
if (quickReplies.length > 0) messageData.message.quick_replies = quickReplies;
} else if (quickReplies.length > 0) messageData.message.quick_replies = quickReplies;
return utils.post(this.env, messageData, utils.services.message, this.api_token);
} catch (error) {
throw error;
}
}
/**
*
*
* @param {*} req Express request object
* @param {*} messageText Text you wish to respond to user
* @param {*} payload Array of carousel objects with format as below. Visit https://messengerx.readthedocs.io/en/latest/#get-started for more info.
* Format : {
* title: 'Carousel Title',
* subtitle: 'Carousel subtitle',
* image_url: 'Carousel image url',
* buttons: Array of button objects,
* }
* @param {*} quickReplies Quick replies you want to display to the user. Expects an object with 3 properties: title: Display Text, content_type: text, payload: text to be sent to bot.
* @returns
* @memberof MessengerxSdk
*/
async sendCarousel(req, messageText, payload, quickReplies) {
if (!req) return new Error('missing request object');
if (!messageText) messageText = '';
if (!payload.buttons) payload.buttons = [];
if (!quickReplies) quickReplies = [];
if (messageText === '' && payload.buttons.length === 0 && quickReplies.length === 0)
return new Error('cannot send empty message.');
try {
const userID = this.getUserFromRequest(req);
if (!userID || userID == null) return new Error('Invalid request! Missing User.');
let errs = [];
//more validation
if (payload.length > 0) {
payload.map((p) => {
p.buttons.map(function (l) {
if (l.type !== 'postback' && l.type !== 'web_url')
throw Error(`invalid button type: ${l.type}`);
if (!l.title) throw Error('Missing button title');
if (!l.payload) throw Error('Missing button payload');
});
});
}
var messageData = {
users: [userID],
message: {
text: messageText,
},
};
if (payload.length > 0) {
messageData.message = {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: [],
},
},
};
if (payload.length > 0) {
payload.map((p) => {
messageData.message.attachment.payload.elements.push({
title: p.title || ' ',
subtitle: p.subtitle || ' ',
image_url: p.image_url || ' ',
buttons: p.buttons,
});
});
}
if (quickReplies.length > 0) messageData.message.quick_replies = quickReplies;
} else if (quickReplies.length > 0) messageData.message.quick_replies = quickReplies;
return utils.post(this.env, messageData, utils.services.message, this.api_token);
} catch (error) {
throw error;
}
}
async addUserTag(tag, values, req, userId) {
if (!req) throw new Error('missing express req object');
if (!tag) throw new Error('missing tag');
if (!values) throw new Error('missing values');
if (typeof values === 'string') {
if (values.length < 1) throw new Error('value cannot be empty');
else values = [values];
}
const u = userId || this.getUserFromRequest(req);
return utils.post(
this.env,
{
tag: tag,
status: 1,
values: values,
displayName: tag,
},
utils.services.tag,
this.api_token,
`${u}`
);
}
async getUserTags(req, userId) {
if (!req) throw new Error('missing express req object');
const u = userId || this.getUserFromRequest(req);
return utils.get(this.env, utils.services.userTags, `${u}`, this.api_token);
}
getUserFromRequest(req) {
if (!req) throw new Error('missing body object');
return req.headers.user_id || new Error('missing user id. please contact administrator');
}
getMessagingEntries(body) {
let self = this;
const val = body.messaging && Array.isArray(body.messaging) && body.messaging.length > 0 && body.messaging;
return val || null;
}
getUserMessages(req) {
if (!req.body) throw new Error('missing body object');
let body = req.body;
let _rawBody = req.body && req.body.raw;
let userID = this.getUserFromRequest(req);
let that = this;
if (!_rawBody || !userID)
throw new Error(
'Unauthorized Client Request, Bot is not available at this time, Please contact us at [email protected]'
);
return jwt.verify(_rawBody, this.api_token, { algorithms: ['HS512'] }, function (err, decoded) {
if (err)
throw new Error(
'Unauthorized Client Request, Bot is not available at this time, Please contact us at [email protected]'
);
try {
let _body =
decoded && decoded.sub && decoded.sub.messaging ? decoded.sub : JSON.parse(decoded && decoded.sub);
let resu = that.getMessagingEntries(_body);
return resu;
} catch (error) {
throw new Error(`Error while parsing incoming message: ${error}`);
}
});
}
getUser(messaging) {
const val = messaging.user;
return val || null;
}
}
module.exports = MessengerxSdk;