-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrepel.ts
More file actions
533 lines (485 loc) · 14.5 KB
/
repel.ts
File metadata and controls
533 lines (485 loc) · 14.5 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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import {
ApplicationCommandOptionType,
ApplicationCommandType,
ChannelType,
type ChatInputCommandInteraction,
Colors,
ContainerBuilder,
EmbedBuilder,
GuildMember,
type Message,
MessageFlags,
PermissionFlagsBits,
type Role,
type TextChannel,
TextDisplayBuilder,
type User,
} from 'discord.js';
import { HOUR, MINUTE, timeToString } from '../../constants/time.js';
import { config } from '../../env.js';
import { getPublicChannels } from '../../util/channel.js';
import { logToChannel } from '../../util/channel-logging.js';
import { buildCommandString, createCommand } from '../../util/commands.js';
const DEFAULT_LOOK_BACK_MS = 10 * MINUTE;
const DEFAULT_TIMEOUT_DURATION_MS = 1 * HOUR;
const isUserInServer = (target: User | GuildMember): target is GuildMember => {
return target instanceof GuildMember;
};
const isUserTimedOut = (target: GuildMember) => {
return target.communicationDisabledUntilTimestamp
? target.communicationDisabledUntilTimestamp > Date.now()
: false;
};
const checkCanRepel = ({
commandUser,
repelRole,
}: {
commandUser: GuildMember;
repelRole: Role;
}): {
ok: boolean;
message?: string;
} => {
const hasPermission =
commandUser.permissions.has(PermissionFlagsBits.ModerateMembers) ||
commandUser.roles.cache.has(repelRole.id);
if (!hasPermission) {
return { ok: false, message: 'You do not have permission to use this command.' };
}
return { ok: true };
};
const checkCanRepelTarget = ({
target,
commandUser,
botMember,
}: {
target: User | GuildMember;
commandUser: GuildMember;
botMember: GuildMember;
}): {
ok: boolean;
message?: string;
} => {
if (!isUserInServer(target)) {
return { ok: true };
}
if (target.user.bot) {
return { ok: false, message: 'You cannot repel a bot.' };
}
if (target.id === commandUser.id) {
return { ok: false, message: 'You cannot repel yourself.' };
}
const isTargetServerOwner = target.id === target.guild.ownerId;
if (isTargetServerOwner) {
return { ok: false, message: 'You cannot repel the server owner.' };
}
if (target.roles.highest.position >= commandUser.roles.highest.position) {
return { ok: false, message: 'You cannot repel this user due to role hierarchy.' };
}
if (target.roles.highest.position >= botMember.roles.highest.position) {
return { ok: false, message: 'I cannot repel this user due to role hierarchy.' };
}
return { ok: true };
};
const sendReasonToTarget = async ({
target,
reason,
guildName,
timeoutDuration,
}: {
target: GuildMember | User;
reason: string;
guildName: string;
timeoutDuration?: number;
}): Promise<boolean> => {
const parts: string[] = [];
parts.push(`You have been repelled from **${guildName}**.`);
if (timeoutDuration && timeoutDuration > 0) {
parts.push(`You have been timed out for ${timeToString(timeoutDuration)}.`);
}
parts.push(`**Reason:** ${reason}`);
const messageContent = parts.join('\n');
const containerComponent = new ContainerBuilder()
.setAccentColor(Colors.DarkRed)
.addTextDisplayComponents(new TextDisplayBuilder().setContent(messageContent));
try {
await target.send({
flags: MessageFlags.IsComponentsV2,
components: [containerComponent],
});
return true;
} catch {
return false;
}
};
const getTargetFromInteraction = async (
interaction: ChatInputCommandInteraction
): Promise<GuildMember | User> => {
const targetFromOption = interaction.options.getUser(RepelOptions.TARGET, true);
let target: User | GuildMember | null = null;
if (!interaction.inGuild() || interaction.guild === null) {
return targetFromOption;
}
try {
target = await interaction.guild.members.fetch(targetFromOption.id);
} catch (error) {
console.error('Error fetching target as guild member:', error);
target = targetFromOption;
}
return target;
};
const handleTimeout = async ({
target,
durationInMilliseconds,
}: {
target: GuildMember | User;
durationInMilliseconds: number;
}): Promise<number> => {
if (durationInMilliseconds === 0 || !isUserInServer(target) || isUserTimedOut(target)) {
return 0;
}
try {
await target.timeout(durationInMilliseconds, 'Repel command executed');
return durationInMilliseconds;
} catch (error) {
console.error('Error applying timeout to user:', error);
return 0;
}
};
const getTextChannels = (interaction: ChatInputCommandInteraction) => {
if (!interaction.inGuild() || !interaction.guild) {
console.error('Interaction is not in a guild');
return [];
}
const channels = Array.from(getPublicChannels(interaction.guild).values());
return [
interaction.channel as TextChannel,
...channels.filter((channel) => channel.id !== interaction.channelId),
];
};
const handleDeleteMessages = async ({
target,
channels,
lookBack,
}: {
target: GuildMember | User;
channels: TextChannel[];
lookBack: number;
}) => {
let deleted = 0;
const failedChannels: string[] = [];
// Collect all target messages from all channels and find the latest timestamp
const channelMessages: Array<{
channel: TextChannel;
targetMessages: Map<string, Message>;
}> = [];
let latestMessageTimestamp = 0;
for (const channel of channels) {
const targetMessages = new Map<string, Message>();
for (const [id, message] of channel.messages.cache) {
if (message.author && message.author.id === target.id && message.deletable) {
targetMessages.set(id, message);
latestMessageTimestamp = Math.max(latestMessageTimestamp, message.createdTimestamp);
}
}
if (targetMessages.size > 0) {
channelMessages.push({ channel, targetMessages });
}
}
// If no messages found from the target user, return early
if (latestMessageTimestamp === 0) {
return { deleted: 0, failedChannels: [] };
}
// Delete messages within the lookback window from the latest message
await Promise.allSettled(
channelMessages.map(async ({ channel, targetMessages }) => {
try {
const messagesToDelete: string[] = [];
for (const [id, message] of targetMessages) {
if (latestMessageTimestamp - message.createdTimestamp < lookBack) {
messagesToDelete.push(id);
}
}
if (messagesToDelete.length === 0) {
return;
}
await channel.bulkDelete(messagesToDelete, true);
deleted += messagesToDelete.length;
} catch (error) {
console.error(`Error deleting messages in channel ${channel.name}:`, error);
failedChannels.push(channel.id);
throw error;
}
})
);
if (failedChannels.length > 0) {
console.error(`Failed to delete messages in ${failedChannels.length} channel(s).`);
}
return { deleted, failedChannels };
};
const logRepelAction = async ({
interaction,
member,
target,
duration,
deleteCount,
reason,
failedChannels,
dm,
}: {
interaction: ChatInputCommandInteraction;
member: GuildMember;
target: User | GuildMember;
reason: string;
duration?: number;
deleteCount: number;
failedChannels: string[];
dm: {
sent: boolean;
shouldSend: boolean;
};
}) => {
const channelInfo =
interaction.channel?.type === ChannelType.GuildVoice
? `**${interaction.channel.name}** voice chat`
: `<#${interaction.channelId}>`;
const memberAuthor = {
name: member.user.tag,
iconURL: member.user.displayAvatarURL(),
};
const targetAuthor = {
name: isUserInServer(target)
? `${target.user.tag} | Repel | ${target.user.username}`
: `${target.tag} | Repel | ${target.username}`,
iconURL: isUserInServer(target) ? target.user.displayAvatarURL() : target.displayAvatarURL(),
};
const commandEmbed = new EmbedBuilder()
.setAuthor(memberAuthor)
.setDescription(`Used \`repel\` command in ${channelInfo}.\n${buildCommandString(interaction)}`)
.setColor('Green')
.setTimestamp();
const resultEmbed = new EmbedBuilder()
.setAuthor(targetAuthor)
.addFields(
{
name: 'Target',
value: `<@${target.id}>`,
inline: true,
},
{
name: 'Moderator',
value: `<@${member.id}>`,
inline: true,
},
{
name: 'Reason',
value: reason,
inline: true,
},
{
name: 'Deleted Messages',
value: deleteCount.toString(),
inline: true,
},
{
name: 'Timeout Duration',
value: duration ? `${timeToString(duration)}` : 'No Timeout',
inline: true,
}
)
.setColor('Orange')
.setTimestamp();
if (dm.shouldSend) {
resultEmbed.addFields({
name: 'DM Sent',
value: dm.sent ? 'Yes' : 'No',
inline: true,
});
}
const failedChannelsEmbed =
failedChannels.length > 0
? new EmbedBuilder()
.setTitle('Failed to delete messages in the following channels:')
.setDescription(failedChannels.map((id) => `<#${id}>`).join('\n'))
.setColor('Red')
.setTimestamp()
: null;
const modMessage = interaction.options.getString(RepelOptions.MESSAGE_FOR_MODS) ?? false;
const mentionText = modMessage
? `${config.roleIds.moderators.map((id) => `<@&${id}>`)} - ${modMessage}`
: undefined;
const channel = interaction.client.channels.cache.get(config.channelIds.repelLogs) as TextChannel;
const embed =
failedChannelsEmbed !== null
? [commandEmbed, resultEmbed, failedChannelsEmbed]
: [commandEmbed, resultEmbed];
await logToChannel({
channel,
content: {
type: 'embed',
embed,
content: mentionText,
},
});
};
const RepelOptions = {
TARGET: 'target',
REASON: 'reason',
LOOK_BACK: 'look_back',
TIMEOUT_DURATION: 'timeout_duration',
MESSAGE_FOR_MODS: 'message_for_mods',
DM_USER: 'dm_user',
} as const;
export const repelCommand = createCommand({
data: {
name: 'repel',
type: ApplicationCommandType.ChatInput,
description: 'Remove recent messages and timeout a user',
options: [
{
name: RepelOptions.TARGET,
required: true,
type: ApplicationCommandOptionType.User,
description: 'The user to timeout and remove messages from',
},
{
name: RepelOptions.REASON,
required: true,
type: ApplicationCommandOptionType.String,
description: 'Reason for the timeout and message removal',
},
{
name: RepelOptions.LOOK_BACK,
required: false,
type: ApplicationCommandOptionType.Integer,
description: `How far back to look for messages to delete in minutes (default: ${timeToString(
DEFAULT_LOOK_BACK_MS
)})`,
choices: [
{
name: '10 minutes (Default)',
value: 10 * MINUTE,
},
{
name: '30 minutes',
value: 30 * MINUTE,
},
{
name: '1 hour',
value: 1 * HOUR,
},
{
name: '3 hours',
value: 3 * HOUR,
},
],
},
{
name: RepelOptions.TIMEOUT_DURATION,
required: false,
type: ApplicationCommandOptionType.Integer,
description: `Duration of the timeout in hours (default: ${timeToString(DEFAULT_TIMEOUT_DURATION_MS)})`,
min_value: 0,
max_value: 24,
},
{
name: RepelOptions.MESSAGE_FOR_MODS,
required: false,
type: ApplicationCommandOptionType.String,
description: 'Optional message to include for moderators in the log',
},
{
name: RepelOptions.DM_USER,
required: false,
type: ApplicationCommandOptionType.Boolean,
description: 'Whether to DM the user about the repel action (Defaults to true)',
},
],
},
execute: async (interaction) => {
if (!interaction.inGuild() || !interaction.guild) {
await interaction.reply({
content: 'This command can only be used in a server.',
flags: MessageFlags.Ephemeral,
});
return;
}
if (!interaction.isChatInputCommand()) {
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const repelRole = interaction.guild.roles.cache.get(config.roleIds.repel);
if (!repelRole) {
await interaction.editReply({
content: '❌ Repel role is not configured correctly. Please contact an administrator.',
});
return;
}
const target = await getTargetFromInteraction(interaction);
const commandUser = interaction.member as GuildMember;
const canRepel = checkCanRepel({ commandUser, repelRole });
if (!canRepel.ok) {
await interaction.editReply({ content: `❌ ${canRepel.message}` });
return;
}
const botMember = interaction.guild.members.me;
if (!botMember) {
await interaction.editReply({
content: '❌ Unable to verify my permissions in the server.',
});
return;
}
const canRepelTarget = checkCanRepelTarget({
target,
commandUser,
botMember,
});
if (!canRepelTarget.ok) {
await interaction.editReply({ content: `❌ ${canRepelTarget.message}` });
return;
}
try {
const reason = interaction.options.getString(RepelOptions.REASON, true);
const lookBack = interaction.options.getInteger(RepelOptions.LOOK_BACK);
const timeoutHours = interaction.options.getInteger(RepelOptions.TIMEOUT_DURATION);
const timeout = await handleTimeout({
target: target,
durationInMilliseconds: timeoutHours ? timeoutHours * HOUR : DEFAULT_TIMEOUT_DURATION_MS,
});
const channels = getTextChannels(interaction);
const { deleted, failedChannels } = await handleDeleteMessages({
channels,
target: target,
lookBack: lookBack ?? DEFAULT_LOOK_BACK_MS,
});
const shouldDMUser = interaction.options.getBoolean(RepelOptions.DM_USER) ?? true;
let dmSent = false;
if (shouldDMUser) {
dmSent = await sendReasonToTarget({
target,
reason,
guildName: interaction.guild.name,
timeoutDuration: timeout,
});
}
logRepelAction({
interaction,
member: commandUser,
target,
reason,
duration: timeout,
deleteCount: deleted,
failedChannels,
dm: {
sent: dmSent,
shouldSend: shouldDMUser,
},
});
await interaction.editReply({
content: `Deleted ${deleted} message(s).`,
});
} catch (error) {
console.error('Error executing repel command:', error);
}
},
});