-
Notifications
You must be signed in to change notification settings - Fork 39
/
discord.js
464 lines (397 loc) · 13.4 KB
/
discord.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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
module.exports = class DiscordController extends require("./template.js") {
constructor () {
super();
this.platform = sb.Platform.get("discord");
if (!this.platform) {
throw new sb.Error({
message: "Discord platform has not been created"
});
}
else if (!this.platform.Self_ID) {
throw new sb.Error({
message: "Discord user ID (Platform/Self_ID) has not been configured"
});
}
else if (!sb.Config.has("DISCORD_BOT_TOKEN", true)) {
throw new sb.Error({
message: "Discord bot token has not been configured"
});
}
const { Client, Intents } = require("discord.js");
const intents = new Intents();
intents.add(Intents.NON_PRIVILEGED, "GUILD_MEMBERS");
this.client = new Client({
ws: { intents },
disableMentions: "everyone"
});
this.initListeners();
this.client.login(sb.Config.get("DISCORD_BOT_TOKEN"));
}
initListeners () {
const client = this.client;
client.on("ready", async () => {
const active = client.channels.cache.filter(i => i.type === "text");
const joinable = sb.Channel.getJoinableForPlatform("discord");
for (const channel of joinable) {
const exists = active.find(i => i.id === channel.Name);
if (!exists) {
channel.Mode = "Inactive";
await channel.saveProperty("Mode", channel.Mode);
console.debug("Discord channel set as inactive", channel);
}
}
});
client.on("message", async (messageObject) => {
const {
commandArguments,
chan,
discordID,
guild,
msg,
mentions,
privateMessage,
user
} = this.parseMessage(messageObject);
if (Array.from(user).length > 32) {
console.debug("Invalid Discord username! user.length > 32, skipping", {
chan, discordID, guild, msg, user, userLength: user.length
});
return;
}
let channelData = null;
const userData = await sb.User.get(user, false, { Discord_ID: discordID });
if (userData) {
if (userData.Discord_ID === null && userData.Twitch_ID !== null) {
if (!this.platform.Data.sendVerificationChallenge) {
// No verification challenge - just assume it's correct
await userData.saveProperty("Discord_ID", discordID);
}
else {
if (userData.Data.discordChallengeNotificationSent || !msg.startsWith(sb.Command.prefix)) {
return;
}
const { challenge } = await DiscordController.createAccountChallenge(userData, discordID);
userData.Data.discordChallengeNotificationSent = true;
await userData.saveProperty("Data");
await this.directPm(
discordID,
sb.Utils.tag.trim `
You were found to be likely to own a Twitch account with the same name as your current Discord account.
If you want to use my commands on Discord, whisper me the following command on Twitch:
${sb.Command.prefix}link ${challenge}
`
);
return;
}
}
else if (userData.Discord_ID === null && userData.Twitch_ID === null) {
await userData.saveProperty("Discord_ID", discordID);
}
else if (userData.Discord_ID !== discordID) {
// Mismatch between discordID and userData.Discord_ID means someone renamed into a different
// user's username, or that there is a different mishap happening. This case is unfortunately exceptional
// for the current user-database structure and the event handler must be aborted.
return;
}
}
else {
// No user data available at this point usually means that the object is being fetched from cache.
// Still, fire a "raw user" message event
const channelData = sb.Channel.get(chan, this.platform);
if (channelData) {
channelData.events.emit("message", {
event: "message",
message: msg,
user: null,
channel: channelData,
platform: this.platform,
raw: { user }
});
}
return;
}
if (!privateMessage) {
channelData = sb.Channel.get(chan, this.platform);
if (!channelData) {
channelData = await sb.Channel.add(chan, this.platform);
await channelData.setup();
}
// If a message comes from a channel set as "Inactive", this means it is active again.
// Change its mode back to active.
if (channelData.Mode === "Inactive") {
channelData.Mode = "Write";
await channelData.saveProperty("Mode", channelData.Mode);
}
const channelDescription = `${guild.name} - #${messageObject.channel.name}`;
if (channelData.Description !== channelDescription) {
await channelData.saveProperty("Description", channelDescription);
}
if (channelData.NSFW !== messageObject.channel.nsfw) {
await channelData.saveProperty("NSFW", messageObject.channel.nsfw);
}
channelData.sessionData.lastActivity = {
user: userData.ID,
date: new sb.Date().valueOf()
};
this.resolveUserMessage(channelData, userData, msg);
sb.Logger.push(sb.Utils.wrapString(msg, this.platform.Message_Limit), userData, channelData);
channelData.events.emit("message", {
type: "message",
message: msg,
user: userData,
channel: channelData,
platform: this.platform
});
if (channelData.Mode !== "Read") {
sb.AwayFromKeyboard.checkActive(userData, channelData);
sb.Reminder.checkActive(userData, channelData);
// Mirroring is set up - mirror the message to the target channel
if (channelData.Mirror) {
this.mirror(msg, userData, channelData);
}
}
}
else {
this.resolveUserMessage(null, userData, msg);
}
if (channelData && channelData.Mode === "Read") {
return;
}
// Own message - skip
if (discordID === this.platform.Self_ID) {
return;
}
// Starts with correct prefix - handle command
if (sb.Command.is(msg)) {
const commandPrefix = sb.Command.prefix;
const command = msg.replace(commandPrefix, "").split(" ").find(Boolean);
const args = (commandArguments[0] === commandPrefix)
? commandArguments.slice(2)
: commandArguments.slice(1);
if (messageObject.reference) {
const { channelID, messageID } = messageObject.reference;
const referenceChannel = await this.client.channels.fetch(channelID);
const referenceMessageObject = await referenceChannel.messages.fetch(messageID);
const { msg } = this.parseMessage(referenceMessageObject);
args.push(...msg.split(" ").filter(Boolean));
}
this.handleCommand(
command,
args.map(i => DiscordController.removeEmoteTags(i)),
channelData,
userData,
{
mentions,
guild,
privateMessage,
member: messageObject.member
}
);
}
});
client.on("error", (err) => {
console.error(err);
this.restart();
});
}
/**
* Sends a message
* @param message
* @param channel
*/
async send (message, channel) {
const globalEmoteRegex = /[A-Z]/;
const channelData = sb.Channel.get(channel, this.platform);
const channelObject = await this.client.channels.fetch(channelData.Name);
if (!channelObject) {
console.warn("No Discord channel available!", channel);
return;
}
if (channelObject.guild) {
const wordSet = new Set(message.split(/\W+/).filter(Boolean));
const globalEmotesMap = this.client.emojis.cache;
const guildEmotesMap = channelObject.guild.emojis.cache;
for (const word of wordSet) {
// First, attempt to find a unique global emoji available to the bot
let emote;
const globalEmotes = globalEmotesMap.filter(i => i.name === word);
if (globalEmotes.size > 0) {
// If there are multiple, try to find it in the current guild's emojis cache and use it
emote = guildEmotesMap.find(i => i.name === word);
// If not found and the word is not overly common, simply pick a random emote out of the global list
if (!emote && globalEmoteRegex.test(word)) {
emote = sb.Utils.randArray([...globalEmotes.values()]);
}
}
if (emote) {
// This regex makes sure all emotes to be replaces are not preceded or followed by a ":" (colon) character
// All emotes on Discord are wrapped at least by colons
const regex = new RegExp(`(?<!(:))\\b${emote.name}\\b(?!(:))`, "g");
message = message.replace(regex, emote.toString());
}
}
const guildUsers = await channelObject.guild.members.fetch();
const sortedUsers = guildUsers.array().sort((a, b) => b.user.username.length - a.user.username.length);
for (const member of sortedUsers) {
const name = sb.User.normalizeUsername(member.user.username);
const regex = new RegExp(`@${sb.Utils.escapeRegExp(name)}`, "gi");
message = message.replace(regex, `<@${member.user.id}>`);
}
}
channelObject.send(sb.Utils.wrapString(message, channelData.Message_Limit ?? this.platform.Message_Limit));
}
/**
* Sends a private message.
* The user in question must have their Discord ID filled out, otherwise the method fails.
* @param {string} message
* @param {User|string|number} user
* @returns {Promise<void>}
* @throws {sb.Error} If the provided user does not exist
* @throws {sb.Error} If the provided user has no Discord ID connected.
*/
async pm (message, user) {
const userData = await sb.User.get(user, true);
if (!userData.Discord_ID) {
throw new sb.Error({
message: `Discord PM attempt: User ${userData.Name} has no Discord ID`
});
}
const discordUser = await this.client.users.fetch(userData.Discord_ID);
await discordUser.send(message);
}
/**
* Directly sends a private message to user, without them necessarily being saved as a user.
* @param {string} userID
* @param {string }msg
* @returns {Promise<void>}
*/
async directPm (userID, msg) {
const discordUser = await this.client.users.fetch(userID);
await discordUser.send(msg);
}
/**
* Handles command execution.
* @param {string} command Command invocation string
* @param {User} userData
* @param {Channel} channelData
* @param {Array} args
* @param {Object} options = {}
* @returns {Promise<void>}
*/
async handleCommand (command, args, channelData, userData, options = {}) {
const execution = await sb.Command.checkAndExecute(command, args, channelData, userData, {
platform: this.platform,
...options
});
if (!execution || !execution.reply) {
return;
}
if (channelData?.Mirror) {
this.mirror(execution.reply, userData,channelData, true);
}
if (options.privateMessage || execution.replyWithPrivateMessage) {
const message = await this.prepareMessage(execution.reply, null);
this.pm(message, userData);
}
else {
const message = await this.prepareMessage(execution.reply, channelData, { skipBanphrases: true });
this.send(message, channelData);
}
}
destroy () {
this.client && this.client.destroy();
this.client = null;
}
parseMessage (messageObject) {
const links = messageObject.attachments.map(i => i.proxyURL);
const args = [
...messageObject.content.split(" "),
...links
];
for (let i = 0; i < args.length; i++) {
const match = args[i].match(/<@!?(\d+)>/);
if (match) {
const user = messageObject.mentions.users.get(match[1]);
if (user) {
args[i] = `@${user.username}`;
}
}
}
let index = 0;
let targetMessage = messageObject.cleanContent.replace(/\n/g, " ");
while (targetMessage.length < this.platform.Message_Limit && index < links.length) {
targetMessage += ` ${links[index]}`;
index++;
}
return {
msg: DiscordController.removeEmoteTags(targetMessage.replace(/\s+/g, " ")),
user: messageObject.author.username.toLowerCase().replace(/\s/g, "_"),
chan: messageObject.channel.id,
channelType: messageObject.channel.type,
discordID: String(messageObject.author.id),
author: messageObject.author,
mentions: messageObject.mentions,
guild: messageObject?.channel?.guild ?? null,
privateMessage: Boolean(messageObject.channel.type === "dm"),
commandArguments: args
};
}
async isUserChannelOwner (channelData, userData) {
if (userData === null || channelData === null) {
return false;
}
const channel = await this.client.channels.fetch(channelData.Name);
if (!channel || !channel.guild) {
return false;
}
return (channel.guild.owner === userData.Discord_ID);
}
async fetchUserList (channelIdentifier) {
const channel = await this.client.channels.fetch(channelIdentifier);
const guild = await channel.guild.fetch();
await Promise.all([
guild.members.fetch(),
guild.roles.fetch()
]);
return [...channel.members.values()].map(i => i.user.username);
}
async fetchChannelEmotes (channelData) {
const discordChannel = await this.client.channels.fetch(channelData.Name);
const guild = await this.client.guilds.fetch(discordChannel.guild.id);
const emojis = guild.emojis.cache.array();
return emojis.map(i => ({
ID: i.id,
name: i.name,
type: "discord",
global: false,
animated: (i.animated)
}));
}
async fetchGlobalEmotes () {
return this.client.emojis.cache.array().map(i => ({
ID: i.id,
name: i.name,
type: "discord",
global: true,
animated: (i.animated)
}));
}
static removeEmoteTags (message) {
return message.replace(/<a?:(.*?):(\d*)>/g, (total, emote) => `${emote} `).trim();
}
static async createAccountChallenge (userData, discordID) {
const row = await sb.Query.getRow("chat_data", "User_Verification_Challenge");
const challenge = require("crypto").randomBytes(16).toString("hex");
row.setValues({
User_Alias: userData.ID,
Specific_ID: discordID,
Challenge: challenge,
Platform_From: sb.Platform.get("discord").ID,
Platform_To: sb.Platform.get("twitch").ID
});
await row.save();
return {
challenge
};
}
};