feat(bots/discord): framework changes and new features

- Migrated to a new command framework which looks better and works better
- Fixed commands not being bundled correctly
- Added message (prefix) commands with argument validation
- Added a new CommandErrorType, for invalid arguments
- `/eval` is now a bit safer
- Corrected colors for the coinflip embed
- `/stop` now works even when the bot is not connected to the API
This commit is contained in:
PalmDevs
2024-07-30 21:05:12 +07:00
parent a848a9c896
commit 646ec8da87
36 changed files with 1153 additions and 616 deletions

View File

@@ -0,0 +1,34 @@
import { inspect } from 'util'
import { runInNewContext } from 'vm'
import { ApplicationCommandOptionType } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
import { createSuccessEmbed } from '$/utils/discord/embeds'
export default new AdminCommand({
name: 'eval',
description: 'Make the bot less sentient by evaluating code',
options: {
code: {
description: 'The code to evaluate',
type: ApplicationCommandOptionType.String,
required: true,
},
['show-hidden']: {
description: 'Show hidden properties',
type: ApplicationCommandOptionType.Boolean,
required: false,
},
},
async execute(context, trigger, { code, 'show-hidden': showHidden }) {
await trigger.reply({
ephemeral: true,
embeds: [
createSuccessEmbed('Evaluate', `\`\`\`js\n${code}\`\`\``).addFields({
name: 'Result',
value: `\`\`\`js\n${inspect(runInNewContext(code, { client: trigger.client, context, trigger }), { depth: 1, showHidden, getters: true, numericSeparator: true, showProxy: true })}\`\`\``,
}),
],
})
},
})

View File

@@ -0,0 +1,21 @@
import { ApplicationCommandOptionType } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
export default new AdminCommand({
name: 'exception-test',
description: 'Makes the bot intentionally hate you by throwing an exception',
options: {
type: {
description: 'The type of exception to throw',
type: ApplicationCommandOptionType.String,
required: true,
choices: Object.keys(CommandErrorType).map(k => ({ name: k, value: k })),
},
},
async execute(_, __, { type }) {
if (type === 'Process') throw new Error('Intentional process exception')
throw new CommandError(CommandErrorType[type as keyof typeof CommandErrorType], 'Intentional bot design') // ;)
},
})

View File

@@ -0,0 +1,93 @@
import { ApplicationCommandOptionType, Routes } from 'discord.js'
import { AdminCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { createSuccessEmbed } from '$/utils/discord/embeds'
const SubcommandOptions = {
where: {
description: 'Where to register the commands',
type: ApplicationCommandOptionType.String,
choices: [
{ name: 'globally', value: 'global' },
{ name: 'this server', value: 'server' },
],
required: true,
},
} as const
export default new AdminCommand({
name: 'slash-commands',
description: 'Register or delete slash commands',
options: {
register: {
description: 'Register slash commands',
type: ApplicationCommandOptionType.Subcommand,
options: SubcommandOptions,
},
delete: {
description: 'Delete slash commands',
type: ApplicationCommandOptionType.Subcommand,
options: SubcommandOptions,
},
},
allowMessageCommand: true,
async execute(context, trigger, { delete: deleteOption, register }) {
const action = register ? 'register' : 'delete'
const { where } = (deleteOption ?? register)!
if (!trigger.inGuild())
throw new CommandError(CommandErrorType.Generic, 'This command can only be used in a server.')
const { global: globalCommands, guild: guildCommands } = Object.groupBy(
Object.values(context.discord.commands),
cmd => (cmd.global ? 'global' : 'guild'),
)
const {
client,
client: { rest },
} = trigger
let response: string | undefined
switch (action) {
case 'register':
if (where === 'global') {
response = 'Registered global slash commands'
await rest.put(Routes.applicationCommands(client.application.id), {
body: globalCommands?.map(c => c.json),
})
} else {
response = 'Registered slash commands on this server'
await rest.put(Routes.applicationGuildCommands(client.application.id, trigger.guildId), {
body: guildCommands?.map(c => c.json),
})
}
break
case 'delete':
if (where === 'global') {
response = 'Deleted global slash commands'
await rest.put(Routes.applicationCommands(client.application.id), {
body: [],
})
} else {
response = 'Deleted slash commands on this server'
await rest.put(Routes.applicationGuildCommands(client.application.id, trigger.guildId), {
body: [],
})
}
break
}
await trigger.reply({ embeds: [createSuccessEmbed(response!)] })
},
})

View File

@@ -0,0 +1,24 @@
import { AdminCommand } from '$/classes/Command'
export default new AdminCommand({
name: 'stop',
description: "You don't want to run this unless the bot starts to go insane, and like, you really need to stop it.",
async execute({ api, logger, executor }, trigger) {
api.intentionallyDisconnecting = true
logger.fatal('Stopping bot...')
trigger.reply({
content: 'Stopping... (I will go offline once done)',
ephemeral: true,
})
if (!api.client.disconnected) api.client.disconnect()
logger.warn('Disconnected from API')
trigger.client.destroy()
logger.warn('Disconnected from Discord API')
logger.info(`Bot stopped, requested by ${executor.id}`)
process.exit(0)
},
})

View File

@@ -1,32 +0,0 @@
import { inspect } from 'util'
import { SlashCommandBuilder } from 'discord.js'
import { createSuccessEmbed } from '$/utils/discord/embeds'
import type { Command } from '../types'
export default {
data: new SlashCommandBuilder()
.setName('eval')
.setDescription('Make the bot less sentient by evaluating code')
.addStringOption(option => option.setName('code').setDescription('The code to evaluate').setRequired(true))
.setDMPermission(true)
.toJSON(),
adminOnly: true,
global: true,
async execute(_, interaction) {
const code = interaction.options.getString('code', true)
await interaction.reply({
ephemeral: true,
embeds: [
createSuccessEmbed('Evaluate', `\`\`\`js\n${code}\`\`\``).addFields({
name: 'Result',
// biome-ignore lint/security/noGlobalEval: Deal with it
value: `\`\`\`js\n${inspect(eval(code), { depth: 1 })}\`\`\``,
}),
],
})
},
} satisfies Command

View File

@@ -1,36 +0,0 @@
import { SlashCommandBuilder } from 'discord.js'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import type { Command } from '../types'
export default {
data: new SlashCommandBuilder()
.setName('exception-test')
.setDescription('Makes the bot intentionally hate you by throwing an exception')
.addStringOption(option =>
option
.setName('type')
.setDescription('The type of exception to throw')
.setRequired(true)
.addChoices(
Object.keys(CommandErrorType).map(
k =>
({
name: k,
value: k,
}) as const,
),
),
)
.setDMPermission(true)
.toJSON(),
adminOnly: true,
global: true,
async execute(_, interaction) {
const type = interaction.options.getString('type', true)
if (type === 'Process') throw new Error('Intentional process exception')
throw new CommandError(CommandErrorType[type as keyof typeof CommandErrorType], 'Intentional bot design') // ;)
},
} satisfies Command

View File

@@ -1,35 +0,0 @@
import { SlashCommandBuilder } from 'discord.js'
import type { Command } from '../types'
export default {
data: new SlashCommandBuilder()
.setName('stop')
.setDescription(
"You don't want to run this unless the bot starts to go insane, and like, you really need to stop it.",
)
.setDMPermission(true)
.toJSON(),
adminOnly: true,
global: true,
async execute({ api, logger }, interaction) {
api.isStopping = true
logger.fatal('Stopping bot...')
await interaction.reply({
content: 'Stopping... (I will go offline once done)',
ephemeral: true,
})
api.client.disconnect()
logger.warn('Disconnected from API')
await interaction.client.destroy()
logger.warn('Disconnected from Discord API')
logger.info(`Bot stopped, requested by ${interaction.user.id}`)
process.exit(0)
},
} satisfies Command

View File

@@ -1,32 +1,37 @@
import { EmbedBuilder } from 'discord.js'
import Command from '$/classes/Command'
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'
import type { Command } from '../types'
export default {
data: new SlashCommandBuilder().setName('coinflip').setDescription('Do a coinflip!').setDMPermission(true).toJSON(),
export default new Command({
name: 'coinflip',
description: 'Do a coinflip!',
global: true,
async execute(_, interaction) {
requirements: {
defaultCondition: 'pass',
},
allowMessageCommand: true,
async execute(_, trigger) {
const result = Math.random() < 0.5 ? ('heads' as const) : ('tails' as const)
const embed = applyCommonEmbedStyles(new EmbedBuilder().setTitle('Flipping... 🪙'), true, false, false)
const embed = applyCommonEmbedStyles(new EmbedBuilder().setTitle('Flipping... 🪙'), false, false, true)
await interaction.reply({
embeds: [embed.toJSON()],
})
const reply = await trigger
.reply({
embeds: [embed.toJSON()],
})
.then(it => it.fetch())
embed.setTitle(`The coin landed on... **${result.toUpperCase()}**! ${EmojiMap[result]}`)
setTimeout(
() =>
interaction.editReply({
reply.edit({
embeds: [embed.toJSON()],
}),
1500,
)
},
} satisfies Command
})
const EmojiMap: Record<'heads' | 'tails', string> = {
heads: '🤯',

View File

@@ -1,44 +1,46 @@
import { SlashCommandBuilder, type TextBasedChannel } from 'discord.js'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { ApplicationCommandOptionType, Message } from 'discord.js'
import { ModerationCommand } from '../../classes/Command'
import { config } from '$/context'
import type { Command } from '../types'
export default {
data: new SlashCommandBuilder()
.setName('reply')
.setDescription('Send a message as the bot')
.addStringOption(option => option.setName('message').setDescription('The message to send').setRequired(true))
.addStringOption(option =>
option
.setName('reference')
.setDescription('The message ID to reply to (use `latest` to reply to the latest message)')
.setRequired(false),
)
.toJSON(),
memberRequirements: {
roles: config.moderation?.roles ?? [],
export default new ModerationCommand({
name: 'reply',
description: 'Send a message as the bot',
options: {
message: {
description: 'The message to send',
required: true,
type: ApplicationCommandOptionType.String,
},
reference: {
description: 'The message ID to reply to (use `latest` to reply to the latest message)',
required: false,
type: ApplicationCommandOptionType.String,
},
},
allowMessageCommand: false,
async execute({ logger, executor }, trigger, { reference: ref, message: msg }) {
if (trigger instanceof Message) return
global: false,
async execute({ logger }, interaction) {
const msg = interaction.options.getString('message', true)
const ref = interaction.options.getString('reference')
const channel = (await interaction.guild!.channels.fetch(interaction.channelId)) as TextBasedChannel
const refMsg = ref?.startsWith('latest') ? (await channel.messages.fetch({ limit: 1 })).at(0)?.id : ref
const channel = await trigger.guild!.channels.fetch(trigger.channelId)
if (!channel?.isTextBased())
throw new CommandError(
CommandErrorType.InvalidArgument,
'This command can only be used in or on text channels',
)
const refMsg = ref?.startsWith('latest')
? await channel.messages.fetch({ limit: 1 }).then(it => it.first())
: ref
await channel.send({
content: msg,
reply: refMsg ? { messageReference: refMsg, failIfNotExists: true } : undefined,
})
logger.info(`User ${interaction.user.tag} made the bot say: ${msg}`)
logger.info(`User ${executor.user.tag} made the bot say: ${msg}`)
await interaction.reply({
await trigger.reply({
content: 'OK!',
ephemeral: true,
})
},
} satisfies Command
})

View File

@@ -1,58 +1,58 @@
import { SlashCommandBuilder } from 'discord.js'
import type { Command } from '../types'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { config } from '$/context'
import { createModerationActionEmbed } from '$/utils/discord/embeds'
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
import { parseDuration } from '$/utils/duration'
export default {
data: new SlashCommandBuilder()
.setName('ban')
.setDescription('Ban a user')
.addUserOption(option => option.setName('user').setRequired(true).setDescription('The user to ban'))
.addStringOption(option => option.setName('reason').setDescription('The reason for banning the user'))
.addStringOption(option =>
option.setName('dmd').setDescription('Duration to delete messages (must be from 0 to 7 days)'),
)
.toJSON(),
memberRequirements: {
roles: config.moderation?.roles ?? [],
export default new ModerationCommand({
name: 'ban',
description: 'Ban a user',
options: {
user: {
description: 'The user to ban',
required: true,
type: ModerationCommand.OptionType.User,
},
reason: {
description: 'The reason for banning the user',
required: false,
type: ModerationCommand.OptionType.String,
},
dmd: {
description: 'Duration to delete messages (must be from 0 to 7 days)',
required: false,
type: ModerationCommand.OptionType.String,
},
},
async execute({ logger, executor }, interaction, { user, reason, dmd }) {
const guild = await interaction.client.guilds.fetch(interaction.guildId)
const member = await guild.members.fetch(user).catch(() => {})
const moderator = await guild.members.fetch(executor.user)
global: false,
if (member) {
if (!member.bannable)
throw new CommandError(CommandErrorType.Generic, 'This user cannot be banned by the bot.')
async execute({ logger }, interaction) {
const user = interaction.options.getUser('user', true)
const reason = interaction.options.getString('reason') ?? 'No reason provided'
const dmd = interaction.options.getString('dmd')
const member = await interaction.guild!.members.fetch(user.id)
const moderator = await interaction.guild!.members.fetch(interaction.user.id)
if (member.bannable) throw new CommandError(CommandErrorType.Generic, 'This user cannot be banned by the bot.')
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0)
throw new CommandError(
CommandErrorType.InvalidUser,
'You cannot ban a user with a role equal to or higher than yours.',
)
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0)
throw new CommandError(
CommandErrorType.InvalidUser,
'You cannot ban a user with a role equal to or higher than yours.',
)
}
const dms = Math.floor(dmd ? parseDuration(dmd) : 0 / 1000)
await interaction.guild!.members.ban(user, {
reason: `Banned by moderator ${interaction.user.tag} (${interaction.user.id}): ${reason}`,
reason: `Banned by moderator ${executor.user.tag} (${executor.id}): ${reason}`,
deleteMessageSeconds: dms,
})
await sendModerationReplyAndLogs(
interaction,
createModerationActionEmbed('Banned', user, interaction.user, reason),
createModerationActionEmbed('Banned', user, executor.user, reason),
)
logger.info(
`${interaction.user.tag} (${interaction.user.id}) banned ${user.tag} (${user.id}) because ${reason}, deleting their messages sent in the previous ${dms}s`,
`${executor.user.tag} (${executor.id}) banned ${user.tag} (${user.id}) because ${reason}, deleting their messages sent in the previous ${dms}s`,
)
},
} satisfies Command
})

View File

@@ -1,31 +1,24 @@
import { SlashCommandBuilder } from 'discord.js'
import type { Command } from '../types'
import { config } from '$/context'
import { ModerationCommand } from '$/classes/Command'
import { createSuccessEmbed } from '$/utils/discord/embeds'
import { cureNickname } from '$/utils/discord/moderation'
export default {
data: new SlashCommandBuilder()
.setName('cure')
.setDescription("Cure a member's nickname")
.addUserOption(option => option.setName('member').setRequired(true).setDescription('The member to cure'))
.toJSON(),
memberRequirements: {
roles: config.moderation?.roles ?? [],
export default new ModerationCommand({
name: 'cure',
description: "Cure a member's nickname",
options: {
member: {
description: 'The member to cure',
required: true,
type: ModerationCommand.OptionType.User,
},
},
global: false,
async execute(_, interaction) {
const user = interaction.options.getUser('member', true)
const member = await interaction.guild!.members.fetch(user.id)
async execute(_, interaction, { member: user }) {
const guild = await interaction.client.guilds.fetch(interaction.guildId)
const member = await guild.members.fetch(user)
await cureNickname(member)
await interaction.reply({
embeds: [createSuccessEmbed(null, `Cured nickname for ${member.toString()}`)],
ephemeral: true,
})
},
} satisfies Command
})

View File

@@ -1,44 +1,47 @@
import { SlashCommandBuilder } from 'discord.js'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { applyRolePreset, removeRolePreset } from '$/utils/discord/rolePresets'
import type { Command } from '../types'
import { config } from '$/context'
import { createModerationActionEmbed } from '$/utils/discord/embeds'
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
import { applyRolePreset, removeRolePreset } from '$/utils/discord/rolePresets'
import { parseDuration } from '$/utils/duration'
export default {
data: new SlashCommandBuilder()
.setName('mute')
.setDescription('Mute a member')
.addUserOption(option => option.setName('member').setRequired(true).setDescription('The member to mute'))
.addStringOption(option => option.setName('reason').setDescription('The reason for muting the member'))
.addStringOption(option => option.setName('duration').setDescription('The duration of the mute'))
.toJSON(),
memberRequirements: {
roles: config.moderation?.roles ?? [],
export default new ModerationCommand({
name: 'mute',
description: 'Mute a member',
options: {
member: {
description: 'The member to mute',
required: true,
type: ModerationCommand.OptionType.User,
},
reason: {
description: 'The reason for muting the member',
required: false,
type: ModerationCommand.OptionType.String,
},
duration: {
description: 'The duration of the mute',
required: false,
type: ModerationCommand.OptionType.String,
},
},
async execute(
{ logger, executor },
interaction,
{ member: user, reason = 'No reason provided', duration: durationInput },
) {
const guild = await interaction.client.guilds.fetch(interaction.guildId)
const member = await guild.members.fetch(user.id)
const moderator = await guild.members.fetch(executor.id)
const duration = durationInput ? parseDuration(durationInput) : Infinity
global: false,
async execute({ logger }, interaction, { isExecutorBotAdmin: isExecutorAdmin }) {
const user = interaction.options.getUser('member', true)
const reason = interaction.options.getString('reason') ?? 'No reason provided'
const duration = interaction.options.getString('duration')
const durationMs = duration ? parseDuration(duration) : null
if (Number.isInteger(durationMs) && durationMs! < 1)
if (Number.isInteger(duration) && duration! < 1)
throw new CommandError(
CommandErrorType.InvalidDuration,
'The duration must be at least 1 millisecond long.',
)
const expires = durationMs ? Date.now() + durationMs : null
const moderator = await interaction.guild!.members.fetch(interaction.user.id)
const member = await interaction.guild!.members.fetch(user.id)
const expires = Math.max(duration, Date.now() + duration)
if (!member)
throw new CommandError(
CommandErrorType.InvalidUser,
@@ -48,25 +51,25 @@ export default {
if (!member.manageable)
throw new CommandError(CommandErrorType.Generic, 'This user cannot be managed by the bot.')
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0 && !isExecutorAdmin)
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0)
throw new CommandError(
CommandErrorType.InvalidUser,
'You cannot mute a user with a role equal to or higher than yours.',
)
await applyRolePreset(member, 'mute', durationMs ? Date.now() + durationMs : null)
await applyRolePreset(member, 'mute', expires)
await sendModerationReplyAndLogs(
interaction,
createModerationActionEmbed('Muted', user, interaction.user, reason, durationMs),
createModerationActionEmbed('Muted', user, executor.user, reason, duration),
)
if (durationMs)
if (duration)
setTimeout(() => {
removeRolePreset(member, 'mute')
}, durationMs)
}, duration)
logger.info(
`Moderator ${interaction.user.tag} (${interaction.user.id}) muted ${user.tag} (${user.id}) until ${expires} because ${reason}`,
`Moderator ${executor.user.tag} (${executor.user.id}) muted ${user.tag} (${user.id}) until ${expires} because ${reason}`,
)
},
} satisfies Command
})

View File

@@ -1,37 +1,32 @@
import { EmbedBuilder, GuildChannel, SlashCommandBuilder } from 'discord.js'
import { EmbedBuilder, GuildChannel } from 'discord.js'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { config } from '$/context'
import { applyCommonEmbedStyles } from '$/utils/discord/embeds'
import type { Command } from '../types'
export default {
data: new SlashCommandBuilder()
.setName('purge')
.setDescription('Purge messages from a channel')
.addIntegerOption(option =>
option.setName('amount').setDescription('The amount of messages to remove').setMaxValue(100).setMinValue(1),
)
.addUserOption(option =>
option.setName('user').setDescription('The user to remove messages from (needs `until`)'),
)
.addStringOption(option =>
option.setName('until').setDescription('The message ID to remove messages until (overrides `amount`)'),
)
.toJSON(),
memberRequirements: {
roles: config.moderation?.roles ?? [],
export default new ModerationCommand({
name: 'purge',
description: 'Purge messages from a channel',
options: {
amount: {
description: 'The amount of messages to remove',
required: false,
type: ModerationCommand.OptionType.Integer,
min: 1,
max: 100,
},
user: {
description: 'The user to remove messages from (needs `until`)',
required: false,
type: ModerationCommand.OptionType.User,
},
until: {
description: 'The message ID to remove messages until (overrides `amount`)',
required: false,
type: ModerationCommand.OptionType.String,
},
},
global: false,
async execute({ logger }, interaction) {
const amount = interaction.options.getInteger('amount')
const user = interaction.options.getUser('user')
const until = interaction.options.getString('until')
async execute({ logger, executor }, interaction, { amount, user, until }) {
if (!amount && !until)
throw new CommandError(CommandErrorType.MissingArgument, 'Either `amount` or `until` must be provided.')
@@ -59,8 +54,9 @@ export default {
await channel.bulkDelete(messages, true)
logger.info(
`Moderator ${interaction.user.tag} (${interaction.user.id}) purged ${messages.size} messages in #${channel.name} (${channel.id})`,
`Moderator ${executor.user.tag} (${executor.id}) purged ${messages.size} messages in #${channel.name} (${channel.id})`,
)
await reply.edit({
embeds: [
embed.setTitle('Purged messages').setDescription(null).addFields({
@@ -70,4 +66,4 @@ export default {
],
})
},
} satisfies Command
})

View File

@@ -1,49 +1,48 @@
import { SlashCommandBuilder } from 'discord.js'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { sendPresetReplyAndLogs } from '$/utils/discord/moderation'
import { applyRolePreset, removeRolePreset } from '$/utils/discord/rolePresets'
import { parseDuration } from '$/utils/duration'
import type { Command } from '../types'
export default {
data: new SlashCommandBuilder()
.setName('role-preset')
.setDescription('Manage role presets for a member')
.addStringOption(option =>
option
.setName('action')
.setRequired(true)
.setDescription('The action to perform')
.addChoices([
{ name: 'apply', value: 'apply' },
{ name: 'remove', value: 'remove' },
]),
)
.addUserOption(option => option.setName('member').setRequired(true).setDescription('The member to manage'))
.addStringOption(option =>
option.setName('preset').setRequired(true).setDescription('The preset to apply or remove'),
)
.addStringOption(option =>
option.setName('duration').setDescription('The duration to apply the preset for (only for apply action)'),
)
.toJSON(),
memberRequirements: {
roles: ['955220417969262612', '973886585294704640'],
const SubcommandOptions = {
member: {
description: 'The member to manage',
required: true,
type: ModerationCommand.OptionType.User,
},
preset: {
description: 'The preset to apply or remove',
required: true,
type: ModerationCommand.OptionType.String,
},
duration: {
description: 'The duration to apply the preset for (only for apply action)',
required: false,
type: ModerationCommand.OptionType.String,
},
} as const
global: false,
export default new ModerationCommand({
name: 'role-preset',
description: 'Manage role presets for a member',
options: {
apply: {
description: 'Apply a role preset to a member',
type: ModerationCommand.OptionType.Subcommand,
options: SubcommandOptions,
},
remove: {
description: 'Remove a role preset from a member',
type: ModerationCommand.OptionType.Subcommand,
options: SubcommandOptions,
},
},
async execute({ logger, executor }, trigger, { apply, remove }) {
let expires: number | undefined
const { member: user, duration: durationInput, preset } = (apply ?? remove)!
const moderator = await trigger.guild!.members.fetch(executor.user.id)
const member = await trigger.guild!.members.fetch(user.id)
async execute({ logger }, interaction, { isExecutorBotAdmin: isExecutorAdmin }) {
const action = interaction.options.getString('action', true) as 'apply' | 'remove'
const user = interaction.options.getUser('member', true)
const preset = interaction.options.getString('preset', true)
const duration = interaction.options.getString('duration')
let expires: number | null | undefined = undefined
const moderator = await interaction.guild!.members.fetch(interaction.user.id)
const member = await interaction.guild!.members.fetch(user.id)
if (!member)
throw new CommandError(
CommandErrorType.InvalidUser,
@@ -53,29 +52,29 @@ export default {
if (!member.manageable)
throw new CommandError(CommandErrorType.Generic, 'This user cannot be managed by the bot.')
if (action === 'apply') {
const durationMs = duration ? parseDuration(duration) : null
if (Number.isInteger(durationMs) && durationMs! < 1)
if (apply) {
const duration = durationInput ? parseDuration(durationInput) : Infinity
if (Number.isInteger(duration) && duration! < 1)
throw new CommandError(
CommandErrorType.InvalidDuration,
'The duration must be at least 1 millisecond long.',
)
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0 && !isExecutorAdmin)
if (moderator.roles.highest.comparePositionTo(member.roles.highest) <= 0)
throw new CommandError(
CommandErrorType.InvalidUser,
'You cannot apply a role preset to a user with a role equal to or higher than yours.',
)
expires = durationMs ? Date.now() + durationMs : null
expires = Math.max(duration, Date.now() + duration)
await applyRolePreset(member, preset, expires)
logger.info(
`Moderator ${interaction.user.tag} (${interaction.user.id}) applied role preset ${preset} to ${user.id} until ${expires}`,
`Moderator ${executor.user.tag} (${executor.user.id}) applied role preset ${preset} to ${user.id} until ${expires}`,
)
} else if (action === 'remove') {
} else if (remove) {
await removeRolePreset(member, preset)
logger.info(
`Moderator ${interaction.user.tag} (${interaction.user.id}) removed role preset ${preset} from ${user.id}`,
`Moderator ${executor.user.tag} (${executor.user.id}) removed role preset ${preset} from ${user.id}`,
)
}
@@ -84,6 +83,6 @@ export default {
removeRolePreset(member, preset)
}, expires)
await sendPresetReplyAndLogs(action, interaction, user, preset, expires)
await sendPresetReplyAndLogs(apply ? 'apply' : 'remove', trigger, executor, user, preset, expires)
},
} satisfies Command
})

View File

@@ -1,39 +1,31 @@
import { createSuccessEmbed } from '$/utils/discord/embeds'
import { durationToString, parseDuration } from '$/utils/duration'
import { SlashCommandBuilder } from 'discord.js'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { config } from '$/context'
import type { Command } from '../types'
import { ChannelType } from 'discord.js'
export default {
data: new SlashCommandBuilder()
.setName('slowmode')
.setDescription('Set a slowmode for the current channel')
.addStringOption(option => option.setName('duration').setDescription('The duration to set').setRequired(true))
.addStringOption(option =>
option
.setName('channel')
.setDescription('The channel to set the slowmode on (defaults to current channel)')
.setRequired(false),
)
.toJSON(),
memberRequirements: {
roles: config.moderation?.roles ?? [],
export default new ModerationCommand({
name: 'slowmode',
description: 'Set a slowmode for a channel',
options: {
duration: {
description: 'The duration to set',
required: true,
type: ModerationCommand.OptionType.String,
},
channel: {
description: 'The channel to set the slowmode on (defaults to current channel)',
required: false,
type: ModerationCommand.OptionType.Channel,
types: [ChannelType.GuildText],
},
},
async execute({ logger, executor }, interaction, { duration: durationInput, channel: channelInput }) {
const channel = channelInput ?? (await interaction.guild!.channels.fetch(interaction.channelId))
const duration = parseDuration(durationInput)
global: false,
async execute({ logger }, interaction) {
const durationStr = interaction.options.getString('duration', true)
const id = interaction.options.getChannel('channel')?.id ?? interaction.channelId
const duration = parseDuration(durationStr)
const channel = await interaction.guild!.channels.fetch(id)
if (!channel?.isTextBased())
if (!channel?.isTextBased() || channel.isDMBased())
throw new CommandError(
CommandErrorType.InvalidChannel,
'The supplied channel is not a text channel or does not exist.',
@@ -46,10 +38,7 @@ export default {
'Duration out of range, must be between 0s and 6h.',
)
logger.info(`Setting slowmode to ${duration}ms on ${channel.id}`)
await channel.setRateLimitPerUser(duration / 1000, `Set by ${interaction.user.tag} (${interaction.user.id})`)
await channel.setRateLimitPerUser(duration / 1000, `Set by ${executor.user.tag} (${executor.id})`)
await interaction.reply({
embeds: [
createSuccessEmbed(
@@ -59,7 +48,7 @@ export default {
})
logger.info(
`${interaction.user.tag} (${interaction.user.id}) set the slowmode on ${channel.name} (${channel.id}) to ${duration}ms`,
`${executor.user.tag} (${executor.id}) set the slowmode on ${channel.name} (${channel.id}) to ${duration}ms`,
)
},
} satisfies Command
})

View File

@@ -1,33 +1,21 @@
import { SlashCommandBuilder } from 'discord.js'
import type { Command } from '../types'
import { config } from '$/context'
import { ModerationCommand } from '$/classes/Command'
import { createModerationActionEmbed } from '$/utils/discord/embeds'
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
export default {
data: new SlashCommandBuilder()
.setName('unban')
.setDescription('Unban a user')
.addUserOption(option => option.setName('user').setRequired(true).setDescription('The user to unban'))
.toJSON(),
memberRequirements: {
roles: config.moderation?.roles ?? [],
export default new ModerationCommand({
name: 'unban',
description: 'Unban a user',
options: {
user: {
description: 'The user to unban',
required: true,
type: ModerationCommand.OptionType.User,
},
},
async execute({ logger, executor }, interaction, { user }) {
await interaction.guild!.members.unban(user, `Unbanned by moderator ${executor.user.tag} (${executor.id})`)
global: false,
async execute({ logger }, interaction) {
const user = interaction.options.getUser('user', true)
await interaction.guild!.members.unban(
user,
`Unbanned by moderator ${interaction.user.tag} (${interaction.user.id})`,
)
await sendModerationReplyAndLogs(interaction, createModerationActionEmbed('Unbanned', user, interaction.user))
logger.info(`${interaction.user.tag} (${interaction.user.id}) unbanned ${user.tag} (${user.id})`)
await sendModerationReplyAndLogs(interaction, createModerationActionEmbed('Unbanned', user, executor.user))
logger.info(`${executor.user.tag} (${executor.id}) unbanned ${user.tag} (${user.id})`)
},
} satisfies Command
})

View File

@@ -1,29 +1,22 @@
import { SlashCommandBuilder } from 'discord.js'
import { ModerationCommand } from '$/classes/Command'
import CommandError, { CommandErrorType } from '$/classes/CommandError'
import { config } from '$/context'
import { appliedPresets } from '$/database/schemas'
import { createModerationActionEmbed } from '$/utils/discord/embeds'
import { sendModerationReplyAndLogs } from '$/utils/discord/moderation'
import { removeRolePreset } from '$/utils/discord/rolePresets'
import { and, eq } from 'drizzle-orm'
import type { Command } from '../types'
export default {
data: new SlashCommandBuilder()
.setName('unmute')
.setDescription('Unmute a member')
.addUserOption(option => option.setName('member').setRequired(true).setDescription('The member to unmute'))
.toJSON(),
memberRequirements: {
roles: config.moderation?.roles ?? [],
export default new ModerationCommand({
name: 'unmute',
description: 'Unmute a member',
options: {
member: {
description: 'The member to unmute',
required: true,
type: ModerationCommand.OptionType.User,
},
},
global: false,
async execute({ logger, database }, interaction) {
const user = interaction.options.getUser('member', true)
async execute({ logger, database, executor }, interaction, { member: user }) {
const member = await interaction.guild!.members.fetch(user.id)
if (!member)
throw new CommandError(
@@ -39,8 +32,8 @@ export default {
throw new CommandError(CommandErrorType.Generic, 'This user is not muted.')
await removeRolePreset(member, 'mute')
await sendModerationReplyAndLogs(interaction, createModerationActionEmbed('Unmuted', user, interaction.user))
await sendModerationReplyAndLogs(interaction, createModerationActionEmbed('Unmuted', user, executor.user))
logger.info(`Moderator ${interaction.user.tag} (${interaction.user.id}) unmuted ${user.tag} (${user.id})`)
logger.info(`Moderator ${executor.user.tag} (${executor.id}) unmuted ${user.tag} (${user.id})`)
},
} satisfies Command
})

View File

@@ -1,56 +0,0 @@
import type { SlashCommandBuilder } from '@discordjs/builders'
import type { ChatInputCommandInteraction } from 'discord.js'
// Temporary system
export type Command = {
data: ReturnType<SlashCommandBuilder['toJSON']>
// The function has to return void or Promise<void>
// because TS may complain about some code paths not returning a value
/**
* The function to execute when this command is triggered
* @param interaction The interaction that triggered this command
*/
execute: (
context: typeof import('../context'),
interaction: ChatInputCommandInteraction,
info: Info,
) => Promise<void> | void
memberRequirements?: {
/**
* The mode to use when checking for requirements.
* - `all` means that the user needs meet all requirements specified.
* - `any` means that the user needs to meet any of the requirements specified.
*
* @default "all"
*/
mode?: 'all' | 'any'
/**
* The permissions required to use this command (in BitFields).
*
* - **0n** means that everyone can use this command.
* - **-1n** means that only bot owners can use this command.
* @default -1n
*/
permissions?: bigint
/**
* The roles required to use this command.
* By default, this is set to `[]`.
*/
roles?: string[]
}
/**
* Whether this command can only be used by bot admins.
* @default false
*/
adminOnly?: boolean
/**
* Whether to register this command as a global slash command.
* This is set to `false` and commands will be registered in allowed guilds only by default.
* @default false
*/
global?: boolean
}
export interface Info {
isExecutorBotAdmin: boolean
}