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/ban-buttons/ban-command-buttons.ts b/src/features/ban-buttons/ban-command-buttons.ts index 75fa2e1..b5e0a71 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, }; }; diff --git a/src/features/repel/embeds.ts b/src/features/repel/embeds.ts new file mode 100644 index 0000000..d313af6 --- /dev/null +++ b/src/features/repel/embeds.ts @@ -0,0 +1,90 @@ +import { + channelMention, + Colors, + EmbedBuilder, + type GuildMember, + type User, + userMention, +} from 'discord.js'; +import { timeToString } from '@/constants/time.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); + +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 buildResultEmbed = (context: { + target: User | GuildMember; + member: GuildMember; + reason: string; + duration?: number; + shouldSendDm: boolean; + dmSent: boolean; +}): EmbedBuilder => { + const footerParts = [ + context.duration + ? `Timeout: ${timeToString(context.duration)}` + : 'No timeout', + ]; + if (context.shouldSendDm) { + footerParts.push(context.dmSent ? 'DM sent' : 'DM sent error'); + } + + return new EmbedBuilder() + .setTitle('Repel') + .addFields( + { + name: 'Repelled User', + value: userMention(context.target.id), + inline: true, + }, + { + name: 'Repelled By', + value: userMention(context.member.id), + inline: true, + }, + { + name: 'Reason', + value: context.reason, + inline: true, + } + ) + .setColor(Colors.Orange) + .setFooter({ text: footerParts.join(' • ') }); +}; + +export const buildDeletedMessagesEmbed = ( + deletedMessages: DeletedMessageSnapshot[] +): EmbedBuilder => + new EmbedBuilder() + .setTitle('Deleted Messages') + .setDescription(buildDeletedMessagesDescription(deletedMessages)) + .setColor(Colors.Red) + .setTimestamp(); diff --git a/src/features/moderation/repel.ts b/src/features/repel/repel.ts similarity index 68% rename from src/features/moderation/repel.ts rename to src/features/repel/repel.ts index f091ce5..532cdb5 100644 --- a/src/features/moderation/repel.ts +++ b/src/features/repel/repel.ts @@ -1,15 +1,14 @@ import { ApplicationCommandOptionType, ChannelType, + channelMention, type ChatInputCommandInteraction, Colors, ContainerBuilder, - EmbedBuilder, type GuildMember, type Message, MessageFlags, - PermissionFlagsBits, - type Role, + roleMention, type TextChannel, TextDisplayBuilder, type User, @@ -24,86 +23,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 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, @@ -169,7 +107,7 @@ const handleTimeout = async ({ if ( durationInMilliseconds === 0 || !isUserInServer(target) || - isUserTimedOut(target) + isTimedOut(target.communicationDisabledUntilTimestamp, Date.now()) ) { return 0; } @@ -203,15 +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(); @@ -223,10 +162,6 @@ const handleDeleteMessages = async ({ message.deletable ) { targetMessages.set(id, message); - latestMessageTimestamp = Math.max( - latestMessageTimestamp, - message.createdTimestamp - ); } } @@ -235,20 +170,26 @@ const handleDeleteMessages = async ({ } } - // If no messages found from the target user, return early - if (latestMessageTimestamp === 0) { - return { deleted: 0, failedChannels: [] }; + 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 { const messagesToDelete: string[] = []; + const snapshots: DeletedMessageSnapshot[] = []; for (const [id, message] of targetMessages) { - if (latestMessageTimestamp - message.createdTimestamp < lookBack) { + if (isWithinLookback(now, message.createdTimestamp, lookBack)) { messagesToDelete.push(id); + snapshots.push({ + channelId: message.channelId, + content: message.content, + createdTimestamp: message.createdTimestamp, + attachmentCount: message.attachments.size, + }); } } @@ -257,6 +198,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 +214,7 @@ const handleDeleteMessages = async ({ `Failed to delete messages in ${failedChannels.length} channel(s).` ); } - return { deleted, failedChannels }; + return { deleted, failedChannels, deletedMessages }; }; const logRepelAction = async ({ @@ -280,7 +222,7 @@ const logRepelAction = async ({ member, target, duration, - deleteCount, + deletedMessages, reason, failedChannels, dm, @@ -290,7 +232,7 @@ const logRepelAction = async ({ target: User | GuildMember; reason: string; duration?: number; - deleteCount: number; + deletedMessages: DeletedMessageSnapshot[]; failedChannels: string[]; dm: { sent: boolean; @@ -300,92 +242,41 @@ 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({ + target, + member, + reason, + duration, + shouldSendDm: dm.shouldSend, + dmSent: dm.sent, + }), + buildDeletedMessagesEmbed(deletedMessages), + ...(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 = - failedChannelsEmbed !== null - ? [commandEmbed, resultEmbed, failedChannelsEmbed] - : [commandEmbed, resultEmbed]; await logToChannel({ channel: SERVER_CHANNELS.repelLogs, content: { type: 'custom', options: { - embeds: embed, + embeds, content: mentionText, components: [buildRepelBanButtons(target.id)], }, @@ -509,11 +400,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; @@ -528,19 +425,17 @@ 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); - 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; @@ -560,7 +455,7 @@ export const repelCommand = createSlashCommand({ target, reason, duration: timeout, - deleteCount: deleted, + deletedMessages, failedChannels, dm: { sent: dmSent, @@ -573,6 +468,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.', + }); } }, }); diff --git a/src/features/repel/util.test.ts b/src/features/repel/util.test.ts new file mode 100644 index 0000000..dc22274 --- /dev/null +++ b/src/features/repel/util.test.ts @@ -0,0 +1,240 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { HOUR, MINUTE } from '@/constants/time.js'; +import { + buildDeletedMessagesDescription, + 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', + 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 now = 1_000_000; + + void it('includes a message inside the window', () => { + assert.equal(isWithinLookback(now, now - 5 * MINUTE, 10 * MINUTE), true); + }); + + void it('excludes a message exactly at the window edge', () => { + assert.equal( + isWithinLookback(now, now - 10 * MINUTE, 10 * MINUTE), + false + ); + }); + + void it('excludes a stale message even when it is the most recent one', () => { + assert.equal( + isWithinLookback(now, now - 20 * MINUTE, 10 * MINUTE), + false + ); + }); + + void it('includes a message sent at the reference time', () => { + assert.equal(isWithinLookback(now, now, 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('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 and content', () => { + const line = formatDeletedMessageLine( + snapshot({ channelId: '42', content: 'spam' }) + ); + assert.equal(line.includes('<#42>'), 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('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 }), + 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..8358fb2 --- /dev/null +++ b/src/features/repel/util.ts @@ -0,0 +1,147 @@ +import { + channelMention, + type GuildMember, + PermissionFlagsBits, + type Role, +} 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; + 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 = ( + referenceTimestamp: number, + createdTimestamp: number, + lookBack: number +): boolean => referenceTimestamp - createdTimestamp < lookBack; + +export const isTimedOut = ( + communicationDisabledUntilTimestamp: number | null, + now: number +): boolean => + communicationDisabledUntilTimestamp + ? communicationDisabledUntilTimestamp > now + : false; + +export const checkCanRepel = ({ + commandUser, + repelRole, +}: { + commandUser: GuildMember; + repelRole: Role; +}): PermissionCheck => { + 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 }; +}; + +// 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 singleLineContent = message.content.replace(/\s*\n\s*/g, ' '); + const body = singleLineContent + ? clampText(singleLineContent, MAX_LOGGED_LINE_CONTENT) + : '(no text content)'; + 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 + ); + 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); +};