From b2d57b3486279e5af8ad2590c4b729e2bf818548 Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 19:07:12 +0000 Subject: [PATCH 01/15] feat: add mass message deletion logs to repels --- src/features/moderation/repel.ts | 100 +++++++++++++++++++++++++++---- 1 file changed, 89 insertions(+), 11 deletions(-) diff --git a/src/features/moderation/repel.ts b/src/features/moderation/repel.ts index f091ce5..f0a8a96 100644 --- a/src/features/moderation/repel.ts +++ b/src/features/moderation/repel.ts @@ -1,5 +1,7 @@ import { ApplicationCommandOptionType, + bold, + channelMention, ChannelType, type ChatInputCommandInteraction, Colors, @@ -12,8 +14,11 @@ import { type Role, type TextChannel, TextDisplayBuilder, + time, + TimestampStyles, type User, } from 'discord.js'; +import { clampText } from '@/util/text.js'; import { isUserInServer } from '@/util/member.js'; import { createSlashCommand } from '../../common/commands/create-commands.js'; import { HOUR, MINUTE, timeToString } from '../../constants/time.js'; @@ -30,6 +35,18 @@ const logger = createLogger('moderation'); const DEFAULT_LOOK_BACK_MS = 10 * MINUTE; const DEFAULT_TIMEOUT_DURATION_MS = 1 * HOUR; +const MAX_LOGGED_MESSAGES = 5; +const MAX_LOGGED_LINE_CONTENT = 300; +const EMBED_DESCRIPTION_LIMIT = 4096; + +type DeletedMessageSnapshot = { + channelId: string; + authorTag: string; + content: string; + createdTimestamp: number; + attachmentCount: number; +}; + const isUserTimedOut = (target: GuildMember) => { return target.communicationDisabledUntilTimestamp ? target.communicationDisabledUntilTimestamp > Date.now() @@ -205,6 +222,7 @@ const handleDeleteMessages = async ({ }) => { let deleted = 0; const failedChannels: string[] = []; + const deletedMessages: DeletedMessageSnapshot[] = []; // Collect all target messages from all channels and find the latest timestamp const channelMessages: Array<{ @@ -237,7 +255,7 @@ const handleDeleteMessages = async ({ // If no messages found from the target user, return early if (latestMessageTimestamp === 0) { - return { deleted: 0, failedChannels: [] }; + return { deleted: 0, failedChannels: [], deletedMessages: [] }; } // Delete messages within the lookback window from the latest message @@ -245,10 +263,18 @@ const handleDeleteMessages = async ({ channelMessages.map(async ({ channel, targetMessages }) => { try { const messagesToDelete: string[] = []; + const snapshots: DeletedMessageSnapshot[] = []; for (const [id, message] of targetMessages) { if (latestMessageTimestamp - message.createdTimestamp < lookBack) { messagesToDelete.push(id); + snapshots.push({ + channelId: message.channelId, + authorTag: message.author.tag, + content: message.content, + createdTimestamp: message.createdTimestamp, + attachmentCount: message.attachments.size, + }); } } @@ -257,6 +283,7 @@ const handleDeleteMessages = async ({ } await channel.bulkDelete(messagesToDelete, true); deleted += messagesToDelete.length; + deletedMessages.push(...snapshots); } catch (error) { logger.error( `Error deleting messages in channel ${channel.name}:`, @@ -272,7 +299,44 @@ const handleDeleteMessages = async ({ `Failed to delete messages in ${failedChannels.length} channel(s).` ); } - return { deleted, failedChannels }; + return { deleted, failedChannels, deletedMessages }; +}; + +const buildDeletedMessagesEmbed = ( + deletedMessages: DeletedMessageSnapshot[] +): EmbedBuilder => { + const sorted = [...deletedMessages].sort( + (first, second) => first.createdTimestamp - second.createdTimestamp + ); + const latest = sorted.slice(-MAX_LOGGED_MESSAGES); + + const lines = latest.map((message) => { + const timestamp = time( + Math.floor(message.createdTimestamp / 1000), + TimestampStyles.ShortTime + ); + const singleLineContent = message.content.replace(/\s*\n\s*/g, ' '); + const body = singleLineContent + ? clampText(singleLineContent, MAX_LOGGED_LINE_CONTENT) + : '(no text content)'; + const attachmentNote = + message.attachmentCount > 0 + ? ` [${message.attachmentCount} attachment${message.attachmentCount === 1 ? '' : 's'}]` + : ''; + return `${timestamp} ${channelMention(message.channelId)} ${bold(message.authorTag)}: ${body}${attachmentNote}`; + }); + + if (deletedMessages.length > latest.length) { + lines.push( + `Showing latest ${latest.length} of ${deletedMessages.length} deleted messages.` + ); + } + + return new EmbedBuilder() + .setTitle('Deleted Messages') + .setDescription(clampText(lines.join('\n'), EMBED_DESCRIPTION_LIMIT)) + .setColor(Colors.Red) + .setTimestamp(); }; const logRepelAction = async ({ @@ -281,6 +345,7 @@ const logRepelAction = async ({ target, duration, deleteCount, + deletedMessages, reason, failedChannels, dm, @@ -291,6 +356,7 @@ const logRepelAction = async ({ reason: string; duration?: number; deleteCount: number; + deletedMessages: DeletedMessageSnapshot[]; failedChannels: string[]; dm: { sent: boolean; @@ -375,10 +441,17 @@ const logRepelAction = async ({ const mentionText = modMessage ? `${config.roleIds.moderators.map((id) => `<@&${id}>`).join(' ')} - ${modMessage}` : undefined; - const embed = - failedChannelsEmbed !== null - ? [commandEmbed, resultEmbed, failedChannelsEmbed] - : [commandEmbed, resultEmbed]; + const deletedMessagesEmbed = + deletedMessages.length > 0 + ? buildDeletedMessagesEmbed(deletedMessages) + : null; + + const embed = [ + commandEmbed, + resultEmbed, + ...(deletedMessagesEmbed !== null ? [deletedMessagesEmbed] : []), + ...(failedChannelsEmbed !== null ? [failedChannelsEmbed] : []), + ]; await logToChannel({ channel: SERVER_CHANNELS.repelLogs, @@ -536,11 +609,12 @@ export const repelCommand = createSlashCommand({ const channels = getTextChannels(interaction); - const { deleted, failedChannels } = await handleDeleteMessages({ - channels, - target: target, - lookBack: lookBack ?? DEFAULT_LOOK_BACK_MS, - }); + const { deleted, failedChannels, deletedMessages } = + await handleDeleteMessages({ + channels, + target: target, + lookBack: lookBack ?? DEFAULT_LOOK_BACK_MS, + }); const shouldDMUser = interaction.options.getBoolean(RepelOptions.DM_USER) ?? true; @@ -561,6 +635,7 @@ export const repelCommand = createSlashCommand({ reason, duration: timeout, deleteCount: deleted, + deletedMessages, failedChannels, dm: { sent: dmSent, @@ -573,6 +648,9 @@ export const repelCommand = createSlashCommand({ }); } catch (error) { logger.error('Error executing repel command:', error); + await interaction.editReply({ + content: 'Something went wrong while executing the repel command.', + }); } }, }); From 202df74c3d6ba93a7a1b3412aa9eaed2ec25879c Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 19:10:29 +0000 Subject: [PATCH 02/15] fix: move deletion embeds into spam-detection channel for clean log seperation --- src/features/moderation/repel.ts | 34 ++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/features/moderation/repel.ts b/src/features/moderation/repel.ts index f0a8a96..5eb994e 100644 --- a/src/features/moderation/repel.ts +++ b/src/features/moderation/repel.ts @@ -17,6 +17,7 @@ import { time, TimestampStyles, type User, + userMention, } from 'discord.js'; import { clampText } from '@/util/text.js'; import { isUserInServer } from '@/util/member.js'; @@ -303,7 +304,8 @@ const handleDeleteMessages = async ({ }; const buildDeletedMessagesEmbed = ( - deletedMessages: DeletedMessageSnapshot[] + deletedMessages: DeletedMessageSnapshot[], + context: { target: User | GuildMember; member: GuildMember } ): EmbedBuilder => { const sorted = [...deletedMessages].sort( (first, second) => first.createdTimestamp - second.createdTimestamp @@ -333,8 +335,20 @@ const buildDeletedMessagesEmbed = ( } return new EmbedBuilder() - .setTitle('Deleted Messages') + .setTitle('Repel - Deleted Messages') .setDescription(clampText(lines.join('\n'), EMBED_DESCRIPTION_LIMIT)) + .addFields( + { + name: 'Repelled User', + value: userMention(context.target.id), + inline: true, + }, + { + name: 'Repelled By', + value: userMention(context.member.id), + inline: true, + } + ) .setColor(Colors.Red) .setTimestamp(); }; @@ -441,15 +455,9 @@ const logRepelAction = async ({ const mentionText = modMessage ? `${config.roleIds.moderators.map((id) => `<@&${id}>`).join(' ')} - ${modMessage}` : undefined; - const deletedMessagesEmbed = - deletedMessages.length > 0 - ? buildDeletedMessagesEmbed(deletedMessages) - : null; - const embed = [ commandEmbed, resultEmbed, - ...(deletedMessagesEmbed !== null ? [deletedMessagesEmbed] : []), ...(failedChannelsEmbed !== null ? [failedChannelsEmbed] : []), ]; @@ -464,6 +472,16 @@ const logRepelAction = async ({ }, }, }); + + if (deletedMessages.length > 0) { + await logToChannel({ + channel: SERVER_CHANNELS.spamDetection, + content: { + type: 'embed', + embed: buildDeletedMessagesEmbed(deletedMessages, { target, member }), + }, + }); + } }; const RepelOptions = { From d6ddd82b4c4249db3f57139af3a95a28e793fdf0 Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 19:30:39 +0000 Subject: [PATCH 03/15] fix: move features/moderation -> /repel and refactor --- src/common/commands/index.ts | 2 +- src/features/repel/embeds.ts | 116 ++++++++ src/features/{moderation => repel}/repel.ts | 292 ++++---------------- src/features/repel/util.test.ts | 270 ++++++++++++++++++ src/features/repel/util.ts | 140 ++++++++++ 5 files changed, 585 insertions(+), 235 deletions(-) create mode 100644 src/features/repel/embeds.ts rename src/features/{moderation => repel}/repel.ts (66%) create mode 100644 src/features/repel/util.test.ts create mode 100644 src/features/repel/util.ts diff --git a/src/common/commands/index.ts b/src/common/commands/index.ts index f7ae66f..59aa7af 100644 --- a/src/common/commands/index.ts +++ b/src/common/commands/index.ts @@ -1,7 +1,7 @@ import { docsCommands } from '@/features/docs/index.js'; import { guidesCommand } from '@/features/guides/index.js'; import cacheMessages from '@/features/cache-messages/index.js'; -import { repelCommand } from '@/features/moderation/repel.js'; +import { repelCommand } from '@/features/repel/repel.js'; import { pingCommand } from '@/features/ping/index.js'; import { publicGuidesCommand } from '@/features/public-guides/index.js'; import { createShowcaseCommand } from '@/features/showcase/create-showcase.js'; diff --git a/src/features/repel/embeds.ts b/src/features/repel/embeds.ts new file mode 100644 index 0000000..eb3b9b1 --- /dev/null +++ b/src/features/repel/embeds.ts @@ -0,0 +1,116 @@ +import { + channelMention, + Colors, + EmbedBuilder, + type GuildMember, + type User, + userMention, +} from 'discord.js'; +import { timeToString } from '@/constants/time.js'; +import { isUserInServer } from '@/util/member.js'; +import { + buildDeletedMessagesDescription, + type DeletedMessageSnapshot, +} from './util.js'; + +export const buildCommandEmbed = ({ + member, + channelInfo, + commandString, +}: { + member: GuildMember; + channelInfo: string; + commandString: string; +}): EmbedBuilder => + new EmbedBuilder() + .setAuthor({ + name: member.user.tag, + iconURL: member.user.displayAvatarURL(), + }) + .setDescription( + `Used \`repel\` command in ${channelInfo}.\n${commandString}` + ) + .setColor(Colors.Green) + .setTimestamp(); + +export const buildResultEmbed = ({ + member, + target, + reason, + deleteCount, + duration, + dm, +}: { + member: GuildMember; + target: User | GuildMember; + reason: string; + deleteCount: number; + duration?: number; + dm: { sent: boolean; shouldSend: boolean }; +}): EmbedBuilder => { + 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 embed = new EmbedBuilder() + .setAuthor(targetAuthor) + .addFields( + { name: 'Target', value: userMention(target.id), inline: true }, + { name: 'Moderator', value: userMention(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(Colors.Orange) + .setTimestamp(); + + if (dm.shouldSend) { + embed.addFields({ + name: 'DM Sent', + value: dm.sent ? 'Yes' : 'No', + inline: true, + }); + } + + return embed; +}; + +export const buildFailedChannelsEmbed = ( + failedChannels: string[] +): EmbedBuilder => + new EmbedBuilder() + .setTitle('Failed to delete messages in the following channels:') + .setDescription(failedChannels.map((id) => channelMention(id)).join('\n')) + .setColor(Colors.Red) + .setTimestamp(); + +export const buildDeletedMessagesEmbed = ( + deletedMessages: DeletedMessageSnapshot[], + context: { target: User | GuildMember; member: GuildMember } +): EmbedBuilder => + new EmbedBuilder() + .setTitle('Repel - Deleted Messages') + .setDescription(buildDeletedMessagesDescription(deletedMessages)) + .addFields( + { + name: 'Repelled User', + value: userMention(context.target.id), + inline: true, + }, + { + name: 'Repelled By', + value: userMention(context.member.id), + inline: true, + } + ) + .setColor(Colors.Red) + .setTimestamp(); diff --git a/src/features/moderation/repel.ts b/src/features/repel/repel.ts similarity index 66% rename from src/features/moderation/repel.ts rename to src/features/repel/repel.ts index 5eb994e..6c1f978 100644 --- a/src/features/moderation/repel.ts +++ b/src/features/repel/repel.ts @@ -1,25 +1,19 @@ import { ApplicationCommandOptionType, - bold, - channelMention, ChannelType, + channelMention, type ChatInputCommandInteraction, Colors, ContainerBuilder, - EmbedBuilder, type GuildMember, type Message, MessageFlags, PermissionFlagsBits, - type Role, + roleMention, type TextChannel, TextDisplayBuilder, - time, - TimestampStyles, type User, - userMention, } from 'discord.js'; -import { clampText } from '@/util/text.js'; import { isUserInServer } from '@/util/member.js'; import { createSlashCommand } from '../../common/commands/create-commands.js'; import { HOUR, MINUTE, timeToString } from '../../constants/time.js'; @@ -30,98 +24,25 @@ import { logToChannel } from '../../util/channel-logging.js'; import { SERVER_CHANNELS } from '@/constants/channels.js'; import { createLogger } from '@/util/logger.js'; import { buildRepelBanButtons } from '@/features/ban-buttons/repel-ban-buttons.js'; +import { + buildCommandEmbed, + buildDeletedMessagesEmbed, + buildFailedChannelsEmbed, + buildResultEmbed, +} from './embeds.js'; +import { + checkCanRepel, + checkCanRepelTarget, + DEFAULT_LOOK_BACK_MS, + DEFAULT_TIMEOUT_DURATION_MS, + type DeletedMessageSnapshot, + isTimedOut, + isWithinLookback, + resolveTimeoutDuration, +} from './util.js'; const logger = createLogger('moderation'); -const DEFAULT_LOOK_BACK_MS = 10 * MINUTE; -const DEFAULT_TIMEOUT_DURATION_MS = 1 * HOUR; - -const MAX_LOGGED_MESSAGES = 5; -const MAX_LOGGED_LINE_CONTENT = 300; -const EMBED_DESCRIPTION_LIMIT = 4096; - -type DeletedMessageSnapshot = { - channelId: string; - authorTag: string; - content: string; - createdTimestamp: number; - attachmentCount: number; -}; - -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, @@ -187,7 +108,7 @@ const handleTimeout = async ({ if ( durationInMilliseconds === 0 || !isUserInServer(target) || - isUserTimedOut(target) + isTimedOut(target.communicationDisabledUntilTimestamp, Date.now()) ) { return 0; } @@ -254,7 +175,6 @@ const handleDeleteMessages = async ({ } } - // If no messages found from the target user, return early if (latestMessageTimestamp === 0) { return { deleted: 0, failedChannels: [], deletedMessages: [] }; } @@ -267,7 +187,13 @@ const handleDeleteMessages = async ({ const snapshots: DeletedMessageSnapshot[] = []; for (const [id, message] of targetMessages) { - if (latestMessageTimestamp - message.createdTimestamp < lookBack) { + if ( + isWithinLookback( + latestMessageTimestamp, + message.createdTimestamp, + lookBack + ) + ) { messagesToDelete.push(id); snapshots.push({ channelId: message.channelId, @@ -303,56 +229,6 @@ const handleDeleteMessages = async ({ return { deleted, failedChannels, deletedMessages }; }; -const buildDeletedMessagesEmbed = ( - deletedMessages: DeletedMessageSnapshot[], - context: { target: User | GuildMember; member: GuildMember } -): EmbedBuilder => { - const sorted = [...deletedMessages].sort( - (first, second) => first.createdTimestamp - second.createdTimestamp - ); - const latest = sorted.slice(-MAX_LOGGED_MESSAGES); - - const lines = latest.map((message) => { - const timestamp = time( - Math.floor(message.createdTimestamp / 1000), - TimestampStyles.ShortTime - ); - const singleLineContent = message.content.replace(/\s*\n\s*/g, ' '); - const body = singleLineContent - ? clampText(singleLineContent, MAX_LOGGED_LINE_CONTENT) - : '(no text content)'; - const attachmentNote = - message.attachmentCount > 0 - ? ` [${message.attachmentCount} attachment${message.attachmentCount === 1 ? '' : 's'}]` - : ''; - return `${timestamp} ${channelMention(message.channelId)} ${bold(message.authorTag)}: ${body}${attachmentNote}`; - }); - - if (deletedMessages.length > latest.length) { - lines.push( - `Showing latest ${latest.length} of ${deletedMessages.length} deleted messages.` - ); - } - - return new EmbedBuilder() - .setTitle('Repel - Deleted Messages') - .setDescription(clampText(lines.join('\n'), EMBED_DESCRIPTION_LIMIT)) - .addFields( - { - name: 'Repelled User', - value: userMention(context.target.id), - inline: true, - }, - { - name: 'Repelled By', - value: userMention(context.member.id), - inline: true, - } - ) - .setColor(Colors.Red) - .setTimestamp(); -}; - const logRepelAction = async ({ interaction, member, @@ -380,93 +256,33 @@ const logRepelAction = async ({ 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, - }); - } + : channelMention(interaction.channelId); 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; + failedChannels.length > 0 ? buildFailedChannelsEmbed(failedChannels) : null; + + const embeds = [ + buildCommandEmbed({ + member, + channelInfo, + commandString: buildCommandString(interaction), + }), + buildResultEmbed({ member, target, reason, deleteCount, duration, dm }), + ...(failedChannelsEmbed !== null ? [failedChannelsEmbed] : []), + ]; const modMessage = interaction.options.getString(RepelOptions.MESSAGE_FOR_MODS) ?? false; const mentionText = modMessage - ? `${config.roleIds.moderators.map((id) => `<@&${id}>`).join(' ')} - ${modMessage}` + ? `${config.roleIds.moderators.map((id) => roleMention(id)).join(' ')} - ${modMessage}` : undefined; - const embed = [ - commandEmbed, - resultEmbed, - ...(failedChannelsEmbed !== null ? [failedChannelsEmbed] : []), - ]; await logToChannel({ channel: SERVER_CHANNELS.repelLogs, content: { type: 'custom', options: { - embeds: embed, + embeds, content: mentionText, components: [buildRepelBanButtons(target.id)], }, @@ -586,7 +402,12 @@ export const repelCommand = createSlashCommand({ const commandUser = interaction.member as GuildMember; - const canRepel = checkCanRepel({ commandUser, repelRole }); + const canRepel = checkCanRepel({ + hasModeratePermission: commandUser.permissions.has( + PermissionFlagsBits.ModerateMembers + ), + hasRepelRole: commandUser.roles.cache.has(repelRole.id), + }); if (!canRepel.ok) { await interaction.editReply({ content: `❌ ${canRepel.message}` }); return; @@ -600,11 +421,17 @@ export const repelCommand = createSlashCommand({ return; } - const canRepelTarget = checkCanRepelTarget({ - target, - commandUser, - botMember, - }); + const canRepelTarget = isUserInServer(target) + ? checkCanRepelTarget({ + isBot: target.user.bot, + targetId: target.id, + commandUserId: commandUser.id, + guildOwnerId: target.guild.ownerId, + targetRolePosition: target.roles.highest.position, + commandUserRolePosition: commandUser.roles.highest.position, + botRolePosition: botMember.roles.highest.position, + }) + : { ok: true }; if (!canRepelTarget.ok) { await interaction.editReply({ content: `❌ ${canRepelTarget.message}` }); return; @@ -619,10 +446,7 @@ export const repelCommand = createSlashCommand({ const timeout = await handleTimeout({ target: target, - durationInMilliseconds: - timeoutHours !== null - ? timeoutHours * HOUR - : DEFAULT_TIMEOUT_DURATION_MS, + durationInMilliseconds: resolveTimeoutDuration(timeoutHours), }); const channels = getTextChannels(interaction); diff --git a/src/features/repel/util.test.ts b/src/features/repel/util.test.ts new file mode 100644 index 0000000..46e8343 --- /dev/null +++ b/src/features/repel/util.test.ts @@ -0,0 +1,270 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { HOUR, MINUTE } from '@/constants/time.js'; +import { + buildDeletedMessagesDescription, + checkCanRepel, + checkCanRepelTarget, + DEFAULT_TIMEOUT_DURATION_MS, + type DeletedMessageSnapshot, + formatAttachmentNote, + formatDeletedMessageLine, + isTimedOut, + isWithinLookback, + MAX_LOGGED_MESSAGES, + resolveTimeoutDuration, +} from './util.js'; + +const snapshot = ( + overrides: Partial = {} +): DeletedMessageSnapshot => ({ + channelId: '100', + authorTag: 'spammer', + content: 'hello', + createdTimestamp: 1_700_000_000_000, + attachmentCount: 0, + ...overrides, +}); + +void describe('repel/util', () => { + void describe('resolveTimeoutDuration', () => { + void it('falls back to the default when no value is given', () => { + assert.equal(resolveTimeoutDuration(null), DEFAULT_TIMEOUT_DURATION_MS); + }); + + void it('converts the chosen hours to milliseconds', () => { + assert.equal(resolveTimeoutDuration(2), 2 * HOUR); + }); + + void it('treats an explicit 0 as no timeout rather than the default', () => { + assert.equal(resolveTimeoutDuration(0), 0); + }); + }); + + void describe('isWithinLookback', () => { + const latest = 1_000_000; + + void it('includes a message inside the window', () => { + assert.equal( + isWithinLookback(latest, latest - 5 * MINUTE, 10 * MINUTE), + true + ); + }); + + void it('excludes a message exactly at the window edge', () => { + assert.equal( + isWithinLookback(latest, latest - 10 * MINUTE, 10 * MINUTE), + false + ); + }); + + void it('excludes a message older than the window', () => { + assert.equal( + isWithinLookback(latest, latest - 20 * MINUTE, 10 * MINUTE), + false + ); + }); + + void it('includes the latest message itself', () => { + assert.equal(isWithinLookback(latest, latest, 10 * MINUTE), true); + }); + }); + + void describe('isTimedOut', () => { + const now = 1_000; + + void it('is false when there is no timeout timestamp', () => { + assert.equal(isTimedOut(null, now), false); + }); + + void it('is false when the timestamp is zero', () => { + assert.equal(isTimedOut(0, now), false); + }); + + void it('is true when the timeout expires in the future', () => { + assert.equal(isTimedOut(now + 1, now), true); + }); + + void it('is false when the timeout has already expired', () => { + assert.equal(isTimedOut(now - 1, now), false); + }); + }); + + void describe('checkCanRepel', () => { + void it('denies a user with neither the permission nor the role', () => { + const result = checkCanRepel({ + hasModeratePermission: false, + hasRepelRole: false, + }); + assert.equal(result.ok, false); + assert.equal( + result.message, + 'You do not have permission to use this command.' + ); + }); + + void it('allows a user with the moderate permission', () => { + assert.deepEqual( + checkCanRepel({ hasModeratePermission: true, hasRepelRole: false }), + { ok: true } + ); + }); + + void it('allows a user with the repel role', () => { + assert.deepEqual( + checkCanRepel({ hasModeratePermission: false, hasRepelRole: true }), + { ok: true } + ); + }); + }); + + void describe('checkCanRepelTarget', () => { + const base = { + isBot: false, + targetId: 'target', + commandUserId: 'mod', + guildOwnerId: 'owner', + targetRolePosition: 1, + commandUserRolePosition: 5, + botRolePosition: 5, + }; + + void it('allows repelling a normal, lower-ranked member', () => { + assert.deepEqual(checkCanRepelTarget(base), { ok: true }); + }); + + void it('rejects a bot target', () => { + const result = checkCanRepelTarget({ ...base, isBot: true }); + assert.equal(result.message, 'You cannot repel a bot.'); + }); + + void it('rejects repelling yourself', () => { + const result = checkCanRepelTarget({ ...base, targetId: 'mod' }); + assert.equal(result.message, 'You cannot repel yourself.'); + }); + + void it('rejects repelling the server owner', () => { + const result = checkCanRepelTarget({ ...base, targetId: 'owner' }); + assert.equal(result.message, 'You cannot repel the server owner.'); + }); + + void it('rejects a target ranked at or above the moderator', () => { + const result = checkCanRepelTarget({ ...base, targetRolePosition: 5 }); + assert.equal( + result.message, + 'You cannot repel this user due to role hierarchy.' + ); + }); + + void it('rejects a target the bot cannot act on', () => { + const result = checkCanRepelTarget({ + ...base, + commandUserRolePosition: 10, + targetRolePosition: 6, + botRolePosition: 5, + }); + assert.equal( + result.message, + 'I cannot repel this user due to role hierarchy.' + ); + }); + }); + + void describe('formatAttachmentNote', () => { + void it('is empty when there are no attachments', () => { + assert.equal(formatAttachmentNote(0), ''); + }); + + void it('uses the singular form for one attachment', () => { + assert.equal(formatAttachmentNote(1), ' [1 attachment]'); + }); + + void it('uses the plural form for multiple attachments', () => { + assert.equal(formatAttachmentNote(3), ' [3 attachments]'); + }); + }); + + void describe('formatDeletedMessageLine', () => { + void it('renders channel mention, bold author and content', () => { + const line = formatDeletedMessageLine( + snapshot({ channelId: '42', authorTag: 'bad#1', content: 'spam' }) + ); + assert.equal(line.includes('<#42>'), true); + assert.equal(line.includes('**bad#1**'), true); + assert.equal(line.endsWith(': spam'), true); + }); + + void it('collapses newlines so a message stays on one line', () => { + const line = formatDeletedMessageLine( + snapshot({ content: 'line1\n\nline2\nline3' }) + ); + assert.equal(line.includes('line1 line2 line3'), true); + assert.equal(line.includes('\n'), false); + }); + + void it('shows a placeholder when there is no text content', () => { + const line = formatDeletedMessageLine(snapshot({ content: '' })); + assert.equal(line.endsWith('(no text content)'), true); + }); + + void it('appends an attachment note', () => { + const line = formatDeletedMessageLine( + snapshot({ content: 'x', attachmentCount: 2 }) + ); + assert.equal(line.endsWith('x [2 attachments]'), true); + }); + + void it('clamps very long content', () => { + const line = formatDeletedMessageLine( + snapshot({ content: 'a'.repeat(500) }) + ); + assert.equal(line.includes('...'), true); + assert.equal(line.includes('a'.repeat(500)), false); + }); + }); + + void describe('buildDeletedMessagesDescription', () => { + void it('lists every message when at or under the cap', () => { + const messages = [ + snapshot({ content: 'first', createdTimestamp: 1 }), + snapshot({ content: 'second', createdTimestamp: 2 }), + ]; + const description = buildDeletedMessagesDescription(messages); + assert.equal(description.split('\n').length, 2); + assert.equal(description.includes('first'), true); + assert.equal(description.includes('second'), true); + assert.equal(description.includes('Showing latest'), false); + }); + + void it('orders messages oldest-to-newest by timestamp', () => { + const description = buildDeletedMessagesDescription([ + snapshot({ content: 'newer', createdTimestamp: 20 }), + snapshot({ content: 'older', createdTimestamp: 10 }), + ]); + assert.equal( + description.indexOf('older') < description.indexOf('newer'), + true + ); + }); + + void it('keeps only the latest messages and notes the omitted count', () => { + const total = MAX_LOGGED_MESSAGES + 2; + const messages = Array.from({ length: total }, (_, index) => + snapshot({ content: `msg-${index}`, createdTimestamp: index + 1 }) + ); + + const description = buildDeletedMessagesDescription(messages); + const lines = description.split('\n'); + + assert.equal(lines.length, MAX_LOGGED_MESSAGES + 1); + assert.equal( + lines.at(-1), + `Showing latest ${MAX_LOGGED_MESSAGES} of ${total} deleted messages.` + ); + // The two oldest messages are dropped. + assert.equal(description.includes('msg-0'), false); + assert.equal(description.includes('msg-1'), false); + assert.equal(description.includes(`msg-${total - 1}`), true); + }); + }); +}); diff --git a/src/features/repel/util.ts b/src/features/repel/util.ts new file mode 100644 index 0000000..973487d --- /dev/null +++ b/src/features/repel/util.ts @@ -0,0 +1,140 @@ +import { bold, channelMention, time, TimestampStyles } from 'discord.js'; +import { HOUR, MINUTE } from '@/constants/time.js'; +import { clampText } from '@/util/text.js'; + +export const DEFAULT_LOOK_BACK_MS = 10 * MINUTE; +export const DEFAULT_TIMEOUT_DURATION_MS = 1 * HOUR; + +export const MAX_LOGGED_MESSAGES = 5; +export const MAX_LOGGED_LINE_CONTENT = 300; +export const EMBED_DESCRIPTION_LIMIT = 4096; + +export type DeletedMessageSnapshot = { + channelId: string; + authorTag: string; + content: string; + createdTimestamp: number; + attachmentCount: number; +}; + +export type PermissionCheck = { + ok: boolean; + message?: string; +}; + +export const resolveTimeoutDuration = (timeoutHours: number | null): number => + timeoutHours !== null ? timeoutHours * HOUR : DEFAULT_TIMEOUT_DURATION_MS; + +export const isWithinLookback = ( + latestTimestamp: number, + createdTimestamp: number, + lookBack: number +): boolean => latestTimestamp - createdTimestamp < lookBack; + +export const isTimedOut = ( + communicationDisabledUntilTimestamp: number | null, + now: number +): boolean => + communicationDisabledUntilTimestamp + ? communicationDisabledUntilTimestamp > now + : false; + +export const checkCanRepel = ({ + hasModeratePermission, + hasRepelRole, +}: { + hasModeratePermission: boolean; + hasRepelRole: boolean; +}): PermissionCheck => { + if (!hasModeratePermission && !hasRepelRole) { + return { + ok: false, + message: 'You do not have permission to use this command.', + }; + } + return { ok: true }; +}; + +// Expects the target to be a server member; callers treat non-members as +// always repellable. +export const checkCanRepelTarget = ({ + isBot, + targetId, + commandUserId, + guildOwnerId, + targetRolePosition, + commandUserRolePosition, + botRolePosition, +}: { + isBot: boolean; + targetId: string; + commandUserId: string; + guildOwnerId: string; + targetRolePosition: number; + commandUserRolePosition: number; + botRolePosition: number; +}): PermissionCheck => { + if (isBot) { + return { ok: false, message: 'You cannot repel a bot.' }; + } + + if (targetId === commandUserId) { + return { ok: false, message: 'You cannot repel yourself.' }; + } + + if (targetId === guildOwnerId) { + return { ok: false, message: 'You cannot repel the server owner.' }; + } + + if (targetRolePosition >= commandUserRolePosition) { + return { + ok: false, + message: 'You cannot repel this user due to role hierarchy.', + }; + } + + if (targetRolePosition >= botRolePosition) { + return { + ok: false, + message: 'I cannot repel this user due to role hierarchy.', + }; + } + + return { ok: true }; +}; + +export const formatAttachmentNote = (count: number): string => + count > 0 ? ` [${count} attachment${count === 1 ? '' : 's'}]` : ''; + +export const formatDeletedMessageLine = ( + message: DeletedMessageSnapshot +): string => { + const timestamp = time( + Math.floor(message.createdTimestamp / 1000), + TimestampStyles.ShortTime + ); + const singleLineContent = message.content.replace(/\s*\n\s*/g, ' '); + const body = singleLineContent + ? clampText(singleLineContent, MAX_LOGGED_LINE_CONTENT) + : '(no text content)'; + return `${timestamp} ${channelMention(message.channelId)} ${bold(message.authorTag)}: ${body}${formatAttachmentNote(message.attachmentCount)}`; +}; + +export const buildDeletedMessagesDescription = ( + deletedMessages: DeletedMessageSnapshot[] +): string => { + const sorted = [...deletedMessages].sort( + (first, second) => first.createdTimestamp - second.createdTimestamp + ); + const latest = sorted.slice(-MAX_LOGGED_MESSAGES); + + const lines = latest.map(formatDeletedMessageLine); + + if (deletedMessages.length > latest.length) { + lines.push( + `Showing latest ${latest.length} of ${deletedMessages.length} deleted messages.` + ); + } + + return clampText(lines.join('\n'), EMBED_DESCRIPTION_LIMIT); +}; From 31c9a5c227b38953fb8257958ebc04e8fdb6f017 Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 19:32:24 +0000 Subject: [PATCH 04/15] fix: double isUserInServer check --- src/features/repel/embeds.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/features/repel/embeds.ts b/src/features/repel/embeds.ts index eb3b9b1..7e847ae 100644 --- a/src/features/repel/embeds.ts +++ b/src/features/repel/embeds.ts @@ -48,13 +48,10 @@ export const buildResultEmbed = ({ duration?: number; dm: { sent: boolean; shouldSend: boolean }; }): EmbedBuilder => { + const targetUser = isUserInServer(target) ? target.user : target; 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(), + name: `${targetUser.tag} | Repel | ${targetUser.username}`, + iconURL: targetUser.displayAvatarURL(), }; const embed = new EmbedBuilder() From 4ea147a0a5e350199a9c556beb22436bfe61c4c1 Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 20:00:33 +0000 Subject: [PATCH 05/15] feat:rework the tri-embed into two embeds one channel --- src/features/repel/embeds.ts | 86 ++++++++++++--------------------- src/features/repel/repel.ts | 23 +++------ src/features/repel/util.test.ts | 10 ++-- src/features/repel/util.ts | 19 ++++---- 4 files changed, 53 insertions(+), 85 deletions(-) diff --git a/src/features/repel/embeds.ts b/src/features/repel/embeds.ts index 7e847ae..c8b1752 100644 --- a/src/features/repel/embeds.ts +++ b/src/features/repel/embeds.ts @@ -7,7 +7,6 @@ import { userMention, } from 'discord.js'; import { timeToString } from '@/constants/time.js'; -import { isUserInServer } from '@/util/member.js'; import { buildDeletedMessagesDescription, type DeletedMessageSnapshot, @@ -33,54 +32,6 @@ export const buildCommandEmbed = ({ .setColor(Colors.Green) .setTimestamp(); -export const buildResultEmbed = ({ - member, - target, - reason, - deleteCount, - duration, - dm, -}: { - member: GuildMember; - target: User | GuildMember; - reason: string; - deleteCount: number; - duration?: number; - dm: { sent: boolean; shouldSend: boolean }; -}): EmbedBuilder => { - const targetUser = isUserInServer(target) ? target.user : target; - const targetAuthor = { - name: `${targetUser.tag} | Repel | ${targetUser.username}`, - iconURL: targetUser.displayAvatarURL(), - }; - - const embed = new EmbedBuilder() - .setAuthor(targetAuthor) - .addFields( - { name: 'Target', value: userMention(target.id), inline: true }, - { name: 'Moderator', value: userMention(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(Colors.Orange) - .setTimestamp(); - - if (dm.shouldSend) { - embed.addFields({ - name: 'DM Sent', - value: dm.sent ? 'Yes' : 'No', - inline: true, - }); - } - - return embed; -}; - export const buildFailedChannelsEmbed = ( failedChannels: string[] ): EmbedBuilder => @@ -92,11 +43,25 @@ export const buildFailedChannelsEmbed = ( export const buildDeletedMessagesEmbed = ( deletedMessages: DeletedMessageSnapshot[], - context: { target: User | GuildMember; member: GuildMember } -): EmbedBuilder => - new EmbedBuilder() - .setTitle('Repel - Deleted Messages') - .setDescription(buildDeletedMessagesDescription(deletedMessages)) + context: { + target: User | GuildMember; + member: GuildMember; + reason: string; + duration?: number; + dmSent: boolean; + } +): EmbedBuilder => { + const footerParts = [ + context.duration + ? `Timeout: ${timeToString(context.duration)}` + : 'No timeout', + ]; + if (context.dmSent) { + footerParts.push('DM sent'); + } + + return new EmbedBuilder() + .setTitle('Repel') .addFields( { name: 'Repelled User', @@ -107,7 +72,18 @@ export const buildDeletedMessagesEmbed = ( name: 'Repelled By', value: userMention(context.member.id), inline: true, + }, + { + name: 'Reason', + value: context.reason, + inline: true, + }, + { + name: 'Deleted Messages', + value: buildDeletedMessagesDescription(deletedMessages), + inline: false, } ) .setColor(Colors.Red) - .setTimestamp(); + .setFooter({ text: footerParts.join(' • ') }); +}; diff --git a/src/features/repel/repel.ts b/src/features/repel/repel.ts index 6c1f978..46c7bb4 100644 --- a/src/features/repel/repel.ts +++ b/src/features/repel/repel.ts @@ -28,7 +28,6 @@ import { buildCommandEmbed, buildDeletedMessagesEmbed, buildFailedChannelsEmbed, - buildResultEmbed, } from './embeds.js'; import { checkCanRepel, @@ -197,7 +196,6 @@ const handleDeleteMessages = async ({ messagesToDelete.push(id); snapshots.push({ channelId: message.channelId, - authorTag: message.author.tag, content: message.content, createdTimestamp: message.createdTimestamp, attachmentCount: message.attachments.size, @@ -234,7 +232,6 @@ const logRepelAction = async ({ member, target, duration, - deleteCount, deletedMessages, reason, failedChannels, @@ -245,7 +242,6 @@ const logRepelAction = async ({ target: User | GuildMember; reason: string; duration?: number; - deleteCount: number; deletedMessages: DeletedMessageSnapshot[]; failedChannels: string[]; dm: { @@ -267,7 +263,13 @@ const logRepelAction = async ({ channelInfo, commandString: buildCommandString(interaction), }), - buildResultEmbed({ member, target, reason, deleteCount, duration, dm }), + buildDeletedMessagesEmbed(deletedMessages, { + target, + member, + reason, + duration, + dmSent: dm.sent, + }), ...(failedChannelsEmbed !== null ? [failedChannelsEmbed] : []), ]; @@ -288,16 +290,6 @@ const logRepelAction = async ({ }, }, }); - - if (deletedMessages.length > 0) { - await logToChannel({ - channel: SERVER_CHANNELS.spamDetection, - content: { - type: 'embed', - embed: buildDeletedMessagesEmbed(deletedMessages, { target, member }), - }, - }); - } }; const RepelOptions = { @@ -476,7 +468,6 @@ export const repelCommand = createSlashCommand({ target, reason, duration: timeout, - deleteCount: deleted, deletedMessages, failedChannels, dm: { diff --git a/src/features/repel/util.test.ts b/src/features/repel/util.test.ts index 46e8343..618f5fd 100644 --- a/src/features/repel/util.test.ts +++ b/src/features/repel/util.test.ts @@ -19,7 +19,6 @@ const snapshot = ( overrides: Partial = {} ): DeletedMessageSnapshot => ({ channelId: '100', - authorTag: 'spammer', content: 'hello', createdTimestamp: 1_700_000_000_000, attachmentCount: 0, @@ -185,12 +184,11 @@ void describe('repel/util', () => { }); void describe('formatDeletedMessageLine', () => { - void it('renders channel mention, bold author and content', () => { + void it('renders channel mention and content', () => { const line = formatDeletedMessageLine( - snapshot({ channelId: '42', authorTag: 'bad#1', content: 'spam' }) + snapshot({ channelId: '42', content: 'spam' }) ); assert.equal(line.includes('<#42>'), true); - assert.equal(line.includes('**bad#1**'), true); assert.equal(line.endsWith(': spam'), true); }); @@ -224,6 +222,10 @@ void describe('repel/util', () => { }); void describe('buildDeletedMessagesDescription', () => { + void it('shows a placeholder when nothing was deleted', () => { + assert.equal(buildDeletedMessagesDescription([]), 'No messages deleted.'); + }); + void it('lists every message when at or under the cap', () => { const messages = [ snapshot({ content: 'first', createdTimestamp: 1 }), diff --git a/src/features/repel/util.ts b/src/features/repel/util.ts index 973487d..8322405 100644 --- a/src/features/repel/util.ts +++ b/src/features/repel/util.ts @@ -1,4 +1,4 @@ -import { bold, channelMention, time, TimestampStyles } from 'discord.js'; +import { channelMention } from 'discord.js'; import { HOUR, MINUTE } from '@/constants/time.js'; import { clampText } from '@/util/text.js'; @@ -6,12 +6,11 @@ export const DEFAULT_LOOK_BACK_MS = 10 * MINUTE; export const DEFAULT_TIMEOUT_DURATION_MS = 1 * HOUR; export const MAX_LOGGED_MESSAGES = 5; -export const MAX_LOGGED_LINE_CONTENT = 300; -export const EMBED_DESCRIPTION_LIMIT = 4096; +export const MAX_LOGGED_LINE_CONTENT = 150; +export const FIELD_VALUE_LIMIT = 1024; export type DeletedMessageSnapshot = { channelId: string; - authorTag: string; content: string; createdTimestamp: number; attachmentCount: number; @@ -109,20 +108,20 @@ export const formatAttachmentNote = (count: number): string => export const formatDeletedMessageLine = ( message: DeletedMessageSnapshot ): string => { - const timestamp = time( - Math.floor(message.createdTimestamp / 1000), - TimestampStyles.ShortTime - ); const singleLineContent = message.content.replace(/\s*\n\s*/g, ' '); const body = singleLineContent ? clampText(singleLineContent, MAX_LOGGED_LINE_CONTENT) : '(no text content)'; - return `${timestamp} ${channelMention(message.channelId)} ${bold(message.authorTag)}: ${body}${formatAttachmentNote(message.attachmentCount)}`; + return `${channelMention(message.channelId)}: ${body}${formatAttachmentNote(message.attachmentCount)}`; }; export const buildDeletedMessagesDescription = ( deletedMessages: DeletedMessageSnapshot[] ): string => { + if (deletedMessages.length === 0) { + return 'No messages deleted.'; + } + const sorted = [...deletedMessages].sort( (first, second) => first.createdTimestamp - second.createdTimestamp ); @@ -136,5 +135,5 @@ export const buildDeletedMessagesDescription = ( ); } - return clampText(lines.join('\n'), EMBED_DESCRIPTION_LIMIT); + return clampText(lines.join('\n'), FIELD_VALUE_LIMIT); }; From 095dcf3dbf5f69abf65cea9d6ff92f3f15c9e21e Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 20:08:52 +0000 Subject: [PATCH 06/15] fix: broken lookback echoing messages --- src/features/repel/repel.ts | 20 +++++--------------- src/features/repel/util.test.ts | 17 +++++++---------- src/features/repel/util.ts | 4 ++-- 3 files changed, 14 insertions(+), 27 deletions(-) diff --git a/src/features/repel/repel.ts b/src/features/repel/repel.ts index 46c7bb4..7976951 100644 --- a/src/features/repel/repel.ts +++ b/src/features/repel/repel.ts @@ -141,16 +141,16 @@ const handleDeleteMessages = async ({ channels: TextChannel[]; lookBack: number; }) => { + const now = Date.now(); let deleted = 0; const failedChannels: string[] = []; const deletedMessages: DeletedMessageSnapshot[] = []; - // Collect all target messages from all channels and find the latest timestamp + // Collect the target's messages from each channel const channelMessages: Array<{ channel: TextChannel; targetMessages: Map; }> = []; - let latestMessageTimestamp = 0; for (const channel of channels) { const targetMessages = new Map(); @@ -162,10 +162,6 @@ const handleDeleteMessages = async ({ message.deletable ) { targetMessages.set(id, message); - latestMessageTimestamp = Math.max( - latestMessageTimestamp, - message.createdTimestamp - ); } } @@ -174,11 +170,11 @@ const handleDeleteMessages = async ({ } } - if (latestMessageTimestamp === 0) { + if (channelMessages.length === 0) { return { deleted: 0, failedChannels: [], deletedMessages: [] }; } - // Delete messages within the lookback window from the latest message + // Delete messages sent within the lookback window before the command was run await Promise.allSettled( channelMessages.map(async ({ channel, targetMessages }) => { try { @@ -186,13 +182,7 @@ const handleDeleteMessages = async ({ const snapshots: DeletedMessageSnapshot[] = []; for (const [id, message] of targetMessages) { - if ( - isWithinLookback( - latestMessageTimestamp, - message.createdTimestamp, - lookBack - ) - ) { + if (isWithinLookback(now, message.createdTimestamp, lookBack)) { messagesToDelete.push(id); snapshots.push({ channelId: message.channelId, diff --git a/src/features/repel/util.test.ts b/src/features/repel/util.test.ts index 618f5fd..40774ef 100644 --- a/src/features/repel/util.test.ts +++ b/src/features/repel/util.test.ts @@ -41,31 +41,28 @@ void describe('repel/util', () => { }); void describe('isWithinLookback', () => { - const latest = 1_000_000; + const now = 1_000_000; void it('includes a message inside the window', () => { - assert.equal( - isWithinLookback(latest, latest - 5 * MINUTE, 10 * MINUTE), - true - ); + assert.equal(isWithinLookback(now, now - 5 * MINUTE, 10 * MINUTE), true); }); void it('excludes a message exactly at the window edge', () => { assert.equal( - isWithinLookback(latest, latest - 10 * MINUTE, 10 * MINUTE), + isWithinLookback(now, now - 10 * MINUTE, 10 * MINUTE), false ); }); - void it('excludes a message older than the window', () => { + void it('excludes a stale message even when it is the most recent one', () => { assert.equal( - isWithinLookback(latest, latest - 20 * MINUTE, 10 * MINUTE), + isWithinLookback(now, now - 20 * MINUTE, 10 * MINUTE), false ); }); - void it('includes the latest message itself', () => { - assert.equal(isWithinLookback(latest, latest, 10 * MINUTE), true); + void it('includes a message sent at the reference time', () => { + assert.equal(isWithinLookback(now, now, 10 * MINUTE), true); }); }); diff --git a/src/features/repel/util.ts b/src/features/repel/util.ts index 8322405..9bf46a7 100644 --- a/src/features/repel/util.ts +++ b/src/features/repel/util.ts @@ -25,10 +25,10 @@ export const resolveTimeoutDuration = (timeoutHours: number | null): number => timeoutHours !== null ? timeoutHours * HOUR : DEFAULT_TIMEOUT_DURATION_MS; export const isWithinLookback = ( - latestTimestamp: number, + referenceTimestamp: number, createdTimestamp: number, lookBack: number -): boolean => latestTimestamp - createdTimestamp < lookBack; +): boolean => referenceTimestamp - createdTimestamp < lookBack; export const isTimedOut = ( communicationDisabledUntilTimestamp: number | null, From adda9057d3c9be6f74ad68510e4ae9ec1c039a36 Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 20:17:34 +0000 Subject: [PATCH 07/15] fix: revert back to tri-embed display --- src/features/repel/embeds.ts | 32 ++++++++++++++++---------------- src/features/repel/repel.ts | 10 +++------- src/features/repel/util.ts | 6 +++--- 3 files changed, 22 insertions(+), 26 deletions(-) diff --git a/src/features/repel/embeds.ts b/src/features/repel/embeds.ts index c8b1752..e490dd9 100644 --- a/src/features/repel/embeds.ts +++ b/src/features/repel/embeds.ts @@ -41,16 +41,13 @@ export const buildFailedChannelsEmbed = ( .setColor(Colors.Red) .setTimestamp(); -export const buildDeletedMessagesEmbed = ( - deletedMessages: DeletedMessageSnapshot[], - context: { - target: User | GuildMember; - member: GuildMember; - reason: string; - duration?: number; - dmSent: boolean; - } -): EmbedBuilder => { +export const buildResultEmbed = (context: { + target: User | GuildMember; + member: GuildMember; + reason: string; + duration?: number; + dmSent: boolean; +}): EmbedBuilder => { const footerParts = [ context.duration ? `Timeout: ${timeToString(context.duration)}` @@ -77,13 +74,16 @@ export const buildDeletedMessagesEmbed = ( name: 'Reason', value: context.reason, inline: true, - }, - { - name: 'Deleted Messages', - value: buildDeletedMessagesDescription(deletedMessages), - inline: false, } ) - .setColor(Colors.Red) + .setColor(Colors.Orange) .setFooter({ text: footerParts.join(' • ') }); }; + +export const buildDeletedMessagesEmbed = ( + deletedMessages: DeletedMessageSnapshot[] +): EmbedBuilder => + new EmbedBuilder() + .setTitle('Deleted Messages') + .setDescription(buildDeletedMessagesDescription(deletedMessages)) + .setColor(Colors.Red); diff --git a/src/features/repel/repel.ts b/src/features/repel/repel.ts index 7976951..fe37b00 100644 --- a/src/features/repel/repel.ts +++ b/src/features/repel/repel.ts @@ -28,6 +28,7 @@ import { buildCommandEmbed, buildDeletedMessagesEmbed, buildFailedChannelsEmbed, + buildResultEmbed, } from './embeds.js'; import { checkCanRepel, @@ -253,13 +254,8 @@ const logRepelAction = async ({ channelInfo, commandString: buildCommandString(interaction), }), - buildDeletedMessagesEmbed(deletedMessages, { - target, - member, - reason, - duration, - dmSent: dm.sent, - }), + buildResultEmbed({ target, member, reason, duration, dmSent: dm.sent }), + buildDeletedMessagesEmbed(deletedMessages), ...(failedChannelsEmbed !== null ? [failedChannelsEmbed] : []), ]; diff --git a/src/features/repel/util.ts b/src/features/repel/util.ts index 9bf46a7..032945e 100644 --- a/src/features/repel/util.ts +++ b/src/features/repel/util.ts @@ -6,8 +6,8 @@ export const DEFAULT_LOOK_BACK_MS = 10 * MINUTE; export const DEFAULT_TIMEOUT_DURATION_MS = 1 * HOUR; export const MAX_LOGGED_MESSAGES = 5; -export const MAX_LOGGED_LINE_CONTENT = 150; -export const FIELD_VALUE_LIMIT = 1024; +export const MAX_LOGGED_LINE_CONTENT = 300; +export const EMBED_DESCRIPTION_LIMIT = 4096; export type DeletedMessageSnapshot = { channelId: string; @@ -135,5 +135,5 @@ export const buildDeletedMessagesDescription = ( ); } - return clampText(lines.join('\n'), FIELD_VALUE_LIMIT); + return clampText(lines.join('\n'), EMBED_DESCRIPTION_LIMIT); }; From 125d78aa9fd285e1f44f83dbba40f54c6fa67ed2 Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 20:20:23 +0000 Subject: [PATCH 08/15] feat: disable the buttons when a moderator interacts with them --- .../ban-buttons/ban-command-buttons.ts | 45 ++++++++++++------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/src/features/ban-buttons/ban-command-buttons.ts b/src/features/ban-buttons/ban-command-buttons.ts index 75fa2e1..fbd7c7f 100644 --- a/src/features/ban-buttons/ban-command-buttons.ts +++ b/src/features/ban-buttons/ban-command-buttons.ts @@ -54,6 +54,27 @@ export const createBanCommandButtons = ({ id: string; actions: BanCommandActions; }): BanCommandButtons => { + const buildButtons = ( + targetId: string, + disabled = false + ): ActionRowBuilder => { + const row = new ActionRowBuilder(); + for (const [key, action] of Object.entries(actions)) { + row.addComponents( + new ButtonBuilder() + .setCustomId(customId(id, key, targetId)) + .setLabel(action.label) + .setStyle( + action.command === 'softban' + ? ButtonStyle.Secondary + : ButtonStyle.Danger + ) + .setDisabled(disabled) + ); + } + return row; + }; + const handler: ButtonSubmitInteraction = { commandName: id, handler: async (interaction) => { @@ -75,8 +96,13 @@ export const createBanCommandButtons = ({ return; } + // Disable the buttons now that a moderator has acted on this repel. + await interaction.update({ + components: [buildButtons(targetId, true)], + }); + const command = buildBanCommand(targetId, action); - await interaction.reply({ + await interaction.followUp({ content: `# Copy and run this ban command:\n${codeBlock(command)}`, flags: MessageFlags.Ephemeral, }); @@ -86,21 +112,6 @@ export const createBanCommandButtons = ({ registerButtonSubmitInteraction(handler); return { - buildButtons: (targetId: string) => { - const row = new ActionRowBuilder(); - for (const [key, action] of Object.entries(actions)) { - row.addComponents( - new ButtonBuilder() - .setCustomId(customId(id, key, targetId)) - .setLabel(action.label) - .setStyle( - action.command === 'softban' - ? ButtonStyle.Secondary - : ButtonStyle.Danger - ) - ); - } - return row; - }, + buildButtons: (targetId: string) => buildButtons(targetId), }; }; From a07ac8d4cc7aace887a32dbe2fb38ee162cdc839 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Skraburski?= Date: Thu, 3 Dec 2026 21:50:17 +0000 Subject: [PATCH 09/15] Update src/features/ban-buttons/ban-command-buttons.ts Co-authored-by: Cake --- src/features/ban-buttons/ban-command-buttons.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/ban-buttons/ban-command-buttons.ts b/src/features/ban-buttons/ban-command-buttons.ts index fbd7c7f..b5e0a71 100644 --- a/src/features/ban-buttons/ban-command-buttons.ts +++ b/src/features/ban-buttons/ban-command-buttons.ts @@ -112,6 +112,6 @@ export const createBanCommandButtons = ({ registerButtonSubmitInteraction(handler); return { - buildButtons: (targetId: string) => buildButtons(targetId), + buildButtons, }; }; From 6c5b83de22a88fe8466ab91130b826e153465695 Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 21:49:58 +0000 Subject: [PATCH 10/15] feat: update colours on embeds --- src/features/repel/embeds.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/features/repel/embeds.ts b/src/features/repel/embeds.ts index e490dd9..0ac4966 100644 --- a/src/features/repel/embeds.ts +++ b/src/features/repel/embeds.ts @@ -29,8 +29,7 @@ export const buildCommandEmbed = ({ .setDescription( `Used \`repel\` command in ${channelInfo}.\n${commandString}` ) - .setColor(Colors.Green) - .setTimestamp(); + .setColor(Colors.Green); export const buildFailedChannelsEmbed = ( failedChannels: string[] @@ -86,4 +85,5 @@ export const buildDeletedMessagesEmbed = ( new EmbedBuilder() .setTitle('Deleted Messages') .setDescription(buildDeletedMessagesDescription(deletedMessages)) - .setColor(Colors.Red); + .setColor(Colors.Red) + .setTimestamp(); From 109a154c74337e9bc82de61a7b840f5574c9b0b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Skraburski?= Date: Thu, 3 Dec 2026 21:51:08 +0000 Subject: [PATCH 11/15] Update src/features/repel/embeds.ts Co-authored-by: Cake --- src/features/repel/embeds.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/features/repel/embeds.ts b/src/features/repel/embeds.ts index 0ac4966..8164ffa 100644 --- a/src/features/repel/embeds.ts +++ b/src/features/repel/embeds.ts @@ -45,6 +45,7 @@ export const buildResultEmbed = (context: { member: GuildMember; reason: string; duration?: number; + shouldSendDm: boolean; dmSent: boolean; }): EmbedBuilder => { const footerParts = [ From 3edd0cf551133459e786b470e55a950ce681dba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Skraburski?= Date: Thu, 3 Dec 2026 21:51:18 +0000 Subject: [PATCH 12/15] Update src/features/repel/embeds.ts Co-authored-by: Cake --- src/features/repel/embeds.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/features/repel/embeds.ts b/src/features/repel/embeds.ts index 8164ffa..d313af6 100644 --- a/src/features/repel/embeds.ts +++ b/src/features/repel/embeds.ts @@ -53,8 +53,8 @@ export const buildResultEmbed = (context: { ? `Timeout: ${timeToString(context.duration)}` : 'No timeout', ]; - if (context.dmSent) { - footerParts.push('DM sent'); + if (context.shouldSendDm) { + footerParts.push(context.dmSent ? 'DM sent' : 'DM sent error'); } return new EmbedBuilder() From 3b009482c18b2912992d0de181b8b50433cdcedd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Skraburski?= Date: Thu, 3 Dec 2026 21:51:28 +0000 Subject: [PATCH 13/15] Update src/features/repel/repel.ts Co-authored-by: Cake --- src/features/repel/repel.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/features/repel/repel.ts b/src/features/repel/repel.ts index fe37b00..4946f9b 100644 --- a/src/features/repel/repel.ts +++ b/src/features/repel/repel.ts @@ -380,12 +380,7 @@ export const repelCommand = createSlashCommand({ const commandUser = interaction.member as GuildMember; - const canRepel = checkCanRepel({ - hasModeratePermission: commandUser.permissions.has( - PermissionFlagsBits.ModerateMembers - ), - hasRepelRole: commandUser.roles.cache.has(repelRole.id), - }); + const canRepel = checkCanRepel({commandUser, repelRole}); if (!canRepel.ok) { await interaction.editReply({ content: `❌ ${canRepel.message}` }); return; From 6d2e0a7ef83d3467367268d1eea629cd15926a1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Skraburski?= Date: Thu, 3 Dec 2026 21:51:36 +0000 Subject: [PATCH 14/15] Update src/features/repel/repel.ts Co-authored-by: Cake --- src/features/repel/repel.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/repel/repel.ts b/src/features/repel/repel.ts index 4946f9b..e651063 100644 --- a/src/features/repel/repel.ts +++ b/src/features/repel/repel.ts @@ -254,7 +254,7 @@ const logRepelAction = async ({ channelInfo, commandString: buildCommandString(interaction), }), - buildResultEmbed({ target, member, reason, duration, dmSent: dm.sent }), + buildResultEmbed({ target, member, reason, duration, shouldSendDm: dm.shouldSend, dmSent: dm.sent }), buildDeletedMessagesEmbed(deletedMessages), ...(failedChannelsEmbed !== null ? [failedChannelsEmbed] : []), ]; From 339c8c1fcab48c3887455ee0721455f650baf1ae Mon Sep 17 00:00:00 2001 From: michal-skraburski Date: Thu, 3 Dec 2026 21:58:53 +0000 Subject: [PATCH 15/15] fix: broken auth and logic --- src/features/repel/repel.ts | 12 +++++++++--- src/features/repel/util.test.ts | 29 ----------------------------- src/features/repel/util.ts | 20 ++++++++++++++------ 3 files changed, 23 insertions(+), 38 deletions(-) diff --git a/src/features/repel/repel.ts b/src/features/repel/repel.ts index e651063..532cdb5 100644 --- a/src/features/repel/repel.ts +++ b/src/features/repel/repel.ts @@ -8,7 +8,6 @@ import { type GuildMember, type Message, MessageFlags, - PermissionFlagsBits, roleMention, type TextChannel, TextDisplayBuilder, @@ -254,7 +253,14 @@ const logRepelAction = async ({ channelInfo, commandString: buildCommandString(interaction), }), - buildResultEmbed({ target, member, reason, duration, shouldSendDm: dm.shouldSend, dmSent: dm.sent }), + buildResultEmbed({ + target, + member, + reason, + duration, + shouldSendDm: dm.shouldSend, + dmSent: dm.sent, + }), buildDeletedMessagesEmbed(deletedMessages), ...(failedChannelsEmbed !== null ? [failedChannelsEmbed] : []), ]; @@ -380,7 +386,7 @@ export const repelCommand = createSlashCommand({ const commandUser = interaction.member as GuildMember; - const canRepel = checkCanRepel({commandUser, repelRole}); + const canRepel = checkCanRepel({ commandUser, repelRole }); if (!canRepel.ok) { await interaction.editReply({ content: `❌ ${canRepel.message}` }); return; diff --git a/src/features/repel/util.test.ts b/src/features/repel/util.test.ts index 40774ef..dc22274 100644 --- a/src/features/repel/util.test.ts +++ b/src/features/repel/util.test.ts @@ -3,7 +3,6 @@ import { describe, it } from 'node:test'; import { HOUR, MINUTE } from '@/constants/time.js'; import { buildDeletedMessagesDescription, - checkCanRepel, checkCanRepelTarget, DEFAULT_TIMEOUT_DURATION_MS, type DeletedMessageSnapshot, @@ -86,34 +85,6 @@ void describe('repel/util', () => { }); }); - void describe('checkCanRepel', () => { - void it('denies a user with neither the permission nor the role', () => { - const result = checkCanRepel({ - hasModeratePermission: false, - hasRepelRole: false, - }); - assert.equal(result.ok, false); - assert.equal( - result.message, - 'You do not have permission to use this command.' - ); - }); - - void it('allows a user with the moderate permission', () => { - assert.deepEqual( - checkCanRepel({ hasModeratePermission: true, hasRepelRole: false }), - { ok: true } - ); - }); - - void it('allows a user with the repel role', () => { - assert.deepEqual( - checkCanRepel({ hasModeratePermission: false, hasRepelRole: true }), - { ok: true } - ); - }); - }); - void describe('checkCanRepelTarget', () => { const base = { isBot: false, diff --git a/src/features/repel/util.ts b/src/features/repel/util.ts index 032945e..8358fb2 100644 --- a/src/features/repel/util.ts +++ b/src/features/repel/util.ts @@ -1,4 +1,9 @@ -import { channelMention } from 'discord.js'; +import { + channelMention, + type GuildMember, + PermissionFlagsBits, + type Role, +} from 'discord.js'; import { HOUR, MINUTE } from '@/constants/time.js'; import { clampText } from '@/util/text.js'; @@ -39,13 +44,16 @@ export const isTimedOut = ( : false; export const checkCanRepel = ({ - hasModeratePermission, - hasRepelRole, + commandUser, + repelRole, }: { - hasModeratePermission: boolean; - hasRepelRole: boolean; + commandUser: GuildMember; + repelRole: Role; }): PermissionCheck => { - if (!hasModeratePermission && !hasRepelRole) { + 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.',