diff options
author | IRONM00N <64110067+IRONM00N@users.noreply.github.com> | 2022-10-03 22:57:40 -0400 |
---|---|---|
committer | IRONM00N <64110067+IRONM00N@users.noreply.github.com> | 2022-10-03 22:57:40 -0400 |
commit | 612ed820a0600ec11ed642005377cd7f5a8a8b77 (patch) | |
tree | 6bca4e7268fd0063ff53cf64fa44df62a23dba50 /src/commands | |
parent | ed98ff7e2679f362f2657e77a6cf8dd3ce9b3d43 (diff) | |
download | tanzanite-612ed820a0600ec11ed642005377cd7f5a8a8b77.tar.gz tanzanite-612ed820a0600ec11ed642005377cd7f5a8a8b77.tar.bz2 tanzanite-612ed820a0600ec11ed642005377cd7f5a8a8b77.zip |
wip
Diffstat (limited to 'src/commands')
41 files changed, 409 insertions, 304 deletions
diff --git a/src/commands/config/config.ts b/src/commands/config/config.ts index adc41d8..4d38c54 100644 --- a/src/commands/config/config.ts +++ b/src/commands/config/config.ts @@ -13,8 +13,8 @@ import { type GuildSettingType, type SlashMessage } from '#lib'; +import { ExtSub, type ArgumentGeneratorReturn, type SlashOption } from '@notenoughupdates/discord-akairo'; import assert from 'assert/strict'; -import { type ArgumentGeneratorReturn, type SlashOption } from 'discord-akairo'; import { ActionRowBuilder, ApplicationCommandOptionType, @@ -32,10 +32,9 @@ import { User, type Message, type MessageComponentInteraction, - type MessageOptions + type MessageCreateOptions } from 'discord.js'; -import _ from 'lodash'; -const { camelCase, snakeCase } = _; +import { camelCase, snakeCase } from 'lodash-es'; export const arrayActions = ['view' as const, 'add' as const, 'remove' as const, 'clear' as const]; export type ArrayActions = typeof arrayActions[number]; @@ -79,7 +78,7 @@ export default class ConfigCommand extends BotCommand { description: `Manage the server's ${loweredName}`, type: ApplicationCommandOptionType.SubcommandGroup, options: isArray - ? [ + ? ([ { name: 'view', description: `View the server's ${loweredName}.`, @@ -118,8 +117,8 @@ export default class ConfigCommand extends BotCommand { description: `Remove all values from a server's ${loweredName}.`, type: ApplicationCommandOptionType.Subcommand } - ] - : [ + ] as ExtSub[]) + : ([ { name: 'view', description: `View the server's ${loweredName}.`, @@ -144,7 +143,7 @@ export default class ConfigCommand extends BotCommand { description: `Delete the server's ${loweredName}.`, type: ApplicationCommandOptionType.Subcommand } - ] + ] as ExtSub[]) }; }), channel: 'guild', @@ -309,7 +308,7 @@ export default class ConfigCommand extends BotCommand { public async generateMessageOptions( message: CommandMessage | SlashMessage, setting?: undefined | keyof typeof guildSettingsObj - ): Promise<MessageOptions & InteractionUpdateOptions> { + ): Promise<MessageCreateOptions & InteractionUpdateOptions> { assert(message.inGuild()); const settingsEmbed = new EmbedBuilder().setColor(colors.default); diff --git a/src/commands/config/disable.ts b/src/commands/config/disable.ts index 6dd94a6..776ecf0 100644 --- a/src/commands/config/disable.ts +++ b/src/commands/config/disable.ts @@ -10,9 +10,9 @@ import { } from '#lib'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, AutocompleteInteraction } from 'discord.js'; -import { default as Fuse } from 'fuse.js'; -assert(Fuse); +// todo: remove this bullshit once typescript gets its shit together +const Fuse = (await import('fuse.js')).default as unknown as typeof import('fuse.js').default; export default class DisableCommand extends BotCommand { private static blacklistedCommands = ['eval', 'disable']; diff --git a/src/commands/config/log.ts b/src/commands/config/log.ts index 0c74ce7..6d0f594 100644 --- a/src/commands/config/log.ts +++ b/src/commands/config/log.ts @@ -8,8 +8,8 @@ import { type GuildLogType, type SlashMessage } from '#lib'; +import { ArgumentGeneratorReturn } from '@notenoughupdates/discord-akairo'; import assert from 'assert/strict'; -import { ArgumentGeneratorReturn } from 'discord-akairo'; import { ApplicationCommandOptionType, ChannelType } from 'discord.js'; export default class LogCommand extends BotCommand { @@ -38,10 +38,10 @@ export default class LogCommand extends BotCommand { slashType: ApplicationCommandOptionType.Channel, channelTypes: [ ChannelType.GuildText, - ChannelType.GuildNews, - ChannelType.GuildNewsThread, - ChannelType.GuildPublicThread, - ChannelType.GuildPrivateThread + ChannelType.GuildAnnouncement, + ChannelType.AnnouncementThread, + ChannelType.PublicThread, + ChannelType.PrivateThread ], only: 'slash' } diff --git a/src/commands/dev/eval.ts b/src/commands/dev/eval.ts index 83168e0..5fe21c0 100644 --- a/src/commands/dev/eval.ts +++ b/src/commands/dev/eval.ts @@ -283,7 +283,7 @@ export default class EvalCommand extends BotCommand { if (!err && proto) embed.addFields({ name: ':gear: Proto', value: proto }); if (!silent || message.util.isSlashMessage(message)) { - await message.util.reply({ content: null, embeds: [embed] }); + await message.util.reply({ content: '', embeds: [embed] }); } else { const success = await message.author.send({ embeds: [embed] }).catch(() => false); if (!deleteMsg) await message.react(success ? emojis.successFull : emojis.errorFull).catch(() => {}); diff --git a/src/commands/dev/superUser.ts b/src/commands/dev/superUser.ts index fc7fcbf..54332d6 100644 --- a/src/commands/dev/superUser.ts +++ b/src/commands/dev/superUser.ts @@ -1,5 +1,5 @@ import { BotCommand, emojis, format, type ArgType, type CommandMessage } from '#lib'; -import { type ArgumentGeneratorReturn, type ArgumentTypeCasterReturn } from 'discord-akairo'; +import { type ArgumentGeneratorReturn, type ArgumentTypeCasterReturn } from '@notenoughupdates/discord-akairo'; export default class SuperUserCommand extends BotCommand { public constructor() { diff --git a/src/commands/dev/test.ts b/src/commands/dev/test.ts index e1f3b73..994b76f 100644 --- a/src/commands/dev/test.ts +++ b/src/commands/dev/test.ts @@ -1,13 +1,14 @@ -import { BotCommand, ButtonPaginator, colors, emojis, OptArgType, Shared, type CommandMessage } from '#lib'; +import { BotCommand, ButtonPaginator, chunk, colors, emojis, OptArgType, Shared, type CommandMessage } from '#lib'; import { ActionRowBuilder, + APIEmbed, ButtonBuilder, ButtonStyle, + Collection, EmbedBuilder, - GatewayDispatchEvents, + Message, Routes, - type ApplicationCommand, - type Collection + type ApplicationCommand } from 'discord.js'; import badLinksSecretArray from '../../../lib/badlinks-secret.js'; import badLinksArray from '../../../lib/badlinks.js'; @@ -52,15 +53,38 @@ export default class TestCommand extends BotCommand { return await message.util.reply(responses[Math.floor(Math.random() * responses.length)]); } + console.dir(args); + if (args.feature) { if (['button', 'buttons'].includes(args.feature?.toLowerCase())) { const buttonRow = new ActionRowBuilder<ButtonBuilder>().addComponents( - new ButtonBuilder({ style: ButtonStyle.Primary, customId: 'primaryButton', label: 'Primary' }), - new ButtonBuilder({ style: ButtonStyle.Secondary, customId: 'secondaryButton', label: 'Secondary' }), - new ButtonBuilder({ style: ButtonStyle.Success, customId: 'successButton', label: 'Success' }), - new ButtonBuilder({ style: ButtonStyle.Danger, customId: 'dangerButton', label: 'Danger' }), - new ButtonBuilder({ style: ButtonStyle.Link, label: 'Link', url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' }) + new ButtonBuilder({ + style: ButtonStyle.Primary, + customId: 'test;button;primary', + label: 'Primary' + }), + new ButtonBuilder({ + style: ButtonStyle.Secondary, + customId: 'test;button;secondary', + label: 'Secondary' + }), + new ButtonBuilder({ + style: ButtonStyle.Success, + customId: 'test;button;success', + label: 'Success' + }), + new ButtonBuilder({ + style: ButtonStyle.Danger, + customId: 'test;button;danger', + label: 'Danger' + }), + new ButtonBuilder({ + style: ButtonStyle.Link, + label: 'Link', + url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' + }) ); + return await message.util.reply({ content: 'buttons', components: [buttonRow] }); } else if (['embed', 'button embed'].includes(args.feature?.toLowerCase())) { const embed = new EmbedBuilder() @@ -80,18 +104,23 @@ export default class TestCommand extends BotCommand { const buttonRow = new ActionRowBuilder<ButtonBuilder>().addComponents( new ButtonBuilder({ style: ButtonStyle.Link, label: 'Link', url: 'https://google.com/' }) ); + return await message.util.reply({ content: 'Test', embeds: [embed], components: [buttonRow] }); } else if (['lots of buttons'].includes(args.feature?.toLowerCase())) { const buttonRows: ActionRowBuilder<ButtonBuilder>[] = []; + for (let a = 1; a <= 5; a++) { const row = new ActionRowBuilder<ButtonBuilder>(); + for (let b = 1; b <= 5; b++) { - const id = (a + 5 * (b - 1)).toString(); + const id = `test;lots;${a + 5 * (b - 1)}`; const button = new ButtonBuilder({ style: ButtonStyle.Primary, customId: id, label: id }); row.addComponents(button); } + buttonRows.push(row); } + return await message.util.reply({ content: 'buttons', components: buttonRows }); } else if (['paginate'].includes(args.feature?.toLowerCase())) { const embeds = []; @@ -142,13 +171,16 @@ export default class TestCommand extends BotCommand { return message.util.reply(`${emojis.error} no`); } else if (['sync automod'].includes(args.feature?.toLowerCase())) { const row = (await Shared.findByPk(0))!; + row.badLinks = badLinksArray; row.badLinksSecret = badLinksSecretArray; row.badWords = badWords; + await row.save(); + return await message.util.reply(`${emojis.success} Synced automod.`); } else if (['modal'].includes(args.feature?.toLowerCase())) { - const m = await message.util.reply({ + return await message.util.reply({ content: 'Click for modal', components: [ new ActionRowBuilder<ButtonBuilder>().addComponents( @@ -156,63 +188,57 @@ export default class TestCommand extends BotCommand { ) ] }); + } else if (args.feature.includes('backlog experiments')) { + this.client.logger.debug('backlog experiments'); + + if (message.channelId !== '1019830755658055691') { + return await message.util.reply(`${emojis.error} This only works in <#1019830755658055691>.`); + } - // eslint-disable-next-line @typescript-eslint/no-misused-promises - this.client.ws.on(GatewayDispatchEvents.InteractionCreate, async (i: any) => { - if (i?.data?.custom_id !== 'test;modal' || i?.data?.component_type !== 2) return; - if (i?.message?.id !== m.id) return; - - const text = { type: 4, style: 1, min_length: 1, max_length: 4000, required: true }; - - await this.client.rest.post(Routes.interactionCallback(i.id, i.token), { - body: { - type: 9, - data: { - custom_id: 'test;login', - title: 'Login (real)', - components: [ - { - type: 1, - components: [ - { - ...text, - custom_id: 'test;login;email', - label: 'Email', - placeholder: 'Email' - } - ] - }, - { - type: 1, - components: [ - { - ...text, - custom_id: 'test;login;password', - label: 'Password', - placeholder: 'Password' - } - ] - }, - { - type: 1, - components: [ - { - ...text, - custom_id: 'test;login;2fa', - label: 'Enter Discord Auth Code', - min_length: 6, - max_length: 6, - placeholder: '6-digit authentication code' - } - ] - } - ] - } - } + let messages = new Collection<string, Message>(); + let lastID: string | undefined; + + // eslint-disable-next-line no-constant-condition + while (true) { + const fetchedMessages = await message.channel.messages.fetch({ + limit: 100, + ...(lastID && { before: lastID }) }); - }); - return; + if (fetchedMessages.size === 0) { + break; + } + + messages = messages.concat(fetchedMessages); + lastID = fetchedMessages.lastKey(); + + this.client.logger.debug(messages.size); + this.client.logger.debug(lastID); + } + + const embeds = messages + .sort((a, b) => a.createdTimestamp - b.createdTimestamp) + .filter((m) => m.embeds.length > 0 && (m.embeds[0].title?.includes('Guild Experiment') ?? false)) + .map( + (m): APIEmbed => ({ + ...m.embeds[0]!.toJSON(), + timestamp: new Date(m.createdTimestamp).toISOString() + }) + ); + + const chunked = chunk(embeds, 10); + + let i = 0; + for (const chunk of chunked) { + this.client.logger.debug(i); + this.client.logger.debug(chunk, 1); + await this.client.rest.post(Routes.channelMessages('795356494261911553'), { + body: { embeds: chunk } + }); + i++; + } + + return await message.util.reply(`${emojis.success} Done.`); } } return await message.util.reply(responses[Math.floor(Math.random() * responses.length)]); diff --git a/src/commands/fun/minesweeper.ts b/src/commands/fun/minesweeper.ts index 85945c7..b0528ac 100644 --- a/src/commands/fun/minesweeper.ts +++ b/src/commands/fun/minesweeper.ts @@ -1,8 +1,6 @@ import { BotCommand, emojis, OptArgType, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; -import { Minesweeper } from '@notenoughupdates/discord.js-minesweeper'; -import assert from 'assert/strict'; +import { Minesweeper } from '@tanzanite/discord.js-minesweeper'; import { ApplicationCommandOptionType } from 'discord.js'; -assert(Minesweeper); export default class MinesweeperCommand extends BotCommand { public constructor() { diff --git a/src/commands/info/guildInfo.ts b/src/commands/info/guildInfo.ts index e364a89..acd5b86 100644 --- a/src/commands/info/guildInfo.ts +++ b/src/commands/info/guildInfo.ts @@ -11,6 +11,7 @@ import { type OptArgType, type SlashMessage } from '#lib'; +import { embedField } from '#lib/common/tags.js'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, @@ -26,7 +27,6 @@ import { PermissionFlagsBits, type BaseGuildVoiceChannel, type GuildPreview, - type Snowflake, type Vanity } from 'discord.js'; @@ -66,9 +66,13 @@ export default class GuildInfoCommand extends BotCommand { let guild: ArgType<'guild' | 'snowflake'> | GuildPreview = args.guild ?? message.guild!; if (typeof guild === 'string') { - const preview = await this.client.fetchGuildPreview(`${args.guild}` as Snowflake).catch(() => undefined); - if (preview) guild = preview; - else return await message.util.reply(`${emojis.error} That guild is not discoverable or does not exist.`); + const preview = await this.client.fetchGuildPreview(`${args.guild}`).catch(() => {}); + + if (preview) { + guild = preview; + } else { + return await message.util.reply(`${emojis.error} That guild is not discoverable or does not exist.`); + } } assert(guild); @@ -96,10 +100,13 @@ export default class GuildInfoCommand extends BotCommand { const otherEmojis = mappings.otherEmojis; const verifiedGuilds = Object.values(mappings.guilds); - if (verifiedGuilds.includes(guild.id as typeof verifiedGuilds[number])) description.push(otherEmojis.BushVerified); - if (guild instanceof Guild) { - if (guild.premiumTier !== GuildPremiumTier.None) description.push(otherEmojis[`BoostTier${guild.premiumTier}`]); + if (verifiedGuilds.includes(guild.id as typeof verifiedGuilds[number])) { + description.push(otherEmojis.BushVerified); + } + + if (guild instanceof Guild && guild.premiumTier !== GuildPremiumTier.None) { + description.push(otherEmojis[`BoostTier${guild.premiumTier}`]); } const features = mappings.features; @@ -138,52 +145,65 @@ export default class GuildInfoCommand extends BotCommand { ) ] as RTCRegion[]; + const members = guild.memberCount; + const online = guild.approximatePresenceCount ?? 0; + const offline = members - online; + guildAbout.push( - `**Owner:** ${escapeMarkdown(guild.members.cache.get(guild.ownerId)?.user.tag ?? '¯\\_(ツ)_/¯')}`, - `**Created** ${timestampAndDelta(guild.createdAt, 'd')}`, - `**Members:** ${guild.memberCount.toLocaleString() ?? 0} (${emojis.onlineCircle} ${ - guild.approximatePresenceCount?.toLocaleString() ?? 0 - }, ${emojis.offlineCircle} ${(guild.memberCount - (guild.approximatePresenceCount ?? 0)).toLocaleString() ?? 0})`, - `**Regions:** ${guildRegions.map((region) => mappings.regions[region] || region).join(', ')}` + embedField` + Owner ${escapeMarkdown(guild.members.cache.get(guild.ownerId)?.user.tag ?? '¯\\_(ツ)_/¯')} + Created ${timestampAndDelta(guild.createdAt, 'd')} + Members ${members} (${emojis.onlineCircle} ${online}, ${emojis.offlineCircle} ${offline}) + Regions ${guildRegions.map((region) => mappings.regions[region] || region).join(', ')} + Boosts ${guild.premiumSubscriptionCount && `Level ${guild.premiumTier} with ${guild.premiumSubscriptionCount} boosts`}` ); - if (guild.premiumSubscriptionCount) - guildAbout.push(`**Boosts:** Level ${guild.premiumTier} with ${guild.premiumSubscriptionCount ?? 0} boosts`); + if (guild.members.me?.permissions.has(PermissionFlagsBits.ManageGuild) && guild.vanityURLCode) { const vanityInfo: Vanity = await guild.fetchVanityData(); - guildAbout.push(`**Vanity URL:** discord.gg/${vanityInfo.code}`, `**Vanity Uses:** ${vanityInfo.uses?.toLocaleString()}`); + guildAbout.push( + embedField` + Vanity URL ${`discord.gg/${vanityInfo.code}`} + Vanity Uses ${vanityInfo.uses}` + ); } - if (guild.icon) guildAbout.push(`**Icon:** [link](${guild.iconURL({ size: 4096, extension: 'png' })})`); - if (guild.banner) guildAbout.push(`**Banner:** [link](${guild.bannerURL({ size: 4096, extension: 'png' })})`); - if (guild.splash) guildAbout.push(`**Splash:** [link](${guild.splashURL({ size: 4096, extension: 'png' })})`); + guildAbout.push( + embedField` + Icon ${guild.icon && `[link](${guild.iconURL({ size: 4096, extension: 'png' })})`} + Banner ${guild.banner && `[link](${guild.bannerURL({ size: 4096, extension: 'png' })})`} + Splash ${guild.splash && `[link](${guild.splashURL({ size: 4096, extension: 'png' })})`}` + ); } else { + const members = guild.approximateMemberCount; + const online = guild.approximatePresenceCount; + const offline = members - online; + guildAbout.push( - `**Members:** ${guild.approximateMemberCount?.toLocaleString() ?? 0} (${emojis.onlineCircle} ${ - guild.approximatePresenceCount?.toLocaleString() ?? 0 - }, ${emojis.offlineCircle} ${( - (guild.approximateMemberCount ?? 0) - (guild.approximatePresenceCount ?? 0) - ).toLocaleString()})`, - `**Emojis:** ${(guild as GuildPreview).emojis.size?.toLocaleString() ?? 0}`, - `**Stickers:** ${(guild as GuildPreview).stickers.size}` + embedField` + Members ${members} (${emojis.onlineCircle} ${online}, ${emojis.offlineCircle} ${offline}) + Emojis ${guild.emojis.size} + Stickers ${guild.stickers.size}` ); } - embed.addFields({ name: '» About', value: guildAbout.join('\n') }); + embed.addFields({ + name: '» About', + // filter out anything that is undefined + value: guildAbout.filter((v) => v !== undefined).join('\n') + }); } private generateStatsField(embed: EmbedBuilder, guild: Guild | GuildPreview) { if (!(guild instanceof Guild)) return; - const guildStats: string[] = []; - const channelTypes = ( [ ['Text', [ChannelType.GuildText]], ['Voice', [ChannelType.GuildVoice]], - ['News', [ChannelType.GuildNews]], + ['News', [ChannelType.GuildAnnouncement]], ['Stage', [ChannelType.GuildStageVoice]], ['Category', [ChannelType.GuildCategory]], - ['Thread', [ChannelType.GuildNewsThread, ChannelType.GuildPrivateThread, ChannelType.GuildPublicThread]] + ['Thread', [ChannelType.AnnouncementThread, ChannelType.PrivateThread, ChannelType.PublicThread]] ] as const ).map( (type) => @@ -205,30 +225,25 @@ export default class GuildInfoCommand extends BotCommand { [GuildPremiumTier.None]: 0 } as const; - guildStats.push( - `**Channels:** ${guild.channels.cache.size.toLocaleString()} / 500 (${channelTypes.join(', ')})`, - // subtract 1 for @everyone role - `**Roles:** ${((guild.roles.cache.size ?? 0) - 1).toLocaleString()} / 250`, - `**Emojis:** ${guild.emojis.cache.size?.toLocaleString() ?? 0} / ${EmojiTierMap[guild.premiumTier]}`, - `**Stickers:** ${guild.stickers.cache.size?.toLocaleString() ?? 0} / ${StickerTierMap[guild.premiumTier]}` - ); + const guildStats = embedField` + Channels ${guild.channels.cache.size} / 500 (${channelTypes.join(', ')}) + Roles ${guild.roles.cache.size - 1 /* account for @everyone role */} / 250 + Emojis ${guild.emojis.cache.size} / ${EmojiTierMap[guild.premiumTier]} + Stickers ${guild.stickers.cache.size} / ${StickerTierMap[guild.premiumTier]}`; - embed.addFields({ name: '» Stats', value: guildStats.join('\n') }); + embed.addFields({ name: '» Stats', value: guildStats }); } private generateSecurityField(embed: EmbedBuilder, guild: Guild | GuildPreview) { if (!(guild instanceof Guild)) return; - const guildSecurity: string[] = []; - - guildSecurity.push( - `**Verification Level:** ${MappedGuildVerificationLevel[guild.verificationLevel]}`, - `**Explicit Content Filter:** ${MappedGuildExplicitContentFilter[guild.explicitContentFilter]}`, - `**Default Message Notifications:** ${MappedGuildDefaultMessageNotifications[guild.defaultMessageNotifications]}`, - `**2FA Required:** ${guild.mfaLevel === GuildMFALevel.Elevated ? 'True' : 'False'}` - ); + const guildSecurity = embedField` + Verification Level ${MappedGuildVerificationLevel[guild.verificationLevel]} + Explicit Content Filter ${MappedGuildExplicitContentFilter[guild.explicitContentFilter]} + Default Message Notifications ${MappedGuildDefaultMessageNotifications[guild.defaultMessageNotifications]} + 2FA Required ${guild.mfaLevel === GuildMFALevel.Elevated ? 'True' : 'False'}`; - embed.addFields({ name: '» Security', value: guildSecurity.join('\n') }); + embed.addFields({ name: '» Security', value: guildSecurity }); } } diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 1680b75..565fc25 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -20,9 +20,11 @@ import { ButtonStyle, EmbedBuilder } from 'discord.js'; -import { default as Fuse } from 'fuse.js'; import packageDotJSON from '../../../package.json' assert { type: 'json' }; +// todo: remove this bullshit once typescript gets its shit together +const Fuse = (await import('fuse.js')).default as unknown as typeof import('fuse.js').default; + assert(Fuse); assert(packageDotJSON); diff --git a/src/commands/info/inviteInfo.ts b/src/commands/info/inviteInfo.ts index bf66a4c..123063d 100644 --- a/src/commands/info/inviteInfo.ts +++ b/src/commands/info/inviteInfo.ts @@ -1,4 +1,5 @@ import { Arg, ArgType, BotCommand, colors, type CommandMessage, type SlashMessage } from '#lib'; +import { embedField } from '#lib/common/tags.js'; import { ApplicationCommandOptionType, EmbedBuilder, Invite } from 'discord.js'; export default class InviteInfoCommand extends BotCommand { @@ -38,8 +39,10 @@ export default class InviteInfoCommand extends BotCommand { } private generateAboutField(embed: EmbedBuilder, invite: Invite) { - const about = [`**code:** ${invite.code}`, `**channel:** ${invite.channel!.name}`]; + const about = embedField` + Code ${invite.code} + Channel ${invite.channel!.name}`; - embed.addFields({ name: '» About', value: about.join('\n') }); + embed.addFields({ name: '» About', value: about }); } } diff --git a/src/commands/info/ping.ts b/src/commands/info/ping.ts index ad58cc0..66cdf01 100644 --- a/src/commands/info/ping.ts +++ b/src/commands/info/ping.ts @@ -43,7 +43,7 @@ export default class PingCommand extends BotCommand { .setColor(colors.default) .setTimestamp(); return message.util.reply({ - content: null, + content: '', embeds: [embed] }); } diff --git a/src/commands/info/snowflake.ts b/src/commands/info/snowflake.ts index ba93611..1d3533e 100644 --- a/src/commands/info/snowflake.ts +++ b/src/commands/info/snowflake.ts @@ -1,5 +1,5 @@ import { BotCommand, colors, timestamp, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; -import { stripIndent } from '#tags'; +import { embedField } from '#tags'; import { ApplicationCommandOptionType, ChannelType, @@ -50,7 +50,7 @@ export default class SnowflakeCommand extends BotCommand { snowflakeEmbed.setTitle(`:snowflake: DM with ${escapeMarkdown(channel.recipient?.tag ?? '¯\\_(ツ)_/¯')} \`[Channel]\``); } else if ( channel.type === ChannelType.GuildCategory || - channel.type === ChannelType.GuildNews || + channel.type === ChannelType.GuildAnnouncement || channel.type === ChannelType.GuildText || channel.type === ChannelType.GuildVoice || channel.type === ChannelType.GuildStageVoice || @@ -68,10 +68,10 @@ export default class SnowflakeCommand extends BotCommand { // Guild if (this.client.guilds.cache.has(snowflake)) { const guild = this.client.guilds.cache.get(snowflake)!; - const guildInfo = stripIndent` - **Name:** ${escapeMarkdown(guild.name)} - **Owner:** ${escapeMarkdown(this.client.users.cache.get(guild.ownerId)?.tag ?? '¯\\_(ツ)_/¯')} (${guild.ownerId}) - **Members:** ${guild.memberCount?.toLocaleString()}`; + const guildInfo = embedField` + Name ${escapeMarkdown(guild.name)} + Owner ${escapeMarkdown(this.client.users.cache.get(guild.ownerId)?.tag ?? '¯\\_(ツ)_/¯')} (${guild.ownerId}) + Members ${guild.memberCount?.toLocaleString()}`; if (guild.icon) snowflakeEmbed.setThumbnail(guild.iconURL({ size: 2048 })!); snowflakeEmbed.addFields({ name: '» Server Info', value: guildInfo }); snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(guild.name)} \`[Server]\``); @@ -81,8 +81,8 @@ export default class SnowflakeCommand extends BotCommand { const fetchedUser = await this.client.users.fetch(`${snowflake}`).catch(() => undefined); if (this.client.users.cache.has(snowflake) || fetchedUser) { const user = (this.client.users.cache.get(snowflake) ?? fetchedUser)!; - const userInfo = stripIndent` - **Name:** <@${user.id}> (${escapeMarkdown(user.tag)})`; + const userInfo = embedField` + Name ${`<@${user.id}> (${escapeMarkdown(user.tag)})`}`; if (user.avatar) snowflakeEmbed.setThumbnail(user.avatarURL({ size: 2048 })!); snowflakeEmbed.addFields({ name: '» User Info', value: userInfo }); snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(user.tag)} \`[User]\``); @@ -91,9 +91,9 @@ export default class SnowflakeCommand extends BotCommand { // Emoji if (this.client.emojis.cache.has(snowflake)) { const emoji = this.client.emojis.cache.get(snowflake)!; - const emojiInfo = stripIndent` - **Name:** ${escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} - **Animated:** ${emoji.animated}`; + const emojiInfo = embedField` + Name ${escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} + Animated ${emoji.animated}`; if (emoji.url) snowflakeEmbed.setThumbnail(emoji.url); snowflakeEmbed.addFields({ name: '» Emoji Info', value: emojiInfo }); snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} \`[Emoji]\``); @@ -102,13 +102,13 @@ export default class SnowflakeCommand extends BotCommand { // Role if (message.guild && message.guild.roles.cache.has(snowflake)) { const role = message.guild.roles.cache.get(snowflake)!; - const roleInfo = stripIndent` - **Name:** <@&${role.id}> (${escapeMarkdown(role.name)}) - **Members:** ${role.members.size} - **Hoisted:** ${role.hoist} - **Managed:** ${role.managed} - **Position:** ${role.position} - **Hex Color:** ${role.hexColor}`; + const roleInfo = embedField` + Name ${`<@&${role.id}> (${escapeMarkdown(role.name)})`} + Members ${role.members.size} + Hoisted ${role.hoist} + Managed ${role.managed} + Position ${role.position} + Hex Color ${role.hexColor}`; if (role.color) snowflakeEmbed.setColor(role.color); snowflakeEmbed.addFields({ name: '» Role Info', value: roleInfo }); snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(role.name)} \`[Role]\``); @@ -116,12 +116,12 @@ export default class SnowflakeCommand extends BotCommand { // SnowflakeInfo const deconstructedSnowflake: DeconstructedSnowflake = SnowflakeUtil.deconstruct(snowflake); - const snowflakeInfo = stripIndent` - **Timestamp:** ${deconstructedSnowflake.timestamp} - **Created:** ${timestamp(new Date(Number(deconstructedSnowflake.timestamp)))} - **Worker ID:** ${deconstructedSnowflake.workerId} - **Process ID:** ${deconstructedSnowflake.processId} - **Increment:** ${deconstructedSnowflake.increment}`; + const snowflakeInfo = embedField` + Timestamp ${deconstructedSnowflake.timestamp} + Created ${timestamp(new Date(Number(deconstructedSnowflake.timestamp)))} + Worker ID ${deconstructedSnowflake.workerId} + Process ID ${deconstructedSnowflake.processId} + Increment ${deconstructedSnowflake.increment}`; snowflakeEmbed.addFields({ name: '» Snowflake Info', value: snowflakeInfo }); return await message.util.reply({ embeds: [snowflakeEmbed] }); diff --git a/src/commands/info/userInfo.ts b/src/commands/info/userInfo.ts index 25621fa..22088fe 100644 --- a/src/commands/info/userInfo.ts +++ b/src/commands/info/userInfo.ts @@ -13,6 +13,7 @@ import { type OptArgType, type SlashMessage } from '#lib'; +import { embedField } from '#lib/common/tags.js'; import { ActivityType, ApplicationCommandOptionType, @@ -20,7 +21,6 @@ import { EmbedBuilder, escapeMarkdown, PermissionFlagsBits, - TeamMemberMembershipState, UserFlags, type APIApplication, type ApplicationFlagsString, @@ -128,62 +128,69 @@ export default class UserInfoCommand extends BotCommand { await this.generateBotField(userEmbed, user); - if (emojis) + if (emojis) { userEmbed.setDescription( `\u200B${emojis.filter((e) => e).join(' ')}${ userEmbed.data.description?.length ? `\n\n${userEmbed.data.description}` : '' }` ); // zero width space + } + return userEmbed; } public static async generateGeneralInfoField(embed: EmbedBuilder, user: User, title = '» General Information') { - // General Info - const generalInfo = [ - `**Mention:** <@${user.id}>`, - `**ID:** ${user.id}`, - `**Created:** ${timestampAndDelta(user.createdAt, 'd')}` - ]; - if (user.accentColor !== null) generalInfo.push(`**Accent Color:** ${user.hexAccentColor}`); - if (user.banner) generalInfo.push(`**Banner:** [link](${user.bannerURL({ extension: 'png', size: 4096 })})`); - - const pronouns = await Promise.race([user.client.utils.getPronounsOf(user), sleep(2 * Time.Second)]); // cut off request after 2 seconds - - if (pronouns && typeof pronouns === 'string' && pronouns !== 'Unspecified') generalInfo.push(`**Pronouns:** ${pronouns}`); - - embed.addFields({ name: title, value: generalInfo.join('\n') }); + const pronouns = await Promise.race([ + user.client.utils.getPronounsOf(user), + // cut off request after 2 seconds + sleep(2 * Time.Second) + ]); + + const generalInfo = embedField` + Mention ${`<@${user.id}>`} + ID ${user.id} + Created ${timestampAndDelta(user.createdAt, 'd')} + Accent Color ${user.hexAccentColor} + Banner ${user.banner && `[link](${user.bannerURL({ extension: 'png', size: 4096 })})`} + Pronouns ${typeof pronouns === 'string' && pronouns !== 'Unspecified' && pronouns}`; + + embed.addFields({ name: title, value: generalInfo }); } public static generateServerInfoField(embed: EmbedBuilder, member?: GuildMember | undefined, title = '» Server Information') { if (!member) return; - // Server User Info - const serverUserInfo = []; - if (member.joinedTimestamp) - serverUserInfo.push( - `**${member.guild!.ownerId == member.user.id ? 'Created Server' : 'Joined'}:** ${timestampAndDelta( - member.joinedAt!, - 'd' - )}` - ); - if (member.premiumSince) serverUserInfo.push(`**Booster Since:** ${timestampAndDelta(member.premiumSince, 'd')}`); - if (member.displayHexColor) serverUserInfo.push(`**Display Color:** ${member.displayHexColor}`); - if (member.user.id == mappings.users['IRONM00N'] && member.guild?.id == mappings.guilds["Moulberry's Bush"]) - serverUserInfo.push(`**General Deletions:** 1⅓`); - if ( - ([mappings.users['nopo'], mappings.users['Bestower']] as const).includes(member.user.id) && - member.guild.id == mappings.guilds["Moulberry's Bush"] - ) - serverUserInfo.push(`**General Deletions:** ⅓`); - if (member?.nickname) serverUserInfo.push(`**Nickname:** ${escapeMarkdown(member?.nickname)}`); - if (serverUserInfo.length) embed.addFields({ name: title, value: serverUserInfo.join('\n') }); + const isGuildOwner = member.guild.ownerId === member.id; + + const deletions = (() => { + if (member.guild.id !== mappings.guilds["Moulberry's Bush"]) return null; + + switch (member.id) { + case mappings.users['IRONM00N']: + return '1⅓'; + case mappings.users['nopo']: + case mappings.users['Bestower']: + return '⅓'; + default: + return null; + } + })(); + + const serverUserInfo = embedField` + Created Server ${member.joinedAt && isGuildOwner && timestampAndDelta(member.joinedAt!, 'd')} + Joined ${member.joinedAt && !isGuildOwner && timestampAndDelta(member.joinedAt!, 'd')} + Booster Since ${member.premiumSince && timestampAndDelta(member.premiumSince, 'd')} + Display Color ${member.displayHexColor} + #general Deletions ${deletions} + Nickname ${member.nickname && escapeMarkdown(member.nickname)}`; + + if (serverUserInfo.length) embed.addFields({ name: title, value: serverUserInfo }); } public static generatePresenceField(embed: EmbedBuilder, member?: GuildMember | undefined, title = '» Presence') { if (!member || !member.presence) return; if (!member.presence.status && !member.presence.clientStatus && !member.presence.activities) return; - // User Presence Info let customStatus = ''; const activitiesNames: string[] = []; if (member.presence.activities) { @@ -231,7 +238,7 @@ export default class UserInfoCommand extends BotCommand { const joined = roles.join(', '); embed.addFields({ name: `» Role${roles.length - 1 ? 's' : ''} [${roles.length}]`, - value: joined.length > 1024 ? 'Too Many Roles to Display' + '...' : joined + value: joined.length > 1024 ? 'Too Many Roles to Display...' : joined }); } @@ -242,7 +249,6 @@ export default class UserInfoCommand extends BotCommand { ) { if (!member) return; - // Important Perms const perms = this.getImportantPermissions(member); if (perms.length) embed.addFields({ name: title, value: perms.join(' ') }); @@ -282,27 +288,13 @@ export default class UserInfoCommand extends BotCommand { return emojis.cross; }; - const botInfo = [ - `**Publicity:** ${applicationInfo.bot_public ? 'Public' : 'Private'}`, - `**Requires Code Grant:** ${applicationInfo.bot_require_code_grant ? emojis.check : emojis.cross}`, - `**Server Members Intent:** ${intent('GatewayGuildMembers', 'GatewayGuildMembersLimited')}`, - `**Presence Intent:** ${intent('GatewayPresence', 'GatewayPresenceLimited')}`, - `**Message Content Intent:** ${intent('GatewayMessageContent', 'GatewayMessageContentLimited')}` - ]; - - if (applicationInfo.owner || applicationInfo.team) { - const teamMembers = applicationInfo.owner - ? [applicationInfo.owner] - : applicationInfo - .team!.members.filter((tm) => tm.membership_state === TeamMemberMembershipState.Accepted) - .map((tm) => tm.user); - botInfo.push( - `**Developer${teamMembers.length > 1 ? 's' : ''}:** ${teamMembers - .map((m) => `${m.username}#${m.discriminator}`) - .join(', ')}` - ); - } + const botInfo = embedField` + Publicity ${applicationInfo.bot_public ? 'Public' : 'Private'} + Code Grant ${applicationInfo.bot_require_code_grant ? 'Required' : 'Not Required'} + Server Members Intent ${intent('GatewayGuildMembers', 'GatewayGuildMembersLimited')} + Presence Intent ${intent('GatewayPresence', 'GatewayPresenceLimited')} + Message Content Intent ${intent('GatewayMessageContent', 'GatewayMessageContentLimited')}`; - if (botInfo.length) embed.addFields({ name: title, value: botInfo.join('\n') }); + embed.addFields({ name: title, value: botInfo }); } } diff --git a/src/commands/leveling/level.ts b/src/commands/leveling/level.ts index 869140d..bf4ca9b 100644 --- a/src/commands/leveling/level.ts +++ b/src/commands/leveling/level.ts @@ -9,11 +9,11 @@ import { type SlashMessage } from '#lib'; import canvas from '@napi-rs/canvas'; -import { SimplifyNumber } from '@notenoughupdates/simplify-number'; +import { simplifyNumber } from '@tanzanite/simplify-number'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, AttachmentBuilder, Guild, PermissionFlagsBits, User } from 'discord.js'; + assert(canvas); -assert(SimplifyNumber); export default class LevelCommand extends BotCommand { public constructor() { @@ -119,9 +119,9 @@ export default class LevelCommand extends BotCommand { // Draw level data text ctx.fillStyle = white; - const xpTxt = `${SimplifyNumber(currentLevelXpProgress)}/${SimplifyNumber(xpForNextLevel)}`; + const xpTxt = `${simplifyNumber(currentLevelXpProgress)}/${simplifyNumber(xpForNextLevel)}`; - const rankTxt = SimplifyNumber(rank.indexOf(rank.find((x) => x.user === user.id)!) + 1); + const rankTxt = simplifyNumber(rank.indexOf(rank.find((x) => x.user === user.id)!) + 1); ctx.fillText(`Level: ${userLevel} XP: ${xpTxt} Rank: ${rankTxt}`, AVATAR_SIZE + 70, AVATAR_SIZE - 20); // Return image in buffer form diff --git a/src/commands/leveling/setLevel.ts b/src/commands/leveling/setLevel.ts index 6f6f69e..3a995a2 100644 --- a/src/commands/leveling/setLevel.ts +++ b/src/commands/leveling/setLevel.ts @@ -1,4 +1,5 @@ -import { AllowedMentions, BotCommand, emojis, format, Level, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { AllowedMentions, BotCommand, emojis, Level, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { commas } from '#lib/common/tags.js'; import assert from 'assert/strict'; import { ApplicationCommandOptionType } from 'discord.js'; @@ -42,20 +43,27 @@ export default class SetLevelCommand extends BotCommand { assert(message.inGuild()); assert(user.id); - if (isNaN(level) || !Number.isInteger(level)) + if (isNaN(level) || !Number.isInteger(level)) { return await message.util.reply(`${emojis.error} Provide a valid number to set the user's level to.`); - if (level > 6553 || level < 0) - return await message.util.reply(`${emojis.error} You cannot set a level higher than **6,553**.`); + } + + if (level > Level.MAX_LEVEL || level < 0) { + return await message.util.reply(commas`${emojis.error} You cannot set a level higher than **${Level.MAX_LEVEL}**.`); + } const [levelEntry] = await Level.findOrBuild({ - where: { user: user.id, guild: message.guild.id }, - defaults: { user: user.id, guild: message.guild.id, xp: 0 } + where: { + user: user.id, + guild: message.guild.id + } }); - await levelEntry.update({ xp: Level.convertLevelToXp(level), user: user.id, guild: message.guild.id }); + + const xp = Level.convertLevelToXp(level); + + await levelEntry.update({ xp, user: user.id, guild: message.guild.id }); + return await message.util.send({ - content: `Successfully set level of <@${user.id}> to ${format.input(level.toLocaleString())} (${format.input( - levelEntry.xp.toLocaleString() - )} XP)`, + content: commas`Successfully set level of <@${user.id}> to **${level}** (**${xp}** xp)`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/leveling/setXp.ts b/src/commands/leveling/setXp.ts index 8c3b86f..270ad68 100644 --- a/src/commands/leveling/setXp.ts +++ b/src/commands/leveling/setXp.ts @@ -1,4 +1,6 @@ -import { AllowedMentions, BotCommand, emojis, format, Level, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { AllowedMentions, BotCommand, emojis, Level, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { commas } from '#lib/common/tags.js'; +import { input } from '#lib/utils/Format.js'; import assert from 'assert/strict'; import { ApplicationCommandOptionType } from 'discord.js'; @@ -44,22 +46,36 @@ export default class SetXpCommand extends BotCommand { assert(user.id); if (isNaN(xp)) return await message.util.reply(`${emojis.error} Provide a valid number.`); - if (xp > 2147483647 || xp < 0) + + if (xp > Level.MAX_XP || xp < 0) { return await message.util.reply( - `${emojis.error} Provide an positive integer under **2,147,483,647** to set the user's xp to.` + commas`${emojis.error} Provide an positive integer under **${Level.MAX_XP}** to set the user's xp to.` ); + } const [levelEntry] = await Level.findOrBuild({ - where: { user: user.id, guild: message.guild.id }, - defaults: { user: user.id, guild: message.guild.id } + where: { + user: user.id, + guild: message.guild.id + } }); - await levelEntry.update({ xp: xp, user: user.id, guild: message.guild.id }); + const res = await levelEntry + .update({ xp: xp, user: user.id, guild: message.guild.id }) + .catch((e) => (e instanceof Error ? e : null)); + + xp = levelEntry.xp; + const level = Level.convertXpToLevel(xp); + + if (res instanceof Error || res == null) { + return await message.util.reply({ + content: commas`Unable to set <@${user.id}>'s xp to **${xp}** with error ${input(res?.message ?? '¯\\_(ツ)_/¯')}.`, + allowedMentions: AllowedMentions.none() + }); + } return await message.util.send({ - content: `Successfully set <@${user.id}>'s xp to ${format.input(levelEntry.xp.toLocaleString())} (level ${format.input( - Level.convertXpToLevel(levelEntry.xp).toLocaleString() - )}).`, + content: commas`${emojis.success} Successfully set <@${user.id}>'s xp to **${xp}** (level **${level}**).`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/moderation/ban.ts b/src/commands/moderation/ban.ts index aee8805..ae77cde 100644 --- a/src/commands/moderation/ban.ts +++ b/src/commands/moderation/ban.ts @@ -96,7 +96,9 @@ export default class BanCommand extends BotCommand { if (!user) return message.util.reply(`${emojis.error} Invalid user.`); const useForce = args.force && message.author.isOwner(); - const canModerateResponse = member ? await Moderation.permissionCheck(message.member, member, 'ban', true, useForce) : true; + const canModerateResponse = member + ? await Moderation.permissionCheck(message.member, member, Moderation.Action.Ban, true, useForce) + : true; if (canModerateResponse !== true) { return await message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/block.ts b/src/commands/moderation/block.ts index a5ad31d..da1dec8 100644 --- a/src/commands/moderation/block.ts +++ b/src/commands/moderation/block.ts @@ -83,7 +83,7 @@ export default class BlockCommand extends BotCommand { return await message.util.reply(`${emojis.error} The user you selected is not in the server or is not a valid user.`); const useForce = args.force && message.author.isOwner(); - const canModerateResponse = await Moderation.permissionCheck(message.member, member, 'block', true, useForce); + const canModerateResponse = await Moderation.permissionCheck(message.member, member, Moderation.Action.Block, true, useForce); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/evidence.ts b/src/commands/moderation/evidence.ts index 9a5e70f..b7c020a 100644 --- a/src/commands/moderation/evidence.ts +++ b/src/commands/moderation/evidence.ts @@ -10,8 +10,8 @@ import { type CommandMessage, type SlashMessage } from '#lib'; +import { Argument, ArgumentGeneratorReturn } from '@notenoughupdates/discord-akairo'; import assert from 'assert/strict'; -import { Argument, ArgumentGeneratorReturn } from 'discord-akairo'; import { ApplicationCommandOptionType, type Message } from 'discord.js'; export default class EvidenceCommand extends BotCommand { diff --git a/src/commands/moderation/kick.ts b/src/commands/moderation/kick.ts index 82ddce4..d757e91 100644 --- a/src/commands/moderation/kick.ts +++ b/src/commands/moderation/kick.ts @@ -70,7 +70,7 @@ export default class KickCommand extends BotCommand { if (!member) return await message.util.reply(`${emojis.error} The user you selected is not in the server or is not a valid user.`); const useForce = force && message.author.isOwner(); - const canModerateResponse = await Moderation.permissionCheck(message.member, member, 'kick', true, useForce); + const canModerateResponse = await Moderation.permissionCheck(message.member, member, Moderation.Action.Kick, true, useForce); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/modlog.ts b/src/commands/moderation/modlog.ts index dcab9ef..649e44f 100644 --- a/src/commands/moderation/modlog.ts +++ b/src/commands/moderation/modlog.ts @@ -12,12 +12,11 @@ import { type CommandMessage, type SlashMessage } from '#lib'; +import { embedField } from '#lib/common/tags.js'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, escapeMarkdown, User } from 'discord.js'; export default class ModlogCommand extends BotCommand { - public static separator = '\n━━━━━━━━━━━━━━━\n'; - public constructor() { super('modlog', { aliases: ['modlog', 'modlogs'], @@ -62,44 +61,63 @@ export default class ModlogCommand extends BotCommand { const logs = await ModLog.findAll({ where: { guild: message.guild.id, - user: foundUser.id + user: foundUser.id, + pseudo: false }, order: [['createdAt', 'ASC']] }); - const niceLogs = logs - .filter((log) => !log.pseudo && !(!hidden && log.hidden)) - .map((log) => ModlogCommand.generateModlogInfo(log, false, false)); - if (niceLogs.length < 1) return message.util.reply(`${emojis.error} **${foundUser.tag}** does not have any modlogs.`); + const niceLogs = logs.filter((log) => !log.hidden || hidden).map((log) => generateModlogInfo(log, false, false)); + + if (niceLogs.length < 1) { + return message.util.reply(`${emojis.error} **${foundUser.tag}** does not have any modlogs.`); + } + const chunked: string[][] = chunk(niceLogs, 4); const embedPages = chunked.map((chunk) => ({ title: `${foundUser.tag}'s Modlogs`, - description: chunk.join(ModlogCommand.separator), + description: chunk.join(modlogSeparator), color: colors.default })); return await ButtonPaginator.send(message, embedPages, undefined, true); } else if (search) { const entry = await ModLog.findByPk(search as string); - if (!entry || entry.pseudo || (entry.hidden && !hidden)) + + if (!entry || entry.pseudo || (entry.hidden && !hidden)) { return message.util.send(`${emojis.error} That modlog does not exist.`); - if (entry.guild !== message.guild.id) return message.util.reply(`${emojis.error} This modlog is from another server.`); + } + + if (entry.guild !== message.guild.id) { + return message.util.reply(`${emojis.error} This modlog is from another server.`); + } + const embed = { title: `Case ${entry.id}`, - description: ModlogCommand.generateModlogInfo(entry, true, false), + description: generateModlogInfo(entry, true, false), color: colors.default }; return await ButtonPaginator.send(message, [embed]); } } +} - public static generateModlogInfo(log: ModLog, showUser: boolean, userFacing: boolean): string { - const trim = (str: string): string => (str.endsWith('\n') ? str.substring(0, str.length - 1).trim() : str.trim()); - const modLog = [`**Case ID:** ${escapeMarkdown(log.id)}`, `**Type:** ${log.type.toLowerCase()}`]; - if (showUser) modLog.push(`**User:** <@!${log.user}>`); - if (!userFacing) modLog.push(`**Moderator:** <@!${log.moderator}>`); - if (log.duration) modLog.push(`**Duration:** ${humanizeDuration(log.duration)}`); - modLog.push(`**Reason:** ${trim(log.reason ?? 'No Reason Specified.')}`); - modLog.push(`**Date:** ${timestamp(log.createdAt)}`); - if (log.evidence && !userFacing) modLog.push(`**Evidence:** ${trim(log.evidence)}`); - return modLog.join(`\n`); +export const modlogSeparator = '\n━━━━━━━━━━━━━━━\n'; + +const trim = (str: string): string => { + if (str.endsWith('\n')) { + return str.substring(0, str.length - 1).trim(); + } else { + return str.trim(); } +}; + +export function generateModlogInfo(log: ModLog, showUser: boolean, userFacing: boolean): string { + return embedField` + Case ID ${escapeMarkdown(log.id)} + Type ${log.type.toLowerCase()} + User ${showUser && `<@!${log.user}>`} + Moderator ${!userFacing && `<@!${log.moderator}>`} + Duration ${log.duration && humanizeDuration(log.duration)} + Reason ${trim(log.reason ?? 'No Reason Specified.')} + Date ${timestamp(log.createdAt)} + Evidence ${log.evidence && !userFacing && trim(log.evidence)}`; } diff --git a/src/commands/moderation/mute.ts b/src/commands/moderation/mute.ts index 9ffaf8d..a64dc99 100644 --- a/src/commands/moderation/mute.ts +++ b/src/commands/moderation/mute.ts @@ -78,7 +78,7 @@ export default class MuteCommand extends BotCommand { return await message.util.reply(`${emojis.error} The user you selected is not in the server or is not a valid user.`); const useForce = args.force && message.author.isOwner(); - const canModerateResponse = await Moderation.permissionCheck(message.member, member, 'mute', true, useForce); + const canModerateResponse = await Moderation.permissionCheck(message.member, member, Moderation.Action.Mute, true, useForce); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/myLogs.ts b/src/commands/moderation/myLogs.ts index 8faca8c..e3f5f10 100644 --- a/src/commands/moderation/myLogs.ts +++ b/src/commands/moderation/myLogs.ts @@ -12,7 +12,7 @@ import { import { ApplicationCommandOptionType } from 'discord.js'; import { input, sanitizeInputForDiscord } from '../../../lib/utils/Format.js'; -import ModlogCommand from './modlog.js'; +import { generateModlogInfo, modlogSeparator } from './modlog.js'; export default class MyLogsCommand extends BotCommand { public constructor() { super('myLogs', { @@ -50,14 +50,14 @@ export default class MyLogsCommand extends BotCommand { const logs = await ModLog.findAll({ where: { guild: guild.id, - user: message.author.id + user: message.author.id, + pseudo: false, + hidden: false }, order: [['createdAt', 'ASC']] }); - const niceLogs = logs - .filter((log) => !log.pseudo && !log.hidden) - .map((log) => ModlogCommand.generateModlogInfo(log, false, true)); + const niceLogs = logs.map((log) => generateModlogInfo(log, false, true)); if (niceLogs.length < 1) return message.util.reply(`${emojis.error} You don't have any modlogs in ${input(guild.name)}.`); @@ -65,7 +65,7 @@ export default class MyLogsCommand extends BotCommand { const embedPages = chunked.map((chunk) => ({ title: `Your Modlogs in ${sanitizeInputForDiscord(guild.name)}`, - description: chunk.join(ModlogCommand.separator), + description: chunk.join(modlogSeparator), color: colors.default })); diff --git a/src/commands/moderation/role.ts b/src/commands/moderation/role.ts index 565f214..a664aa4 100644 --- a/src/commands/moderation/role.ts +++ b/src/commands/moderation/role.ts @@ -12,8 +12,8 @@ import { type OptArgType, type SlashMessage } from '#lib'; +import { type ArgumentGeneratorReturn } from '@notenoughupdates/discord-akairo'; import assert from 'assert/strict'; -import { type ArgumentGeneratorReturn } from 'discord-akairo'; import { ApplicationCommandOptionType, PermissionFlagsBits, type Snowflake } from 'discord.js'; export default class RoleCommand extends BotCommand { diff --git a/src/commands/moderation/slowmode.ts b/src/commands/moderation/slowmode.ts index 82d0264..1256d1f 100644 --- a/src/commands/moderation/slowmode.ts +++ b/src/commands/moderation/slowmode.ts @@ -1,6 +1,6 @@ import { Arg, BotCommand, emojis, format, humanizeDuration, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { Argument } from '@notenoughupdates/discord-akairo'; import assert from 'assert/strict'; -import { Argument } from 'discord-akairo'; import { ApplicationCommandOptionType, ChannelType } from 'discord.js'; export default class SlowmodeCommand extends BotCommand { @@ -30,7 +30,7 @@ export default class SlowmodeCommand extends BotCommand { retry: '{error} Choose a valid channel.', optional: true, slashType: ApplicationCommandOptionType.Channel, - channelTypes: [ChannelType.GuildText, ChannelType.GuildPrivateThread, ChannelType.GuildPublicThread] + channelTypes: [ChannelType.GuildText, ChannelType.PrivateThread, ChannelType.PublicThread] } ], slash: true, @@ -55,7 +55,7 @@ export default class SlowmodeCommand extends BotCommand { if ( args.channel.type !== ChannelType.GuildText && - args.channel.type !== ChannelType.GuildNews && + args.channel.type !== ChannelType.GuildAnnouncement && args.channel.type !== ChannelType.GuildVoice && !args.channel.isThread() ) diff --git a/src/commands/moderation/timeout.ts b/src/commands/moderation/timeout.ts index 7bb02f7..db6ab56 100644 --- a/src/commands/moderation/timeout.ts +++ b/src/commands/moderation/timeout.ts @@ -73,7 +73,13 @@ export default class TimeoutCommand extends BotCommand { return await message.util.reply(`${emojis.error} The user you selected is not in the server or is not a valid user.`); const useForce = args.force && message.author.isOwner(); - const canModerateResponse = await Moderation.permissionCheck(message.member, member, 'timeout', true, useForce); + const canModerateResponse = await Moderation.permissionCheck( + message.member, + member, + Moderation.Action.Timeout, + true, + useForce + ); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/unblock.ts b/src/commands/moderation/unblock.ts index 4838392..4fdfc28 100644 --- a/src/commands/moderation/unblock.ts +++ b/src/commands/moderation/unblock.ts @@ -75,7 +75,13 @@ export default class UnblockCommand extends BotCommand { return await message.util.reply(`${emojis.error} The user you selected is not in the server or is not a valid user.`); const useForce = args.force && message.author.isOwner(); - const canModerateResponse = await Moderation.permissionCheck(message.member, member, 'unblock', true, useForce); + const canModerateResponse = await Moderation.permissionCheck( + message.member, + member, + Moderation.Action.Unblock, + true, + useForce + ); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/unmute.ts b/src/commands/moderation/unmute.ts index a4d348d..c8fccc8 100644 --- a/src/commands/moderation/unmute.ts +++ b/src/commands/moderation/unmute.ts @@ -66,7 +66,13 @@ export default class UnmuteCommand extends BotCommand { const member = message.guild.members.cache.get(user.id)!; const useForce = force && message.author.isOwner(); - const canModerateResponse = await Moderation.permissionCheck(message.member, member, 'unmute', true, useForce); + const canModerateResponse = await Moderation.permissionCheck( + message.member, + member, + Moderation.Action.Unmute, + true, + useForce + ); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/untimeout.ts b/src/commands/moderation/untimeout.ts index 3775c65..64364e5 100644 --- a/src/commands/moderation/untimeout.ts +++ b/src/commands/moderation/untimeout.ts @@ -73,7 +73,13 @@ export default class UntimeoutCommand extends BotCommand { if (!member.isCommunicationDisabled()) return message.util.reply(`${emojis.error} That user is not timed out.`); const useForce = args.force && message.author.isOwner(); - const canModerateResponse = await Moderation.permissionCheck(message.member, member, 'timeout', true, useForce); + const canModerateResponse = await Moderation.permissionCheck( + message.member, + member, + Moderation.Action.Untimeout, + true, + useForce + ); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/warn.ts b/src/commands/moderation/warn.ts index 4bc7f13..a7ed814 100644 --- a/src/commands/moderation/warn.ts +++ b/src/commands/moderation/warn.ts @@ -69,7 +69,7 @@ export default class WarnCommand extends BotCommand { const member = message.guild.members.cache.get(user.id); if (!member) return message.util.reply(`${emojis.error} I cannot warn users that are not in the server.`); const useForce = force && message.author.isOwner(); - const canModerateResponse = await Moderation.permissionCheck(message.member, member, 'warn', true, useForce); + const canModerateResponse = await Moderation.permissionCheck(message.member, member, Moderation.Action.Warn, true, useForce); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moulberry-bush/capes.ts b/src/commands/moulberry-bush/capes.ts index b292f24..a67cf46 100644 --- a/src/commands/moulberry-bush/capes.ts +++ b/src/commands/moulberry-bush/capes.ts @@ -13,7 +13,9 @@ import { } from '#lib'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, type APIEmbed, type AutocompleteInteraction } from 'discord.js'; -import { default as Fuse } from 'fuse.js'; + +// todo: remove this bullshit once typescript gets its shit together +const Fuse = (await import('fuse.js')).default as unknown as typeof import('fuse.js').default; assert(Fuse); @@ -85,7 +87,7 @@ export default class CapesCommand extends BotCommand { } } else { const embeds: APIEmbed[] = capes.map(this.makeEmbed); - await ButtonPaginator.send(message, embeds, null); + await ButtonPaginator.send(message, embeds, ''); } } diff --git a/src/commands/tickets/ticket-!.ts b/src/commands/tickets/ticket-!.ts index c5c59f2..b98ec1f 100644 --- a/src/commands/tickets/ticket-!.ts +++ b/src/commands/tickets/ticket-!.ts @@ -1,5 +1,5 @@ import { BotCommand, deepWriteable, type SlashMessage } from '#lib'; -import { Flag, type ArgumentGeneratorReturn, type SlashOption } from 'discord-akairo'; +import { Flag, type ArgumentGeneratorReturn, type SlashOption } from '@notenoughupdates/discord-akairo'; import { ApplicationCommandOptionType } from 'discord.js'; export const ticketSubcommands = deepWriteable({ diff --git a/src/commands/utilities/activity.ts b/src/commands/utilities/activity.ts index 89ca53e..3f17d0a 100644 --- a/src/commands/utilities/activity.ts +++ b/src/commands/utilities/activity.ts @@ -7,7 +7,7 @@ import { type CommandMessage, type SlashMessage } from '#lib'; -import { type ArgumentGeneratorReturn, type ArgumentTypeCaster } from 'discord-akairo'; +import { type ArgumentGeneratorReturn, type ArgumentTypeCaster } from '@notenoughupdates/discord-akairo'; import { ApplicationCommandOptionType, ChannelType, type DiscordAPIError, type Snowflake } from 'discord.js'; const activityMap = { diff --git a/src/commands/utilities/highlight-!.ts b/src/commands/utilities/highlight-!.ts index 7716887..0e2db33 100644 --- a/src/commands/utilities/highlight-!.ts +++ b/src/commands/utilities/highlight-!.ts @@ -1,5 +1,5 @@ import { BotCommand, deepWriteable, Highlight, HighlightWord, type SlashMessage } from '#lib'; -import { Flag, type ArgumentGeneratorReturn, type SlashOption } from 'discord-akairo'; +import { Flag, type ArgumentGeneratorReturn, type SlashOption } from '@notenoughupdates/discord-akairo'; import { ApplicationCommandOptionType, Constants, type AutocompleteInteraction, type CacheType } from 'discord.js'; export const highlightSubcommands = deepWriteable({ diff --git a/src/commands/utilities/highlight-block.ts b/src/commands/utilities/highlight-block.ts index b16852e..d1dec1e 100644 --- a/src/commands/utilities/highlight-block.ts +++ b/src/commands/utilities/highlight-block.ts @@ -1,6 +1,6 @@ import { AllowedMentions, BotCommand, emojis, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { Argument, ArgumentGeneratorReturn } from '@notenoughupdates/discord-akairo'; import assert from 'assert/strict'; -import { Argument, ArgumentGeneratorReturn } from 'discord-akairo'; import { BaseChannel, GuildMember, User } from 'discord.js'; import { HighlightBlockResult } from '../../../lib/common/HighlightManager.js'; import { highlightSubcommands } from './highlight-!.js'; diff --git a/src/commands/utilities/highlight-matches.ts b/src/commands/utilities/highlight-matches.ts index d54fd4a..0665b37 100644 --- a/src/commands/utilities/highlight-matches.ts +++ b/src/commands/utilities/highlight-matches.ts @@ -1,6 +1,6 @@ import { BotCommand, ButtonPaginator, chunk, colors, emojis, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { type ArgumentGeneratorReturn } from '@notenoughupdates/discord-akairo'; import assert from 'assert/strict'; -import { type ArgumentGeneratorReturn } from 'discord-akairo'; import { type APIEmbed } from 'discord.js'; import { highlightSubcommands } from './highlight-!.js'; diff --git a/src/commands/utilities/highlight-unblock.ts b/src/commands/utilities/highlight-unblock.ts index 0f2dd78..f9cc806 100644 --- a/src/commands/utilities/highlight-unblock.ts +++ b/src/commands/utilities/highlight-unblock.ts @@ -1,6 +1,6 @@ import { AllowedMentions, BotCommand, emojis, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { Argument, ArgumentGeneratorReturn } from '@notenoughupdates/discord-akairo'; import assert from 'assert'; -import { Argument, ArgumentGeneratorReturn } from 'discord-akairo'; import { BaseChannel, GuildMember, User } from 'discord.js'; import { HighlightUnblockResult } from '../../../lib/common/HighlightManager.js'; import { highlightSubcommands } from './highlight-!.js'; diff --git a/src/commands/utilities/price.ts b/src/commands/utilities/price.ts index 6f08aaa..0d5d4b3 100644 --- a/src/commands/utilities/price.ts +++ b/src/commands/utilities/price.ts @@ -1,7 +1,9 @@ import { ArgType, BotCommand, colors, emojis, format, formatList, type CommandMessage } from '#lib'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, AutocompleteInteraction, EmbedBuilder } from 'discord.js'; -import { default as Fuse } from 'fuse.js'; + +// todo: remove this bullshit once typescript gets its shit together +const Fuse = (await import('fuse.js')).default as unknown as typeof import('fuse.js').default; assert(Fuse); diff --git a/src/commands/utilities/steal.ts b/src/commands/utilities/steal.ts index a208920..bd2976a 100644 --- a/src/commands/utilities/steal.ts +++ b/src/commands/utilities/steal.ts @@ -1,13 +1,11 @@ import { Arg, BotCommand, emojis, format, OptArgType, regex, type CommandMessage, type SlashMessage } from '#lib'; +import { type ArgumentGeneratorReturn, type ArgumentType, type ArgumentTypeCaster } from '@notenoughupdates/discord-akairo'; import assert from 'assert/strict'; -import { type ArgumentGeneratorReturn, type ArgumentType, type ArgumentTypeCaster } from 'discord-akairo'; import { ApplicationCommandOptionType, Attachment } from 'discord.js'; -import _ from 'lodash'; +import { snakeCase } from 'lodash-es'; import { Stream } from 'stream'; import { URL } from 'url'; -assert(_); - // so I don't have to retype things const enum lang { emojiStart = 'What emoji would you like to steal?', @@ -53,7 +51,7 @@ export default class StealCommand extends BotCommand { const name = yield { prompt: { start: lang.nameStart, retry: lang.nameRetry, optional: true }, - default: hasImage && message.attachments.first()!.name ? _.snakeCase(message.attachments.first()!.name!) : 'unnamed_emoji' + default: hasImage && message.attachments.first()!.name ? snakeCase(message.attachments.first()!.name!) : 'unnamed_emoji' }; return { emoji, name }; diff --git a/src/commands/utilities/whoHasRole.ts b/src/commands/utilities/whoHasRole.ts index c01a0c3..31e413d 100644 --- a/src/commands/utilities/whoHasRole.ts +++ b/src/commands/utilities/whoHasRole.ts @@ -77,7 +77,7 @@ export default class WhoHasRoleCommand extends BotCommand { return await message.util.reply(`${emojis.error} No members found matching the given roles.`); } - return await ButtonPaginator.send(message, embedPages, null, true); + return await ButtonPaginator.send(message, embedPages, '', true); } } diff --git a/src/commands/utilities/wolframAlpha.ts b/src/commands/utilities/wolframAlpha.ts index 503af87..48739cf 100644 --- a/src/commands/utilities/wolframAlpha.ts +++ b/src/commands/utilities/wolframAlpha.ts @@ -1,7 +1,7 @@ import { AllowedMentions, BotCommand, colors, emojis, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; -import { initializeClass as WolframAlphaAPI } from '@notenoughupdates/wolfram-alpha-api'; +import { initializeClass as WolframAlphaAPI } from '@tanzanite/wolfram-alpha'; import assert from 'assert/strict'; -import { ApplicationCommandOptionType, EmbedBuilder, type MessageOptions } from 'discord.js'; +import { ApplicationCommandOptionType, EmbedBuilder, type MessageCreateOptions } from 'discord.js'; assert(WolframAlphaAPI); @@ -62,7 +62,7 @@ export default class WolframAlphaCommand extends BotCommand { name: '📥 Input', value: await this.client.utils.inspectCleanRedactCodeblock(args.expression) }); - const sendOptions: MessageOptions = { content: null, allowedMentions: AllowedMentions.none() }; + const sendOptions: MessageCreateOptions = { content: '', allowedMentions: AllowedMentions.none() }; try { const calculated = await (args.image ? waApi.getSimple({ i: args.expression, timeout: 1, background: '2C2F33', foreground: 'white' }) |