-
Notifications
You must be signed in to change notification settings - Fork 13
/
discord.js
478 lines (431 loc) · 15.2 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import {
ActionRow,
ButtonBuilder,
ButtonStyle,
Colors,
ComponentType,
EmbedBuilder,
Message,
MessageType,
SelectMenuBuilder,
ChannelType,
} from "discord.js";
import CONSTANTS from "../common/CONSTANTS.js";
import { escapeMessage, escapeLinks } from "./markdown.js";
import { generateHash, truncateText } from "./text.js";
import { badAttachments, badStickers, censor } from "../common/moderation/automod.js";
import { MessageActionRowBuilder } from "../common/types/ActionRowBuilder.js";
/**
* @param {import("discord.js").Message | import("discord.js").PartialMessage} message
*
* @returns {Promise<Required<Pick<import("discord.js").BaseMessageOptions, "embeds" | "files">>>}
*/
export async function extractMessageExtremities(message, allowLanguage = true) {
const embeds = [
...(!allowLanguage && typeof (await badStickers(message)).strikes === "number"
? []
: message.stickers.map((sticker) =>
new EmbedBuilder().setImage(sticker.url).setColor(Colors.Blurple),
)),
...message.embeds
.filter((embed) => !embed.video)
.map((oldEmbed) => {
const newEmbed = EmbedBuilder.from(oldEmbed);
const { data } = newEmbed;
if (allowLanguage) return newEmbed;
if (data.description) {
const censored = censor(data.description);
if (censored) newEmbed.setDescription(censored.censored);
}
if (data.title) {
const censored = censor(data.title);
if (censored) newEmbed.setTitle(censored.censored);
}
if (data.url && censor(data.url)) newEmbed.setURL("");
if (data.image?.url && censor(data.image.url)) newEmbed.setImage("");
if (data.thumbnail?.url && censor(data.thumbnail.url)) newEmbed.setThumbnail("");
if (data.footer?.text) {
const censored = censor(data.footer.text);
if (censored) {
newEmbed.setFooter({
text: censored.censored,
iconURL: data.footer.icon_url,
});
}
}
if (data.author) {
const censoredName = censor(data.author.name);
const censoredUrl = data.author.url && censor(data.author.url);
if (censoredName || censoredUrl) {
newEmbed.setAuthor({
name: censoredName ? censoredName.censored : data.author.name,
iconURL: data.author.icon_url,
url: censoredUrl ? "" : data.author.url,
});
}
}
newEmbed.setFields(
(data.fields || []).map((field) => {
const censoredName = censor(field.name);
const censoredValue = censor(field.value);
return {
name: censoredName ? censoredName.censored : field.name,
value: censoredValue ? censoredValue.censored : field.value,
inline: field.inline,
};
}),
);
return newEmbed;
}),
];
while (embeds.length > 10) embeds.pop();
return {
embeds,
files:
!allowLanguage && typeof (await badAttachments(message)).language === "number"
? []
: message.attachments.toJSON(),
};
}
/**
* Get all messages from a channel.
*
* @deprecated Too laggy.
*
* @template {import("discord.js").Message<C extends import("discord.js").GuildTextBasedChannel ? true : false>} T
* @template {import("discord.js").TextBasedChannel} C
*
* @param {C} channel - The channel to fetch messages from.
*
* @returns {Promise<T[]>} - The messages.
*/
export async function getAllMessages(channel) {
/** @type {T[]} */
const messages = [];
/** @type {import("discord.js").Snowflake | undefined} */
// eslint-disable-next-line fp/no-let -- This needs to be changable
let lastId;
do {
// eslint-disable-next-line no-await-in-loop -- We can’t use `Promise.all` here
const fetchedMessages = await channel.messages.fetch({ before: lastId, limit: 100 });
// @ts-expect-error -- This is the right type.
messages.push(...fetchedMessages.toJSON());
lastId = fetchedMessages.lastKey();
} while (lastId);
return messages;
}
/**
* A property that returns the content that is rendered regardless of the message type. In some cases, this just returns the regular message
* content. Otherwise this returns an English message denoting the contents of the system message.
*
* @author [Rapptz/discord.py](https://github.com/Rapptz/discord.py/blob/40986f9/discord/message.py#L1825-L1944).
*
* @param {import("discord.js").Message} message - Message to convert.
*
* @returns {Promise<string>} Text representation of the message.
*/
export async function messageToText(message, replies = true) {
const linklessContent = message.webhookId ? message.content : escapeLinks(message.content);
const actualContent = message.flags.has("Loading")
? (Date.now() - +message.createdAt) / 1_000 / 60 > 15
? CONSTANTS.emojis.discord.error + " The application did not respond"
: CONSTANTS.emojis.discord.typing +
" " +
escapeMessage(message.author.username) +
" is thinking..."
: message.content;
switch (message.type) {
case MessageType.Default: {
return linklessContent;
}
case MessageType.RecipientAdd: {
return (
CONSTANTS.emojis.discord.add +
` ${message.author.toString()} added ${
message.mentions.users.first()?.toString() ?? ""
} to the ${message.guild ? "thread" : "group"}.`
);
}
case MessageType.RecipientRemove: {
return (
CONSTANTS.emojis.discord.remove +
` ${message.author.toString()} removed ${
message.mentions.users.first()?.toString() ?? ""
} from the ${message.guild ? "thread" : "group"}.`
);
}
case MessageType.ChannelNameChange: {
return (
CONSTANTS.emojis.discord.edit +
` ${message.author.toString()} changed the ${
message.channel.isThread() &&
message.channel.parent?.type === ChannelType.GuildForum
? "post title"
: "channel name"
}: **${escapeMessage(message.content)}**`
);
}
case MessageType.ChannelIconChange: {
return (
CONSTANTS.emojis.discord.edit +
` ${message.author.toString()} changed the channel icon.`
);
}
case MessageType.ChannelPinnedMessage: {
const pinned = await message.fetchReference().catch(() => {});
return (
CONSTANTS.emojis.discord.pin +
` ${message.author.toString()} pinned [a message](${
pinned?.url || ""
}) to this channel. See all [pinned messages](${pinned?.channel.url}).`
);
}
case MessageType.UserJoin: {
const formats = [
`${message.author.toString()} joined the party.`,
`${message.author.toString()} is here.`,
`Welcome, ${message.author.toString()}. We hope you brought pizza.`,
`A wild ${message.author.toString()} appeared.`,
`${message.author.toString()} just landed.`,
`${message.author.toString()} just slid into the server.`,
`${message.author.toString()} just showed up!`,
`Welcome ${message.author.toString()}. Say hi!`,
`${message.author.toString()} hopped into the server.`,
`Everyone welcome ${message.author.toString()}!`,
"Glad you're here, ${message.author.toString()}.",
`Good to see you, ${message.author.toString()}.`,
`Yay you made it, ${message.author.toString()}!`,
];
return (
CONSTANTS.emojis.discord.add + ` ${formats[+message.createdAt % formats.length]}`
);
}
case MessageType.GuildBoost: {
return (
CONSTANTS.emojis.discord.boost +
` ${message.author.toString()} just boosted the server${
message.content ? ` **${escapeMessage(message.content)}** times` : ""
}!`
);
}
case MessageType.GuildBoostTier1: {
return (
CONSTANTS.emojis.discord.boost +
` ${message.author.toString()} just boosted the server${
message.content ? ` **${escapeMessage(message.content)}** times` : ""
}! ${escapeMessage(message.guild?.name ?? "")} has achieved **Level 1**!`
);
}
case MessageType.GuildBoostTier2: {
return (
CONSTANTS.emojis.discord.boost +
` ${message.author.toString()} just boosted the server${
message.content ? ` **${escapeMessage(message.content)}** times` : ""
}! ${escapeMessage(message.guild?.name ?? "")} has achieved **Level 2**!`
);
}
case MessageType.GuildBoostTier3: {
return (
CONSTANTS.emojis.discord.boost +
` ${message.author.toString()} just boosted the server${
message.content ? ` **${escapeMessage(message.content)}** times` : ""
}! ${escapeMessage(message.guild?.name ?? "")} has achieved **Level 3**!`
);
}
case MessageType.ChannelFollowAdd: {
return (
CONSTANTS.emojis.discord.add +
` ${message.author.toString()} has added **${escapeMessage(
message.content,
)}** to this channel. Its most important updates will show up here.`
);
}
// if self.type is MessageType.guild_stream:
// # the author will be a Member
// return f'{self.author.name} is live! Now streaming {self.author.activity.name}' # type: ignore
case MessageType.GuildDiscoveryDisqualified: {
return "This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details.";
}
case MessageType.GuildDiscoveryRequalified: {
return "This server is eligible for Server Discovery again and has been automatically relisted!";
}
case MessageType.GuildDiscoveryGracePeriodInitialWarning: {
return "This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery.";
}
case MessageType.GuildDiscoveryGracePeriodFinalWarning: {
return "This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery.";
}
case MessageType.ThreadCreated: {
return (
CONSTANTS.emojis.discord.thread +
` ${message.author.toString()} started a thread: **${escapeMessage(
message.content,
)}** See all **threads**.`
);
}
case MessageType.Reply: {
if (!replies) return linklessContent;
const repliedMessage = await message.fetchReference().catch(() => {});
if (!repliedMessage)
return (
`*${CONSTANTS.emojis.discord.reply} Original message was deleted.*\n\n` +
linklessContent
);
const cleanContent = await messageToText(repliedMessage, false);
return (
`*[Replying to](${repliedMessage.url}) ${repliedMessage.author.toString()}${
cleanContent ? `:*\n> ${truncateText(cleanContent, 300)}` : "*"
}\n\n` + linklessContent
);
}
case MessageType.ThreadStarterMessage: {
const reference = await message.fetchReference().catch(() => {});
// the resolved message for the reference will be a Message
return reference
? (await messageToText(reference, replies)) || actualContent
: `${CONSTANTS.emojis.discord.thread} Sorry, we couldn't load the first message in this thread`;
}
case MessageType.GuildInviteReminder: {
return (
"Wondering who to invite?\n" +
"Start by inviting anyone who can help you build the server!"
);
}
case MessageType.ContextMenuCommand: {
if (!replies) return actualContent;
return `*${message.interaction?.user.toString() ?? ""} used **${escapeMessage(
message.interaction?.commandName ?? "",
)}**:*\n${actualContent}`;
}
case MessageType.ChatInputCommand: {
if (!replies) return actualContent;
return `*${message.interaction?.user.toString() ?? ""} used **/${escapeMessage(
message.interaction?.commandName ?? "",
)}**:*\n${actualContent}`;
}
case MessageType.Call: {
return CONSTANTS.emojis.discord.call + `${message.author.toString()} started a call.`;
}
default: {
// Fallback for unknown message types
throw new TypeError("Unknown message type: " + message.type);
}
}
}
/**
* @param {import("discord.js").Message} message
* @param {Readonly<import("discord.js").EmojiIdentifierResolvable[]>} reactions
*/
export async function reactAll(message, reactions) {
for (const reaction of reactions) {
await message.react(reaction);
}
}
/**
* @template {Record<string, any>} T
*
* @param {T[]} array
* @param {(value: T, index: number, array: (T | undefined)[]) => string} toString
* @param {string} failMessage
* @param {string} title
* @param {(options: import("discord.js").BaseMessageOptions) => Promise<Message | import("discord.js").InteractionResponse | void>} reply
*/
export async function paginate(array, toString, failMessage, title, reply) {
const PAGE_OFFSET = 15;
const previousId = generateHash("previous");
const previousButton = new ButtonBuilder()
.setLabel("<< Previous")
.setStyle(ButtonStyle.Primary)
.setDisabled(true)
.setCustomId(previousId);
const numberOfPages = Math.ceil(array.length / PAGE_OFFSET);
const nextId = generateHash("next");
const nextButton = new ButtonBuilder()
.setLabel("Next >>")
.setStyle(ButtonStyle.Primary)
.setDisabled(numberOfPages === 1)
.setCustomId(nextId);
// eslint-disable-next-line fp/no-let -- This must be changable.
let offset = 0;
/**
* Generate an embed that has the next page.
*
* @returns EmbedBuilder with the next page.
*/
function generateMessage() {
const content = array
.filter((_, index) => index >= offset && index < offset + PAGE_OFFSET)
.map((current, index, all) => `${index + offset + 1}) ${toString(current, index, all)}`)
.join("\n")
.trim();
if (!content) {
return {
content: `${CONSTANTS.emojis.statuses.no} ${failMessage}`,
ephemeral: true,
};
}
return {
components: [new MessageActionRowBuilder().addComponents(previousButton, nextButton)],
embeds: [
new EmbedBuilder()
.setTitle(title)
.setDescription(content)
.setFooter({
text: `Page ${Math.floor(offset / PAGE_OFFSET) + 1}/${numberOfPages}`,
})
.setColor(CONSTANTS.themeColor),
],
fetchReply: true,
};
}
let message = await reply(generateMessage());
const collector = message?.createMessageComponentCollector({
filter: (buttonInteraction) =>
[previousId, nextId].includes(buttonInteraction.customId) &&
buttonInteraction.user.id === message?.interaction?.user.id,
time: CONSTANTS.collectorTime,
});
collector
?.on("collect", async (buttonInteraction) => {
if (buttonInteraction.customId === nextId) offset += PAGE_OFFSET;
else offset -= PAGE_OFFSET;
previousButton.setDisabled(offset === 0);
nextButton.setDisabled(offset + PAGE_OFFSET >= array.length - 1);
message = await reply(generateMessage());
await buttonInteraction.deferUpdate();
collector.resetTimer();
})
.on("end", async () => {
await reply({
components: message instanceof Message ? disableComponents(message.components) : [],
});
});
}
/** @param {ActionRow<import("discord.js").MessageActionRowComponent>[]} row */
export function disableComponents(row) {
return row.map(({ components }) =>
new MessageActionRowBuilder().setComponents(
components.map((component) => {
if (component.type === ComponentType.Button) {
const button = ButtonBuilder.from(component);
if (button.data.style !== ButtonStyle.Link) button.setDisabled(true);
return button;
}
return SelectMenuBuilder.from(component).setDisabled(true);
}),
),
);
}
/**
* @param {null | undefined | import("discord.js").Channel} channel
*
* @returns {| import("discord.js").DMChannel
* | import("discord.js").PartialDMChannel
* | import("discord.js").PartialGroupDMChannel
* | import("discord.js").NonThreadGuildBasedChannel
* | undefined}
*/
export function getBaseChannel(channel) {
const nonThread = channel?.isThread() ? channel.parent : channel;
return nonThread && !nonThread.isThread() ? nonThread : undefined;
}