-
Notifications
You must be signed in to change notification settings - Fork 0
/
pester.js
297 lines (270 loc) · 9.04 KB
/
pester.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
const argsParser = require('concierge/arguments'),
emailValidator = require('email-validator'),
nodeMailer = require('nodemailer'),
twilio = require('twilio');
let mailTransport = null,
twilioTransport = null,
facebookHandle = null;
const ensure = (name, def, obj) => {
if (!obj) {
obj = exports.config;
}
if (!obj[name]) {
obj[name] = def;
}
};
const privateMessage = (api, event, user, message) => {
api.sendPrivateMessage(`${user.name}, ${event.sender_name} says: ${message}`, user.id);
};
const textMessage = (event, phoneNumber, user, message) => {
ensure(event.event_source, {}, exports.config.stored);
ensure(user.id, {}, exports.config.stored[event.event_source]);
if (phoneNumber === '-') {
if (exports.config.stored[event.event_source][user.id].phone) {
phoneNumber = exports.config.stored[event.event_source][user.id].phone;
}
else if (user.phone) {
phoneNumber = user.phone;
}
else {
throw new Error(`No stored phone number for ${user.name}.`);
}
}
exports.config.stored[event.event_source][user.id].phone = phoneNumber;
user.phone = phoneNumber;
twilioTransport.sendMessage({
to: phoneNumber,
from: exports.config.smsConfig.phoneNumber,
body: message
}, (err, responseData) => {
if (err) {
throw new Error('Could not send the SMS.');
}
});
};
const seenChat = (api, event, user, message) => {
exports.config.seen.push({
id: user.id,
thread: event.thread_id,
name: user.name,
from: event.sender_name,
message: message
});
};
const respondChat = (api, event, user, message) => {
exports.config.respond.push({
id: user.id,
thread: event.thread_id,
name: user.name,
from: event.sender_name,
message: message
});
};
const emailMessage = (event, email, user, message) => {
ensure(event.event_source, {}, exports.config.stored);
ensure(user.id, {}, exports.config.stored[event.event_source]);
if (email === '-') {
if (exports.config.stored[event.event_source][user.id].email) {
email = exports.config.stored[event.event_source][user.id].email;
}
else if (user.email) {
email = user.email;
}
else {
throw new Error(`No stored email for ${user.name}.`);
}
}
exports.config.stored[event.event_source][user.id].email = email;
user.email = email;
mailTransport.sendMail({
from: `"Concierge (pester)" <${exports.config.emailConfig.auth.user}>`,
to: email,
subject: 'Pester',
html: `<h3>Pester</h3><p>This is a pester from <span style="color:red">${event.sender_name}</span> for <span style="color:cyan">${user.name}</span>.</p><hr /><p>${message}</p>`
}, (error, info) => {
if (error) {
console.critical(error);
throw new Error('Email could not be sent.');
}
});
};
const onMessage = (api, event) => {
for (let i = 0; i < exports.config.respond.length; i++) {
const pester = exports.config.respond[i];
if (event.thread_id == pester.thread && event.sender_id == pester.id) {
exports.config.respond.splice(i, 1);
i--;
api.sendMessage(`@${pester.name}, @${pester.from} says: ${pester.message}`, event.thread_id);
}
}
};
const onRead = readObj => {
for (let i = 0; i < exports.config.seen.length; i++) {
const pester = exports.config.seen[i];
if (readObj.thread_id == pester.thread && readObj.sender_id == pester.id) {
exports.config.seen.splice(i, 1);
i--;
facebookHandle.getApi().sendMessage(`@${pester.name}, @${pester.from} says: ${pester.message}`, readObj.thread_id);
}
}
};
const onStart = status => {
if (status.success && !facebookHandle && status.integration.__descriptor.name === 'facebook') {
facebookHandle = status.integration;
facebookHandle.on('read', onRead);
}
};
const onPreStop = integ => {
if (facebookHandle && integ.__descriptor.name === 'facebook') {
facebookHandle.removeListener('read', onRead);
facebookHandle = null;
}
};
exports.load = platform => {
ensure('seen', []);
ensure('respond', []);
ensure('stored', {});
platform.on('message', onMessage);
if (exports.config.emailConfig) {
mailTransport = nodeMailer.createTransport(exports.config.emailConfig);
}
else {
LOG.warn('Email SMTP server has not been configured');
}
if (exports.config.smsConfig) {
twilioTransport = twilio(exports.config.smsConfig.sid, exports.config.smsConfig.token);
}
else {
LOG.warn('SMS settings have not been configured');
}
facebookHandle = platform.modulesLoader.getLoadedModules('integration')
.find(i => i.__descriptor.name === 'facebook' && i.__descriptor.__running);
if (facebookHandle) {
facebookHandle.on('read', onRead);
}
platform.modulesLoader.on('start', onStart);
platform.modulesLoader.on('prestop', onPreStop);
};
exports.unload = platform => {
platform.modulesLoader.removeListener('start', onStart);
platform.modulesLoader.removeListener('prestop', onPreStop);
if (facebookHandle) {
facebookHandle.removeListener('read', onRead);
}
facebookHandle = null;
platform.removeListener('message', onMessage);
};
exports.run = (api, event) => {
const pesterQueue = [];
const pesterArgs = [
{
long: '--private',
short: '-pm',
description: 'Sends a private message to the person on this integration.',
run: () => {
pesterQueue.push(privateMessage.bind(this, api, event));
}
},
{
long: '--textmessage',
short: '-tx',
description: 'Sends a text message to the persons phone.',
expects: ['PHONE_NUM'],
defaults: ['-'],
run: (out, vals) => {
if (!/^\+?[0-9]+$/.test(vals[0]) && vals[0] !== '-') {
throw new Error('Invalid phone number provided, please use international format (e.g. +64123456789)');
}
if (!exports.config.smsConfig) {
throw new Error('Please configure your SMS settings (see https://twilio.github.io/twilio-node) and restart the module before continuing.');
}
pesterQueue.push(textMessage.bind(this, event, vals[0]));
}
},
{
long: '--seen',
short: '-se',
description: 'Sends a message to the persons the next time they are seen in this chat.',
run: () => {
if (event.event_source.indexOf('facebook') < 0) {
throw new Error('Seen is currently only supported on facebook.');
}
pesterQueue.push(seenChat.bind(this, api, event));
}
},
{
long: '--respond',
short: '-re',
description: 'Sends a message to the persons the next time they send something in this chat.',
run: () => {
pesterQueue.push(respondChat.bind(this, api, event));
}
},
{
long: '--email',
short: '-em',
description: 'Sends a message to the persons the next time they send something in this chat.',
expects: ['EMAIL'],
defaults: ['-'],
run: (out, vals) => {
if (!emailValidator.validate(vals[0]) && vals[0] !== '-') {
throw new Error('Invalid email address');
}
if (!exports.config.emailConfig) {
throw new Error('Please configure your email settings (see https://nodemailer.com/) and restart the module before continuing.');
}
pesterQueue.push(emailMessage.bind(this, event, vals[0]));
}
}
];
let args;
try {
args = argsParser.parseArguments(event.arguments.slice(1), pesterArgs, {
enabled: true,
string: `${api.commandPrefix}pester [name/id] [message...]`,
colours: false
});
}
catch (e) {
return api.sendMessage(e.message, event.thread_id);
}
if (args.parsed['-h']) {
return api.sendMessage(args.parsed['-h'].out, event.thread_id);
}
if (args.unassociated.length < 2) {
return api.sendMessage('Both a name/id and a message must be provided.', event.thread_id);
}
const message = args.unassociated.slice(1).join(' ');
if (args.parsed['-tx'] && message.length > 160) {
return api.sendMessage('The maximum length of a text message is 160 characters. Please shorten your message.', event.thread_id);
}
const inputUser = args.unassociated[0].trim().toLowerCase();
const users = api.getUsers(event.thread_id);
const searchResults = Object.keys(users).filter(u => {
const usr = users[u];
const t = u.trim().toLowerCase();
return t.startsWith(inputUser) || usr.name.trim().toLowerCase().startsWith(inputUser) || usr.id === inputUser || u === inputUser;
});
if (searchResults.length > 1) {
return api.sendMessage(`Don't know who you mean by "${args.unassociated[0]}":\n- ${searchResults.map(u => `${u}: ${users[u].name}`).join('\n- ')}`, event.thread_id);
}
else if (searchResults === 0) {
return api.sendMessage(`Ummmm, well... this is akward. Who is ${args.unassociated[0]}?`, event.thread_id);
}
if (pesterQueue.length === 0) {
return api.sendMessage('I would pester, but you never told me how...', event.thread_id);
}
const user = users[searchResults[0]];
if (!user.id) {
user.id = searchResults[0];
}
api.sendMessage(`Pestering ${user.name} with the message "${message}". Options: ${Object.keys(args.parsed).join(', ')}.`, event.thread_id);
for (let pester of pesterQueue) {
try {
pester(user, message);
}
catch (e) {
api.sendMessage(e.message, event.thread_id);
}
}
};