-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
392 lines (364 loc) Ā· 11.1 KB
/
bot.js
File metadata and controls
392 lines (364 loc) Ā· 11.1 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
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
const Discord = require('discord.js');
const config = require('config');
const _ = require('lodash');
const schedule = require('node-schedule');
const moment = require('moment');
const chrono = require('chrono-node');
const Promise = require('bluebird');
const logger = require('./src/utils/Logger');
const Database = require('./src/providers/Database'); // eslint-disable-line
const ScheduleMessageSchema = require('./src/models/scheduleMessage');
const schedulers = []; // List of users scheduling messages
const bot = new Discord.Client({ autoReconnect: true, max_message_cache: 0 });
const getResponseMessage = async message => {
const collected = await message.channel.awaitMessages(
response => {
return message.author.id === response.author.id;
},
{
max: 1,
time: 20000,
errors: ['time']
}
);
const responseMessage = collected.first();
if (
_.includes(['quit', 'exit', 'cancel'], _.toLower(responseMessage.content))
) {
throw new Error('Message scheduling canceled.');
}
return responseMessage;
};
const fetchAuthor = async authorId => bot.users.get(authorId);
const fetchScheduleChannel = async scheduleChannelId =>
bot.channels.get(scheduleChannelId);
const getScheduledMessageById = async ({ id, authorId = false } = {}) => {
try {
const query = {
active: true,
scheduledDate: { $gt: Date.now() },
_id: id
};
if (authorId) {
query.authorId = { $eq: authorId };
}
const scheduledMessage = await ScheduleMessageSchema.findOne(query);
return scheduledMessage;
} catch (err) {
logger.error('Error while trying to fetch scheduled messages %j', err);
throw new Error(`Scheduled message not found (id: ${id})`);
}
};
const getScheduledMessages = async (authorId = false) => {
try {
const query = {
active: true,
scheduledDate: { $gt: Date.now() }
};
if (authorId) {
query.authorId = { $eq: authorId };
}
const scheduledMessages = await ScheduleMessageSchema.find(query);
const sm = await Promise.map(scheduledMessages, async scheduledMessage => {
try {
const author = await fetchAuthor(scheduledMessage.authorId);
const scheduleChannel = await fetchScheduleChannel(
scheduledMessage.scheduleChannelId
);
return {
id: scheduledMessage._id.toString(),
author,
scheduleChannel,
scheduleGuild: scheduleChannel.guild || undefined,
message: scheduledMessage.message,
scheduledDate: moment(scheduledMessage.scheduledDate).format(
'YYYY-MM-DD HH:mm'
),
createdDate: moment(scheduledMessage.createdDate).format(
'YYYY-MM-DD HH:mm'
),
scheduledMessageObject: scheduledMessage
};
} catch (err) {
logger.error('Error fetching author or schedule channel : %j', err);
return false;
}
});
return _.compact(sm);
} catch (err) {
logger.error('Error while trying to fetch scheduled messages %j', err);
return false;
}
};
bot.login(config.discord.token);
bot.on('ready', async () => {
logger.info('Starting scheduler bot...');
const scheduledMessages = await getScheduledMessages(); // (because we're changing db items)
/* eslint-disable no-param-reassign */
await Promise.map(scheduledMessages, scheduledMessage => {
schedule.scheduleJob(
scheduledMessage.id,
scheduledMessage.scheduledDate,
async () => {
scheduledMessage.scheduleChannel.send(scheduledMessage.message);
scheduledMessage.scheduledMessageObject.active = false;
await scheduledMessage.scheduledMessageObject.save();
}
);
});
/* eslint-enable no-param-reassign */
});
bot.on('message', async message => {
if (0 !== message.content.indexOf(config.discord.prefix)) {
return;
}
const prefixLength = _.size(config.discord.prefix);
const args = _.split(message.content, ' ');
const command = _.toLower(args.shift().substr(prefixLength));
if (!_.includes(['schedule'], command)) {
return;
}
if (0 < _.size(args)) {
if ('list' === _.first(args)) {
const listAllCondition =
'all' === _.nth(args, 1) && message.author.id === config.ownerId
? null
: message.author.id;
const scheduledMessages = await getScheduledMessages(listAllCondition);
const smList = _(scheduledMessages)
.map(
sm =>
`Id: ${sm.id}\nChannel: ${sm.scheduleChannel.name} (${sm.scheduleGuild.name})\nMessage: ${sm.message}\nDate: ${sm.scheduledDate}`
)
.join('\n');
message.channel.send(`${smList || 'No scheduled messages.'}`, {
split: true
});
} else if ('delete' === _.first(args)) {
const deletedId = _.nth(args, 1);
if (!deletedId) {
await message.channel.send({
embed: {
color: _.random(1, 16777214),
fields: [
{
name: '**__Error__**',
value: `Missing argument: id of message schedule to delete.\nUsage: ${config.discord.prefix}${command} delete [scheduleId]`
}
]
}
});
return;
}
try {
const scheduleMessage = await getScheduledMessageById({
id: deletedId
});
const scheduleJob = _.get(schedule.scheduledJobs, deletedId);
if (scheduleJob) {
scheduleJob.cancel();
}
scheduleMessage.active = false;
await scheduleMessage.save();
message.channel.send(`Scheduled message (id: ${deletedId}) deleted.`);
} catch (err) {
logger.error('Error deleting schedule message %s: %j', deletedId, err);
await message.channel.send({
embed: {
color: _.random(1, 16777214),
fields: [
{
name: '**__Error__**',
value: `Error deleting schedule message (id: ${deletedId}), message not found.`
}
]
}
});
}
} else if ('help' === _.first(args)) {
await message.channel.send({
embed: {
color: _.random(1, 16777214),
fields: [
{
name: `${config.discord.prefix}schedule`,
value: `Message scheduling`
},
{
name: `${config.discord.prefix}schedule list`,
value: `List all scheduled messages`
},
{
name: `${config.discord.prefix}schedule delete [scheduleId]`,
value: `Delete a scheduled message (with the id returned with \`${config.discord.prefix}schedule list\`)`
}
]
}
});
}
return;
}
if (_.includes(schedulers, message.author.id)) {
// Already in scheduling process
return;
}
schedulers.push(message.author.id);
await message.channel.send({
embed: {
color: _.random(1, 16777214),
fields: [
{
name: 'š ',
value: 'Which channel do you want the message to be scheduled in ?'
}
]
}
});
try {
const channelMessage = await getResponseMessage(message);
const [broadcastChannel] = bot.channels
.filter(
chan => 'text' === chan.type && channelMessage.content === chan.id
)
.array();
if (_.isEmpty(broadcastChannel) || !broadcastChannel.guild) {
throw new Error('Cannot find channel.');
}
const member = broadcastChannel.guild.member(message.author);
if (!member) {
throw new Error('You are not on this discord guild.');
}
if (!member.permissions.has('ADMINISTRATOR')) {
throw new Error('You cannot schedule a message for this channel.');
}
await message.channel.send({
embed: {
color: _.random(1, 16777214),
fields: [
{
name: '**__š Schedule message channel__**',
value: `\`${broadcastChannel.guild} - ${broadcastChannel.name}\``
},
{
name: '\u200B',
value: '\u200B'
},
{
name: 'ā°',
value: 'When do you want the message to be scheduled on ?'
}
]
}
});
const scheduleDate = await getResponseMessage(message);
const chronoDate = chrono.parseDate(scheduleDate.content);
const formatedDate = moment(chronoDate);
if (!formatedDate.isValid()) {
throw new Error('Invalid date');
}
if (moment().isAfter(formatedDate)) {
throw new Error(
`Date in the past. (${formatedDate.format('YYYY-MM-DD HH:mm')})`
);
}
if (formatedDate.isAfter(moment().add(2, 'months'))) {
throw new Error(
`Schedule date must be lower than 2 months. (${formatedDate.format(
'YYYY-MM-DD HH:mm'
)})`
);
}
await message.channel.send({
embed: {
color: _.random(1, 16777214),
fields: [
{
name: '**__ā° Schedule date__**',
value: formatedDate.format('YYYY-MM-DD HH:mm')
},
{
name: '\u200B',
value: '\u200B'
},
{
name: 'š',
value: 'What is the content of the message to be scheduled ?'
}
]
}
});
const scheduleMessage = await getResponseMessage(message);
const scheduleM = await ScheduleMessageSchema.create({
authorId: message.author.id,
scheduleChannelId: broadcastChannel.id,
scheduleGuildId: broadcastChannel.guild.id,
scheduledDate: formatedDate.format('YYYY-MM-DD HH:mm'),
active: true,
message: scheduleMessage.content
});
schedule.scheduleJob(
scheduleM._id.toString(),
formatedDate.format('YYYY-MM-DD HH:mm'),
async () => {
broadcastChannel.send(scheduleMessage.content);
scheduleM.active = false;
await scheduleM.save();
}
);
logger.info(
`Scheduled ${scheduleMessage.content} by ${message.author.tag} in ${
broadcastChannel.name
} (${broadcastChannel.guild.name}) on ${formatedDate.format(
'YYYY-MM-DD HH:mm'
)}`
);
await message.channel.send({
embed: {
color: _.random(1, 16777214),
fields: [
{
name: '**__š Message Content__**',
value: scheduleMessage.content
},
{
name: '\u200B',
value: '\u200B'
},
{
name: 'š Schedule Channel',
value: broadcastChannel.name
},
{
name: '\u200B',
value: '\u200B'
},
{
name: 'ā° Schedule date',
value: formatedDate.format('YYYY-MM-DD HH:mm')
}
]
}
});
} catch (err) {
logger.error(err);
await message.channel.send({
embed: {
color: _.random(1, 16777214),
fields: [
{
name: '**__Error__**',
value: `${err.message}`
}
]
}
});
}
_.pull(schedulers, message.author.id);
return;
});
bot.on('disconnect', e => {
logger.error(`DISCONNECT: ${e} (${e.code})`);
});
bot.on('error', e => {
logger.error(`ERROR: ${e}`);
});