diff options
Diffstat (limited to 'src')
29 files changed, 515 insertions, 118 deletions
diff --git a/src/arguments/discordEmoji.ts b/src/arguments/discordEmoji.ts index d9428e1..efaa4dd 100644 --- a/src/arguments/discordEmoji.ts +++ b/src/arguments/discordEmoji.ts @@ -1,5 +1,5 @@ -import { type BushArgumentTypeCaster } from '#lib'; -import { type Snowflake } from 'discord-api-types'; +import type { BushArgumentTypeCaster } from '#lib'; +import type { Snowflake } from 'discord-api-types'; export const discordEmoji: BushArgumentTypeCaster<DiscordEmojiInfo | null> = (_, phrase) => { if (!phrase) return null; diff --git a/src/commands/config/config.ts b/src/commands/config/config.ts index 2fae2fd..5346924 100644 --- a/src/commands/config/config.ts +++ b/src/commands/config/config.ts @@ -354,6 +354,7 @@ export default class ConfigCommand extends BushCommand { }; const components = new ActionRow().addComponents( + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Primary).setCustomId('command_settingsBack').setLabel('Back') ); settingsEmbed.setDescription( diff --git a/src/commands/config/features.ts b/src/commands/config/features.ts index 2e7d623..7fa82a9 100644 --- a/src/commands/config/features.ts +++ b/src/commands/config/features.ts @@ -90,7 +90,7 @@ export default class FeaturesCommand extends BushCommand { .setMaxValues(1) .setMinValues(1) .setOptions( - guildFeatures.map((f) => + ...guildFeatures.map((f) => new SelectMenuOption().setLabel(guildFeaturesObj[f].name).setValue(f).setDescription(guildFeaturesObj[f].description) ) ) diff --git a/src/commands/dev/servers.ts b/src/commands/dev/servers.ts index 173970b..378893e 100644 --- a/src/commands/dev/servers.ts +++ b/src/commands/dev/servers.ts @@ -1,6 +1,6 @@ import { BushCommand, ButtonPaginator, type BushMessage, type BushSlashMessage } from '#lib'; -import { APIEmbed } from 'discord-api-types'; -import { type Guild } from 'discord.js'; +import type { APIEmbed } from 'discord-api-types'; +import type { Guild } from 'discord.js'; export default class ServersCommand extends BushCommand { public constructor() { diff --git a/src/commands/dev/test.ts b/src/commands/dev/test.ts index 669001f..9784412 100644 --- a/src/commands/dev/test.ts +++ b/src/commands/dev/test.ts @@ -1,5 +1,4 @@ import { BushCommand, ButtonPaginator, Shared, type BushMessage } from '#lib'; -// eslint-disable-next-line node/file-extension-in-import import { Routes } from 'discord-api-types/rest/v9'; import { ActionRow, @@ -55,10 +54,15 @@ export default class TestCommand extends BushCommand { if (['button', 'buttons'].includes(args?.feature?.toLowerCase())) { const ButtonRow = new ActionRow().addComponents( + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Primary).setCustomId('primaryButton').setLabel('Primary'), + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Secondary).setCustomId('secondaryButton').setLabel('Secondary'), + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Success).setCustomId('successButton').setLabel('Success'), + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Danger).setCustomId('dangerButton').setLabel('Danger'), + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Link).setLabel('Link').setURL('https://www.youtube.com/watch?v=dQw4w9WgXcQ') ); return await message.util.reply({ content: 'buttons', components: [ButtonRow] }); @@ -78,6 +82,7 @@ export default class TestCommand extends BushCommand { .setTitle('Title'); const buttonRow = new ActionRow().addComponents( + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Link).setLabel('Link').setURL('https://google.com/') ); return await message.util.reply({ content: 'Test', embeds: [embed], components: [buttonRow] }); @@ -87,6 +92,7 @@ export default class TestCommand extends BushCommand { const row = new ActionRow(); for (let b = 1; b <= 5; b++) { const id = (a + 5 * (b - 1)).toString(); + // @ts-expect-error: outdated @discord.js/builders const button = new ButtonComponent().setStyle(ButtonStyle.Primary).setCustomId(id).setLabel(id); row.addComponents(button); } @@ -119,6 +125,7 @@ export default class TestCommand extends BushCommand { const row = new ActionRow(); for (let b = 1; b <= 5; b++) { const id = (a + 5 * (b - 1)).toString(); + // @ts-expect-error: outdated @discord.js/builders const button = new ButtonComponent().setStyle(ButtonStyle.Secondary).setCustomId(id).setLabel(id); row.addComponents(button); } @@ -151,6 +158,7 @@ export default class TestCommand extends BushCommand { content: 'Click for modal', components: [ new ActionRow().addComponents( + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Primary).setLabel('Modal').setCustomId('test;modal') ) ] diff --git a/src/commands/info/guildInfo.ts b/src/commands/info/guildInfo.ts index a4b7fb9..ed8a973 100644 --- a/src/commands/info/guildInfo.ts +++ b/src/commands/info/guildInfo.ts @@ -1,6 +1,6 @@ import { BushCommand, type ArgType, type BushMessage, type BushSlashMessage, type OptionalArgType } from '#lib'; import assert from 'assert'; -import { GuildDefaultMessageNotifications, GuildExplicitContentFilter } from 'discord-api-types'; +import { GuildDefaultMessageNotifications, GuildExplicitContentFilter } from 'discord-api-types/v9'; import { ApplicationCommandOptionType, Embed, diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 2383566..ef3ef30 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -143,14 +143,17 @@ export default class HelpCommand extends BushCommand { const row = new ActionRow(); if (!client.config.isDevelopment && !client.guilds.cache.some((guild) => guild.ownerId === message.author.id)) { + // @ts-expect-error: outdated @discord.js/builders row.addComponents(new ButtonComponent().setStyle(ButtonStyle.Link).setLabel('Invite Me').setURL(util.invite)); } if (!client.guilds.cache.get(client.config.supportGuild.id)?.members.cache.has(message.author.id)) { row.addComponents( + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Link).setLabel('Support Server').setURL(client.config.supportGuild.invite) ); } if (packageDotJSON?.repository) + // @ts-expect-error: outdated @discord.js/builders row.addComponents(new ButtonComponent().setStyle(ButtonStyle.Link).setLabel('GitHub').setURL(packageDotJSON.repository)); else void message.channel?.send('Error importing package.json, please report this to my developer.'); diff --git a/src/commands/info/links.ts b/src/commands/info/links.ts index 25b040c..d9d5b8a 100644 --- a/src/commands/info/links.ts +++ b/src/commands/info/links.ts @@ -22,10 +22,13 @@ export default class LinksCommand extends BushCommand { public override async exec(message: BushMessage | BushSlashMessage) { const buttonRow = new ActionRow(); if (!client.config.isDevelopment || message.author.isOwner()) { + // @ts-expect-error: outdated @discord.js/builders buttonRow.addComponents(new ButtonComponent().setStyle(ButtonStyle.Link).setLabel('Invite Me').setURL(util.invite)); } buttonRow.addComponents( + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Link).setLabel('Support Server').setURL(client.config.supportGuild.invite), + // @ts-expect-error: outdated @discord.js/builders new ButtonComponent().setStyle(ButtonStyle.Link).setLabel('GitHub').setURL(packageDotJSON.repository) ); return await message.util.reply({ content: 'Here are some useful links:', components: [buttonRow] }); diff --git a/src/commands/info/userInfo.ts b/src/commands/info/userInfo.ts index 97cdc30..02a3be6 100644 --- a/src/commands/info/userInfo.ts +++ b/src/commands/info/userInfo.ts @@ -7,7 +7,7 @@ import { type BushSlashMessage, type BushUser } from '#lib'; -import { APIApplication, TeamMemberMembershipState } from 'discord-api-types'; +import { TeamMemberMembershipState, type APIApplication } from 'discord-api-types/v9'; import { ActivityType, ApplicationCommandOptionType, diff --git a/src/commands/moulberry-bush/capes.ts b/src/commands/moulberry-bush/capes.ts index 032f62d..47a4ea6 100644 --- a/src/commands/moulberry-bush/capes.ts +++ b/src/commands/moulberry-bush/capes.ts @@ -1,6 +1,6 @@ import { BushCommand, ButtonPaginator, DeleteButton, type BushMessage, type OptionalArgType } from '#lib'; import assert from 'assert'; -import { APIEmbed } from 'discord-api-types'; +import { APIEmbed } from 'discord-api-types/v9'; import { ApplicationCommandOptionType, AutocompleteInteraction, PermissionFlagsBits } from 'discord.js'; import Fuse from 'fuse.js'; import got from 'got'; diff --git a/src/commands/utilities/highlight-!.ts b/src/commands/utilities/highlight-!.ts index 332af03..687990f 100644 --- a/src/commands/utilities/highlight-!.ts +++ b/src/commands/utilities/highlight-!.ts @@ -1,6 +1,6 @@ import { BushCommand, Highlight, HighlightWord, type BushSlashMessage } from '#lib'; import { Flag, type ArgumentGeneratorReturn, type SlashOption } from 'discord-akairo'; -import { ApplicationCommandOptionType } from 'discord-api-types'; +import { ApplicationCommandOptionType } from 'discord-api-types/v9'; import { ApplicationCommandSubCommandData, AutocompleteInteraction, CacheType } from 'discord.js'; type Unpacked<T> = T extends (infer U)[] ? U : T; diff --git a/src/commands/utilities/reminders.ts b/src/commands/utilities/reminders.ts index 509da67..10206c1 100644 --- a/src/commands/utilities/reminders.ts +++ b/src/commands/utilities/reminders.ts @@ -1,6 +1,6 @@ import { BushCommand, ButtonPaginator, Reminder, type BushMessage, type BushSlashMessage } from '#lib'; import assert from 'assert'; -import { APIEmbed } from 'discord-api-types'; +import { APIEmbed } from 'discord-api-types/v9'; import { PermissionFlagsBits } from 'discord.js'; import { Op } from 'sequelize'; diff --git a/src/lib/common/AutoMod.ts b/src/lib/common/AutoMod.ts index 784085d..9024260 100644 --- a/src/lib/common/AutoMod.ts +++ b/src/lib/common/AutoMod.ts @@ -156,6 +156,7 @@ export class AutoMod { ? [ new ActionRow().addComponents( new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Danger) .setLabel('Ban User') .setCustomId(`automod;ban;${this.message.author.id};everyone mention and scam phrase`) @@ -277,6 +278,7 @@ export class AutoMod { ? [ new ActionRow().addComponents( new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Danger) .setLabel('Ban User') .setCustomId(`automod;ban;${this.message.author.id};${highestOffence.reason}`) diff --git a/src/lib/common/ButtonPaginator.ts b/src/lib/common/ButtonPaginator.ts index 0399e74..09e059c 100644 --- a/src/lib/common/ButtonPaginator.ts +++ b/src/lib/common/ButtonPaginator.ts @@ -1,6 +1,6 @@ import { DeleteButton, type BushMessage, type BushSlashMessage } from '#lib'; import { CommandUtil } from 'discord-akairo'; -import { APIEmbed } from 'discord-api-types'; +import { APIEmbed } from 'discord-api-types/v9'; import { ActionRow, ActionRowComponent, ButtonComponent, ButtonStyle, Embed, type MessageComponentInteraction } from 'discord.js'; /** @@ -173,26 +173,31 @@ export class ButtonPaginator { protected getPaginationRow(disableAll = false): ActionRow<ActionRowComponent> { return new ActionRow().addComponents( new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Primary) .setCustomId('paginate_beginning') .setEmoji(PaginateEmojis.BEGINNING) .setDisabled(disableAll || this.curPage === 0), new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Primary) .setCustomId('paginate_back') .setEmoji(PaginateEmojis.BACK) .setDisabled(disableAll || this.curPage === 0), new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Primary) .setCustomId('paginate_stop') .setEmoji(PaginateEmojis.STOP) .setDisabled(disableAll), new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Primary) .setCustomId('paginate_next') .setEmoji(PaginateEmojis.FORWARD) .setDisabled(disableAll || this.curPage === this.embeds.length - 1), new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Primary) .setCustomId('paginate_end') .setEmoji(PaginateEmojis.END) diff --git a/src/lib/common/ConfirmationPrompt.ts b/src/lib/common/ConfirmationPrompt.ts index bd11c5c..1f027ef 100644 --- a/src/lib/common/ConfirmationPrompt.ts +++ b/src/lib/common/ConfirmationPrompt.ts @@ -31,11 +31,13 @@ export class ConfirmationPrompt { this.messageOptions.components = [ new ActionRow().addComponents( new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Primary) .setCustomId('confirmationPrompt_confirm') .setEmoji({ id: util.emojisRaw.successFull, name: 'successFull', animated: false }) .setLabel('Yes'), new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Danger) .setCustomId('confirmationPrompt_cancel') .setEmoji({ id: util.emojisRaw.errorFull, name: 'errorFull', animated: false }) diff --git a/src/lib/common/DeleteButton.ts b/src/lib/common/DeleteButton.ts index cf3b416..f2e0ff3 100644 --- a/src/lib/common/DeleteButton.ts +++ b/src/lib/common/DeleteButton.ts @@ -68,6 +68,7 @@ export class DeleteButton { this.messageOptions.components = [ new ActionRow().addComponents( new ButtonComponent() + // @ts-expect-error: outdated @discord.js/builders .setStyle(ButtonStyle.Primary) .setCustomId('paginate__stop') .setEmoji(PaginateEmojis.STOP) diff --git a/src/lib/common/util/Moderation.ts b/src/lib/common/util/Moderation.ts index 0ba6fca..c2236ab 100644 --- a/src/lib/common/util/Moderation.ts +++ b/src/lib/common/util/Moderation.ts @@ -10,7 +10,33 @@ import { type BushUserResolvable, type ModLogType } from '#lib'; -import { Embed, PermissionFlagsBits, type Snowflake } from 'discord.js'; +import assert from 'assert'; +import { ActionRow, ButtonComponent, ButtonStyle, ComponentType, Embed, PermissionFlagsBits, type Snowflake } from 'discord.js'; + +enum punishMap { + 'warned' = 'warn', + 'muted' = 'mute', + 'unmuted' = 'unmute', + 'kicked' = 'kick', + 'banned' = 'ban', + 'unbanned' = 'unban', + 'timedout' = 'timeout', + 'untimedout' = 'untimeout', + 'blocked' = 'block', + 'unblocked' = 'unblock' +} +enum reversedPunishMap { + 'warn' = 'warned', + 'mute' = 'muted', + 'unmute' = 'unmuted', + 'kick' = 'kicked', + 'ban' = 'banned', + 'unban' = 'unbanned', + 'timeout' = 'timedout', + 'untimeout' = 'untimedout', + 'block' = 'blocked', + 'unblock' = 'unblocked' +} /** * A utility class with moderation-related methods. @@ -204,6 +230,19 @@ export class Moderation { return typeMap[type]; } + public static punishmentToPresentTense(punishment: PunishmentTypeDM): PunishmentTypePresent { + return punishMap[punishment]; + } + + public static punishmentToPastTense(punishment: PunishmentTypePresent): PunishmentTypeDM { + return reversedPunishMap[punishment]; + } + + /** + * Notifies the specified user of their punishment. + * @param options Options for notifying the user. + * @returns Whether or not the dm was successfully sent. + */ public static async punishDM(options: PunishDMOptions): Promise<boolean> { const ending = await options.guild.getSetting('punishmentEnding'); const dmEmbed = @@ -211,16 +250,45 @@ export class Moderation { ? new Embed().setDescription(ending).setColor(util.colors.newBlurple) : undefined; + const appealsEnabled = !!( + (await options.guild.hasFeature('punishmentAppeals')) && (await options.guild.getLogChannel('appeals')) + ); + + let content = `You have been ${options.punishment} `; + if (options.punishment.includes('blocked')) { + assert(options.channel); + content += `from <#${options.channel}> `; + } + content += `in ${util.format.input(options.guild.name)} `; + if (options.duration !== null && options.duration !== undefined) + content += options.duration ? `for ${util.humanizeDuration(options.duration)} ` : 'permanently '; + const reason = options.reason?.trim() ? options.reason?.trim() : 'No reason provided'; + content += `for ${util.format.input(reason)}.`; + + let components; + if (appealsEnabled && options.modlog) + components = [ + new ActionRow({ + type: ComponentType.ActionRow, + components: [ + // @ts-expect-error: outdated @discord.js/builders + new ButtonComponent({ + custom_id: `appeal;${this.punishmentToPresentTense(options.punishment)};${ + options.guild.id + };${client.users.resolveId(options.user)};${options.modlog}`, + style: ButtonStyle.Primary, + type: ComponentType.Button, + label: 'Appeal' + }) + ] + }) + ]; + const dmSuccess = await client.users .send(options.user, { - content: `You have been ${options.punishment} in **${options.guild.name}** ${ - options.duration !== null && options.duration !== undefined - ? options.duration - ? `for ${util.humanizeDuration(options.duration)} ` - : 'permanently ' - : '' - }for **${options.reason?.trim() ? options.reason?.trim() : 'No reason provided'}**.`, - embeds: dmEmbed ? [dmEmbed] : undefined + content, + embeds: dmEmbed ? [dmEmbed] : undefined, + components }) .catch(() => false); return !!dmSuccess; @@ -342,6 +410,11 @@ export interface RemovePunishmentEntryOptions { */ export interface PunishDMOptions { /** + * The modlog case id so the user can make an appeal. + */ + modlog?: string; + + /** * The guild that the punishment is taking place in. */ guild: BushGuild; @@ -354,7 +427,7 @@ export interface PunishDMOptions { /** * The punishment that the user has received. */ - punishment: string; + punishment: PunishmentTypeDM; /** * The reason the user's punishment. @@ -371,4 +444,35 @@ export interface PunishDMOptions { * @default true */ sendFooter: boolean; + + /** + * The channel that the user was (un)blocked from. + */ + channel?: Snowflake; } + +export type PunishmentTypeDM = + | 'warned' + | 'muted' + | 'unmuted' + | 'kicked' + | 'banned' + | 'unbanned' + | 'timedout' + | 'untimedout' + | 'blocked' + | 'unblocked'; + +export type PunishmentTypePresent = + | 'warn' + | 'mute' + | 'unmute' + | 'kick' + | 'ban' + | 'unban' + | 'timeout' + | 'untimeout' + | 'block' + | 'unblock'; + +export type AppealButtonId = `appeal;${PunishmentTypePresent};${Snowflake};${Snowflake};${string}`; diff --git a/src/lib/extensions/discord-akairo/BushClientUtil.ts b/src/lib/extensions/discord-akairo/BushClientUtil.ts index c4a5e79..bf4dfaf 100644 --- a/src/lib/extensions/discord-akairo/BushClientUtil.ts +++ b/src/lib/extensions/discord-akairo/BushClientUtil.ts @@ -21,13 +21,14 @@ import assert from 'assert'; import { exec } from 'child_process'; import deepLock from 'deep-lock'; import { ClientUtil, Util as AkairoUtil } from 'discord-akairo'; -import { APIMessage } from 'discord-api-types'; +import type { APIMessage } from 'discord-api-types/v9'; import { Constants as DiscordConstants, GuildMember, Message, PermissionFlagsBits, PermissionsBitField, + PermissionsString, ThreadMember, User, Util as DiscordUtil, @@ -798,10 +799,13 @@ export class BushClientUtil extends ClientUtil { * @param permissions The permissions to check for. * @returns The missing permissions or null if none are missing. */ - public userGuildPermCheck(message: BushMessage | BushSlashMessage, permissions: bigint[]) { + public userGuildPermCheck( + message: BushMessage | BushSlashMessage, + permissions: typeof PermissionFlagsBits[keyof typeof PermissionFlagsBits][] + ): PermissionsString[] | null { const missing = message.member?.permissions.missing(permissions) ?? []; - return missing.length ? missing.map((p) => PermissionFlagsBits[p]) : null; + return missing.length ? missing : null; } /** @@ -810,10 +814,10 @@ export class BushClientUtil extends ClientUtil { * @param permissions The permissions to check for. * @returns The missing permissions or null if none are missing. */ - public clientGuildPermCheck(message: BushMessage | BushSlashMessage, permissions: bigint[]) { + public clientGuildPermCheck(message: BushMessage | BushSlashMessage, permissions: bigint[]): PermissionsString[] | null { const missing = message.guild?.me?.permissions.missing(permissions) ?? []; - return missing.length ? missing.map((p) => PermissionFlagsBits[p]) : null; + return missing.length ? missing : null; } /** @@ -824,19 +828,20 @@ export class BushClientUtil extends ClientUtil { * @param checkChannel Whether to check the channel permissions instead of the guild permissions. * @returns The missing permissions or null if none are missing. */ - public clientSendAndPermCheck(message: BushMessage | BushSlashMessage, permissions: bigint[] = [], checkChannel = false) { - const missing = []; - const sendPerm = message.channel!.isThread() ? PermissionFlagsBits.SendMessages : PermissionFlagsBits.SendMessagesInThreads; + public clientSendAndPermCheck( + message: BushMessage | BushSlashMessage, + permissions: bigint[] = [], + checkChannel = false + ): PermissionsString[] | null { + const missing: PermissionsString[] = []; + const sendPerm = message.channel!.isThread() ? 'SendMessages' : 'SendMessagesInThreads'; if (!message.inGuild()) return null; if (!message.guild.me!.permissionsIn(message.channel.id).has(sendPerm)) missing.push(sendPerm); missing.push( ...(checkChannel - ? message - .guild!.me!.permissionsIn(message.channel!.id!) - .missing(permissions) - .map((p) => PermissionFlagsBits[p]) + ? message.guild!.me!.permissionsIn(message.channel!.id!).missing(permissions) : this.clientGuildPermCheck(message, permissions) ?? []) ); diff --git a/src/lib/extensions/discord-akairo/BushCommand.ts b/src/lib/extensions/discord-akairo/BushCommand.ts index 650b538..ff3748e 100644 --- a/src/lib/extensions/discord-akairo/BushCommand.ts +++ b/src/lib/extensions/discord-akairo/BushCommand.ts @@ -44,7 +44,7 @@ import { type ContextMenuCommand, type MissingPermissionSupplier, type SlashOption, - type SlashResolveTypes + type SlashResolveType } from 'discord-akairo'; import { type ApplicationCommandOptionChoice, @@ -147,7 +147,7 @@ interface BaseBushArgumentOptions extends Omit<ArgumentOptions, 'type' | 'prompt * * ex. get the resolved member object when the type is `USER` */ - slashResolve?: SlashResolveTypes; + slashResolve?: SlashResolveType; /** * The choices of the option for the user to pick from @@ -340,7 +340,7 @@ export interface ArgsInfo { description: string; optional?: boolean; slashType: AkairoApplicationCommandOptionData['type'] | false; - slashResolve?: SlashResolveTypes; + slashResolve?: SlashResolveType; only?: 'slash' | 'text'; type: string; } diff --git a/src/lib/extensions/discord.js/BushGuild.ts b/src/lib/extensions/discord.js/BushGuild.ts index 93875b8..80799fd 100644 --- a/src/lib/extensions/discord.js/BushGuild.ts +++ b/src/lib/extensions/discord.js/BushGuild.ts @@ -173,8 +173,22 @@ export class BushGuild extends Guild { if ((await this.bans.fetch()).has(user.id)) return banResponse.ALREADY_BANNED; const ret = await (async () => { + // add modlog entry + const { log: modlog } = await Moderation.createModLogEntry({ + type: options.duration ? ModLogType.TEMP_BAN : ModLogType.PERM_BAN, + user: user, + moderator: moderator.id, + reason: options.reason, + duration: options.duration, + guild: this, + evidence: options.evidence + }); + if (!modlog) return banResponse.MODLOG_ERROR; + caseID = modlog.id; + // dm user dmSuccessEvent = await Moderation.punishDM({ + modlog: modlog.id, guild: this, user: user, punishment: 'banned', @@ -187,24 +201,11 @@ export class BushGuild extends Guild { const banSuccess = await this.bans .create(user?.id ?? options.user, { reason: `${moderator.tag} | ${options.reason ?? 'No reason provided.'}`, - days: options.deleteDays + deleteMessageDays: options.deleteDays }) .catch(() => false); if (!banSuccess) return banResponse.ACTION_ERROR; - // add modlog entry - const { log: modlog } = await Moderation.createModLogEntry({ - type: options.duration ? ModLogType.TEMP_BAN : ModLogType.PERM_BAN, - user: user, - moderator: moderator.id, - reason: options.reason, - duration: options.duration, - guild: this, - evidence: options.evidence - }); - if (!modlog) return banResponse.MODLOG_ERROR; - caseID = modlog.id; - // add punishment entry so they can be unbanned later const punishmentEntrySuccess = await Moderation.createPunishmentEntry({ type: 'ban', diff --git a/src/lib/extensions/discord.js/BushGuildMember.ts b/src/lib/extensions/discord.js/BushGuildMember.ts index 84fdf13..5d7144b 100644 --- a/src/lib/extensions/discord.js/BushGuildMember.ts +++ b/src/lib/extensions/discord.js/BushGuildMember.ts @@ -3,6 +3,8 @@ import { BushClientEvents, Moderation, ModLogType, + PunishmentTypeDM, + Time, type BushClient, type BushGuild, type BushGuildTextBasedChannel, @@ -29,14 +31,29 @@ export class BushGuildMember extends GuildMember { /** * Send a punishment dm to the user. + * @param modlog The modlog case id so the user can make an appeal. * @param punishment The punishment that the user has received. * @param reason The reason for the user's punishment. * @param duration The duration of the punishment. * @param sendFooter Whether or not to send the guild's punishment footer with the dm. * @returns Whether or not the dm was sent successfully. */ - public async bushPunishDM(punishment: string, reason?: string | null, duration?: number, sendFooter = true): Promise<boolean> { - return Moderation.punishDM({ guild: this.guild, user: this, punishment, reason: reason ?? undefined, duration, sendFooter }); + public async bushPunishDM( + punishment: PunishmentTypeDM, + reason?: string | null, + duration?: number, + modlog?: string, + sendFooter = true + ): Promise<boolean> { + return Moderation.punishDM({ + modlog, + guild: this.guild, + user: this, + punishment, + reason: reason ?? undefined, + duration, + sendFooter + }); } /** @@ -304,7 +321,7 @@ export class BushGuildMember extends GuildMember { if (!options.silent) { // dm user - const dmSuccess = await this.bushPunishDM('muted', options.reason, options.duration ?? 0); + const dmSuccess = await this.bushPunishDM('muted', options.reason, options.duration ?? 0, modlog.id); dmSuccessEvent = dmSuccess; if (!dmSuccess) return muteResponse.DM_ERROR; } @@ -386,7 +403,7 @@ export class BushGuildMember extends GuildMember { if (!options.silent) { // dm user - const dmSuccess = await this.bushPunishDM('unmuted', options.reason, undefined, false); + const dmSuccess = await this.bushPunishDM('unmuted', options.reason, undefined, '', false); dmSuccessEvent = dmSuccess; if (!dmSuccess) return unmuteResponse.DM_ERROR; } @@ -429,14 +446,6 @@ export class BushGuildMember extends GuildMember { const moderator = await util.resolveNonCachedUser(options.moderator ?? this.guild.me); if (!moderator) return kickResponse.CANNOT_RESOLVE_USER; const ret = await (async () => { - // dm user - const dmSuccess = options.silent ? null : await this.bushPunishDM('kicked', options.reason); - dmSuccessEvent = dmSuccess ?? undefined; - - // kick - const kickSuccess = await this.kick(`${moderator?.tag} | ${options.reason ?? 'No reason provided.'}`).catch(() => false); - if (!kickSuccess) return kickResponse.ACTION_ERROR; - // add modlog entry const { log: modlog } = await Moderation.createModLogEntry({ type: ModLogType.KICK, @@ -449,6 +458,15 @@ export class BushGuildMember extends GuildMember { }); if (!modlog) return kickResponse.MODLOG_ERROR; caseID = modlog.id; + + // dm user + const dmSuccess = options.silent ? null : await this.bushPunishDM('kicked', options.reason, undefined, modlog.id); + dmSuccessEvent = dmSuccess ?? undefined; + + // kick + const kickSuccess = await this.kick(`${moderator?.tag} | ${options.reason ?? 'No reason provided.'}`).catch(() => false); + if (!kickSuccess) return kickResponse.ACTION_ERROR; + if (dmSuccess === false) return kickResponse.DM_ERROR; return kickResponse.SUCCESS; })(); @@ -489,17 +507,6 @@ export class BushGuildMember extends GuildMember { }); const ret = await (async () => { - // dm user - const dmSuccess = options.silent ? null : await this.bushPunishDM('banned', options.reason, options.duration ?? 0); - dmSuccessEvent = dmSuccess ?? undefined; - - // ban - const banSuccess = await this.ban({ - reason: `${moderator.tag} | ${options.reason ?? 'No reason provided.'}`, - days: options.deleteDays - }).catch(() => false); - if (!banSuccess) return banResponse.ACTION_ERROR; - // add modlog entry const { log: modlog } = await Moderation.createModLogEntry({ type: options.duration ? ModLogType.TEMP_BAN : ModLogType.PERM_BAN, @@ -514,6 +521,19 @@ export class BushGuildMember extends GuildMember { if (!modlog) return banResponse.MODLOG_ERROR; caseID = modlog.id; + // dm user + const dmSuccess = options.silent + ? null + : await this.bushPunishDM('banned', options.reason, options.duration ?? 0, modlog.id); + dmSuccessEvent = dmSuccess ?? undefined; + + // ban + const banSuccess = await this.ban({ + reason: `${moderator.tag} | ${options.reason ?? 'No reason provided.'}`, + deleteMessageDays: options.deleteDays + }).catch(() => false); + if (!banSuccess) return banResponse.ACTION_ERROR; + // add punishment entry so they can be unbanned later const punishmentEntrySuccess = await Moderation.createPunishmentEntry({ type: 'ban', @@ -595,20 +615,21 @@ export class BushGuildMember extends GuildMember { }); if (!punishmentEntrySuccess) return blockResponse.PUNISHMENT_ENTRY_ADD_ERROR; - if (!options.silent) { - // dm user - const dmSuccess = await this.send({ - content: `You have been blocked from <#${channel.id}> in **${this.guild.name}** ${ - options.duration !== null && options.duration !== undefined - ? options.duration - ? `for ${util.humanizeDuration(options.duration)} ` - : 'permanently ' - : '' - }for **${options.reason?.trim() ? options.reason?.trim() : 'No reason provided'}**.` - }).catch(() => false); - dmSuccessEvent = !!dmSuccess; - if (!dmSuccess) return blockResponse.DM_ERROR; - } + // dm user + const dmSuccess = options.silent + ? null + : await Moderation.punishDM({ + punishment: 'blocked', + reason: options.reason ?? undefined, + duration: options.duration ?? 0, + modlog: modlog.id, + guild: this.guild, + user: this, + sendFooter: true, + channel: channel.id + }); + dmSuccessEvent = !!dmSuccess; + if (!dmSuccess) return blockResponse.DM_ERROR; return blockResponse.SUCCESS; })(); @@ -683,16 +704,22 @@ export class BushGuildMember extends GuildMember { }); if (!punishmentEntrySuccess) return unblockResponse.ACTION_ERROR; - if (!options.silent) { - // dm user - const dmSuccess = await this.send({ - content: `You have been unblocked from <#${channel.id}> in **${this.guild.name}** for **${ - options.reason?.trim() ? options.reason?.trim() : 'No reason provided' - }**.` - }).catch(() => false); - dmSuccessEvent = !!dmSuccess; - if (!dmSuccess) return unblockResponse.DM_ERROR; - } + // dm user + const dmSuccess = options.silent + ? null + : await Moderation.punishDM({ + punishment: 'unblocked', + reason: options.reason ?? undefined, + guild: this.guild, + user: this, + sendFooter: false, + channel: channel.id + }); + dmSuccessEvent = !!dmSuccess; + if (!dmSuccess) return blockResponse.DM_ERROR; + + dmSuccessEvent = !!dmSuccess; + if (!dmSuccess) return unblockResponse.DM_ERROR; return unblockResponse.SUCCESS; })(); @@ -723,7 +750,7 @@ export class BushGuildMember extends GuildMember { // checks if (!this.guild.me!.permissions.has(PermissionFlagsBits.ModerateMembers)) return timeoutResponse.MISSING_PERMISSIONS; - const twentyEightDays = client.consts.timeUnits.days.value * 28; + const twentyEightDays = Time.Day * 28; if (options.duration > twentyEightDays) return timeoutResponse.INVALID_DURATION; let caseID: string | undefined = undefined; @@ -756,7 +783,7 @@ export class BushGuildMember extends GuildMember { if (!options.silent) { // dm user - const dmSuccess = await this.bushPunishDM('timed out', options.reason, options.duration); + const dmSuccess = await this.bushPunishDM('timedout', options.reason, options.duration, modlog.id); dmSuccessEvent = dmSuccess; if (!dmSuccess) return timeoutResponse.DM_ERROR; } @@ -815,7 +842,7 @@ export class BushGuildMember extends GuildMember { if (!options.silent) { // dm user - const dmSuccess = await this.bushPunishDM('untimedout', options.reason); + const dmSuccess = await this.bushPunishDM('untimedout', options.reason, undefined, '', false); dmSuccessEvent = dmSuccess; if (!dmSuccess) return removeTimeoutResponse.DM_ERROR; } diff --git a/src/lib/models/instance/Guild.ts b/src/lib/models/instance/Guild.ts index b41eb9e..b81562c 100644 --- a/src/lib/models/instance/Guild.ts +++ b/src/lib/models/instance/Guild.ts @@ -385,6 +385,11 @@ export const guildFeaturesObj = asGuildFeature({ name: 'Log Manual Punishments', description: "Adds manual punishment to the user's modlogs and the logging channels.", default: true + }, + punishmentAppeals: { + name: 'Punishment Appeals', + description: 'Allow users to appeal their punishments and send the appeal to the configured channel.', + default: false } }); @@ -404,6 +409,10 @@ export const guildLogsObj = { error: { description: 'Logs errors that occur with the bot.', configurable: true + }, + appeals: { + description: 'Where punishment appeals are sent.', + configurable: true } }; diff --git a/src/lib/utils/BushConstants.ts b/src/lib/utils/BushConstants.ts index 4327fec..93de100 100644 --- a/src/lib/utils/BushConstants.ts +++ b/src/lib/utils/BushConstants.ts @@ -317,7 +317,6 @@ export class BushConstants { }, userFlags: { - None: '', Staff: '<:discordEmployee:848742947826434079>', Partner: '<:partneredServerOwner:848743051593777152>', Hypesquad: '<:hypeSquadEvents:848743108283072553>', @@ -331,7 +330,8 @@ export class BushConstants { VerifiedBot: '<:verifiedbot_rebrand1:938928232667947028><:verifiedbot_rebrand2:938928355707879475>', VerifiedDeveloper: '<:earlyVerifiedBotDeveloper:848741079875846174>', CertifiedModerator: '<:discordCertifiedModerator:877224285901582366>', - BotHTTPInteractions: 'BotHTTPInteractions' + BotHTTPInteractions: 'BotHTTPInteractions', + Spammer: 'Spammer' }, status: { diff --git a/src/listeners/client/interactionCreate.ts b/src/listeners/client/interactionCreate.ts index 636bb6e..40315a0 100644 --- a/src/listeners/client/interactionCreate.ts +++ b/src/listeners/client/interactionCreate.ts @@ -20,7 +20,7 @@ export default class InteractionCreateListener extends BushListener { return; } else if (interaction.isButton()) { const id = interaction.customId; - if (id.startsWith('paginate_') || id.startsWith('command_') || id.startsWith('confirmationPrompt_')) return; + if (['paginate_', 'command_', 'confirmationPrompt_', 'appeal'].some((s) => id.startsWith(s))) return; else if (id.startsWith('automod;')) void AutoMod.handleInteraction(interaction as BushButtonInteraction); else return await interaction.reply({ content: 'Buttons go brrr', ephemeral: true }); } else if (interaction.isSelectMenu()) { diff --git a/src/listeners/track-manual-punishments/modlogSyncBan.ts b/src/listeners/track-manual-punishments/modlogSyncBan.ts index 9886530..b68de7c 100644 --- a/src/listeners/track-manual-punishments/modlogSyncBan.ts +++ b/src/listeners/track-manual-punishments/modlogSyncBan.ts @@ -1,5 +1,5 @@ import { BushListener, BushUser, Moderation, ModLogType, Time, type BushClientEvents } from '#lib'; -import { AuditLogEvent } from 'discord-api-types'; +import { AuditLogEvent } from 'discord-api-types/v9'; import { Embed, PermissionFlagsBits } from 'discord.js'; export default class ModlogSyncBanListener extends BushListener { diff --git a/src/listeners/track-manual-punishments/modlogSyncKick.ts b/src/listeners/track-manual-punishments/modlogSyncKick.ts index b7762db..6ff9bd6 100644 --- a/src/listeners/track-manual-punishments/modlogSyncKick.ts +++ b/src/listeners/track-manual-punishments/modlogSyncKick.ts @@ -1,5 +1,5 @@ import { BushListener, BushUser, Moderation, ModLogType, Time, type BushClientEvents } from '#lib'; -import { AuditLogEvent } from 'discord-api-types'; +import { AuditLogEvent } from 'discord-api-types/v9'; import { Embed, PermissionFlagsBits } from 'discord.js'; export default class ModlogSyncKickListener extends BushListener { diff --git a/src/listeners/track-manual-punishments/modlogSyncTimeout.ts b/src/listeners/track-manual-punishments/modlogSyncTimeout.ts index 21dde1a..993002e 100644 --- a/src/listeners/track-manual-punishments/modlogSyncTimeout.ts +++ b/src/listeners/track-manual-punishments/modlogSyncTimeout.ts @@ -1,5 +1,5 @@ import { BushListener, BushUser, Moderation, ModLogType, Time, type BushClientEvents } from '#lib'; -import { AuditLogEvent } from 'discord-api-types'; +import { AuditLogEvent } from 'discord-api-types/v9'; import { Embed, PermissionFlagsBits } from 'discord.js'; export default class ModlogSyncTimeoutListener extends BushListener { diff --git a/src/listeners/track-manual-punishments/modlogSyncUnban.ts b/src/listeners/track-manual-punishments/modlogSyncUnban.ts index a268ef4..366d072 100644 --- a/src/listeners/track-manual-punishments/modlogSyncUnban.ts +++ b/src/listeners/track-manual-punishments/modlogSyncUnban.ts @@ -1,5 +1,5 @@ import { BushListener, BushUser, Moderation, ModLogType, Time, type BushClientEvents } from '#lib'; -import { AuditLogEvent } from 'discord-api-types'; +import { AuditLogEvent } from 'discord-api-types/v9'; import { Embed, PermissionFlagsBits } from 'discord.js'; export default class ModlogSyncUnbanListener extends BushListener { diff --git a/src/listeners/ws/INTERACTION_CREATE.ts b/src/listeners/ws/INTERACTION_CREATE.ts index a7c8a45..fd79529 100644 --- a/src/listeners/ws/INTERACTION_CREATE.ts +++ b/src/listeners/ws/INTERACTION_CREATE.ts @@ -1,6 +1,29 @@ -import { BushListener } from '#lib'; -// eslint-disable-next-line node/file-extension-in-import -import { GatewayDispatchEvents, Routes } from 'discord-api-types/v9'; +import { BushListener, BushUser, Moderation, ModLog, PunishmentTypePresent } from '#lib'; +import assert from 'assert'; +import { TextInputStyle } from 'discord-api-types-next/v9'; +import { + APIBaseInteraction, + APIEmbed, + APIInteraction as DiscordAPITypesAPIInteraction, + APIInteractionResponseChannelMessageWithSource, + APIInteractionResponseDeferredMessageUpdate, + APIInteractionResponseUpdateMessage, + APIModalInteractionResponse, + APIModalSubmission, + ButtonStyle, + ComponentType, + GatewayDispatchEvents, + InteractionResponseType, + InteractionType, + Routes +} from 'discord-api-types/v9'; +import { ActionRow, ButtonComponent, Embed, Snowflake } from 'discord.js'; + +// todo: use from discord-api-types once updated +export type APIModalSubmitInteraction = APIBaseInteraction<InteractionType.ModalSubmit, APIModalSubmission> & + Required<Pick<APIBaseInteraction<InteractionType.ModalSubmit, APIModalSubmission>, 'data'>>; + +export type APIInteraction = DiscordAPITypesAPIInteraction | APIModalSubmitInteraction; export default class WsInteractionCreateListener extends BushListener { public constructor() { @@ -11,15 +34,218 @@ export default class WsInteractionCreateListener extends BushListener { }); } - public override async exec(interaction: any) { - // console.dir(interaction); + public override async exec(interaction: APIInteraction) { + console.dir(interaction); - if (interaction.type === 5) { - await this.client.rest.post(Routes.interactionCallback(interaction.id, interaction.token), { - body: { - type: 6 - } + const respond = ( + options: + | APIModalInteractionResponse + | APIInteractionResponseDeferredMessageUpdate + | APIInteractionResponseChannelMessageWithSource + | APIInteractionResponseUpdateMessage + ) => { + return this.client.rest.post( + Routes.interactionCallback(interaction.id, interaction.token), + options ? { body: options } : undefined + ); + }; + + const deferredMessageUpdate = () => { + return respond({ + type: InteractionResponseType.DeferredMessageUpdate }); + }; + + if (interaction.type === InteractionType.MessageComponent) { + if (interaction.data.custom_id.startsWith('appeal;')) { + const [, punishment, guildId, userId, modlogCase] = interaction.data.custom_id.split(';') as [ + 'appeal', + PunishmentTypePresent, + Snowflake, + Snowflake, + string + ]; + + const guild = client.guilds.resolve(guildId); + if (!guild) + return respond({ + type: InteractionResponseType.ChannelMessageWithSource, + data: { + content: `${util.emojis.error} I am no longer in that server.` + } + }); + + const modal: APIModalInteractionResponse = { + type: InteractionResponseType.Modal, + data: { + custom_id: `appeal_submit;${punishment};${guildId};${userId};${modlogCase}`, + title: `${util.capitalize(punishment)} Appeal`, + components: [ + { + type: ComponentType.ActionRow, + components: [ + { + type: ComponentType.TextInput, + style: TextInputStyle.Paragraph, + max_length: 1024, + required: true, + label: `Why were you ${Moderation.punishmentToPastTense(punishment)}?`, + placeholder: `Why do you think you received a ${punishment}?`, + custom_id: 'appeal_reason' + } + ] + }, + { + type: ComponentType.ActionRow, + components: [ + { + type: ComponentType.TextInput, + style: TextInputStyle.Paragraph, + max_length: 1024, + required: true, + label: 'Do you believe it was fair?', + placeholder: `Why do you think you received a ${punishment}?`, + custom_id: 'appeal_fair' + } + ] + }, + { + type: ComponentType.ActionRow, + components: [ + { + type: ComponentType.TextInput, + style: TextInputStyle.Paragraph, + max_length: 1024, + required: true, + label: `Why should your ${punishment} be removed?`, + placeholder: `Why should your ${punishment} be removed?`, + custom_id: 'appeal_why' + } + ] + } + ] + } + }; + + return respond(modal); + } else if ( + interaction.data.custom_id.startsWith('appeal_accept;') || + interaction.data.custom_id.startsWith('appeal_deny;') + ) { + const [action, punishment, guildId, userId, modlogCase] = interaction.data.custom_id.split(';') as [ + 'appeal_accept' | 'appeal_deny', + PunishmentTypePresent, + Snowflake, + Snowflake, + string + ]; + + if (action === 'appeal_deny') { + await client.users + .send(userId, `Your ${punishment} appeal has been denied in ${client.guilds.resolve(guildId)!}.`) + .catch(() => {}); + + void respond({ + type: InteractionResponseType.ChannelMessageWithSource, + data: { + components: [ + { + type: 1, + components: [ + { + type: ComponentType.Button, + style: ButtonStyle.Danger, + label: 'Close', + custom_id: 'appeal_denied' + } + ] + } + ] + } + }); + } + } + } else if (interaction.type === InteractionType.ModalSubmit) { + if (interaction.data.custom_id.startsWith('appeal_submit;')) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [, punishment, guildId, userId, modlogCase] = interaction.data.custom_id.split(';') as [ + 'appeal_submit', + PunishmentTypePresent, + Snowflake, + Snowflake, + string + ]; + + const guild = client.guilds.resolve(guildId); + if (!guild) + return respond({ + type: InteractionResponseType.ChannelMessageWithSource, + data: { + content: `${util.emojis.error} I am no longer in that server.` + } + }); + + const channel = await guild.getLogChannel('appeals'); + if (!channel) + return respond({ + type: InteractionResponseType.ChannelMessageWithSource, + data: { + content: `${util.emojis.error} ${guild.name} has misconfigured their appeals channel.` + } + }); + + assert(interaction.user); + const user = new BushUser(client, interaction.user as any); + assert(user); + + const caseId = await ModLog.findOne({ where: { user: userId, guild: guildId, id: modlogCase } }); + + const embed = new Embed() + .setTitle(`${util.capitalize(punishment)} Appeal`) + .setColor(util.colors.newBlurple) + .setTimestamp() + .setFooter({ text: `CaseID: ${modlogCase}` }) + .setAuthor({ name: user.tag, iconURL: user.displayAvatarURL() }) + .addField({ + name: `Why were you ${Moderation.punishmentToPastTense(punishment)}?`, + value: interaction.data.components![0].components[0]!.value.substring(0, 1024) + }) + .addField({ + name: 'Do you believe it was fair?', + value: interaction.data.components![1].components[0]!.value.substring(0, 1024) + }) + .addField({ + name: `Why should your ${punishment} be removed?`, + value: interaction.data.components![2].components[0]!.value.substring(0, 1024) + }) + .toJSON() as APIEmbed; + + const components = [ + new ActionRow({ + type: 1, + components: [ + // @ts-expect-error: outdated @discord.js/builders + new ButtonComponent({ + type: 2, + custom_id: `appeal_accept;${punishment};${guildId};${userId};${modlogCase}`, + label: 'Accept', + style: 3 /* Success */ + }).toJSON(), + // @ts-expect-error: outdated @discord.js/builders + new ButtonComponent({ + type: 2, + custom_id: `appeal_deny;${punishment};${guildId};${userId};${modlogCase}`, + label: 'Deny', + style: 4 /* Danger */ + }).toJSON() + ] + }) + ]; + + await channel.send({ embeds: [embed], components }); + } else { + return deferredMessageUpdate(); + } } } } |