diff options
author | IRONM00N <64110067+IRONM00N@users.noreply.github.com> | 2022-06-16 14:32:18 -0400 |
---|---|---|
committer | IRONM00N <64110067+IRONM00N@users.noreply.github.com> | 2022-06-16 14:32:18 -0400 |
commit | 0e87bbd3940d89defcb04926587b35c8f4d1947f (patch) | |
tree | e50860d4dc25a11d4c3977b583284c4bcad1b077 /src/commands | |
parent | 661e4c9935aeb8760dafc7ced4bbec6cc356a033 (diff) | |
download | tanzanite-0e87bbd3940d89defcb04926587b35c8f4d1947f.tar.gz tanzanite-0e87bbd3940d89defcb04926587b35c8f4d1947f.tar.bz2 tanzanite-0e87bbd3940d89defcb04926587b35c8f4d1947f.zip |
remove util classes, move config out of src
Diffstat (limited to 'src/commands')
91 files changed, 1267 insertions, 755 deletions
diff --git a/src/commands/admin/channelPermissions.ts b/src/commands/admin/channelPermissions.ts index f6240a5..12245a9 100644 --- a/src/commands/admin/channelPermissions.ts +++ b/src/commands/admin/channelPermissions.ts @@ -1,4 +1,14 @@ -import { BushCommand, ButtonPaginator, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + ButtonPaginator, + clientSendAndPermCheck, + emojis, + formatError, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; @@ -15,7 +25,7 @@ export default class ChannelPermissionsCommand extends BushCommand { { id: 'target', description: 'The user/role to change the permissions of.', - type: util.arg.union('member', 'role'), + type: Arg.union('member', 'role'), readableType: 'member|role', prompt: 'What user/role would you like to change?', retry: '{error} Choose a valid user/role to change.', @@ -48,7 +58,7 @@ export default class ChannelPermissionsCommand extends BushCommand { ] } ], - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), userPermissions: [PermissionFlagsBits.Administrator], channel: 'guild', slash: true, @@ -64,9 +74,9 @@ export default class ChannelPermissionsCommand extends BushCommand { if (message.util.isSlashMessage(message)) await message.interaction.deferReply(); const permission = message.util.isSlashMessage(message) - ? await util.arg.cast('permission', message, args.permission) + ? await Arg.cast('permission', message, args.permission) : args.permission; - if (!permission) return await message.util.reply(`${util.emojis.error} Invalid permission.`); + if (!permission) return await message.util.reply(`${emojis.error} Invalid permission.`); const failedChannels = []; for (const [, channel] of message.guild.channels.cache) { try { @@ -79,7 +89,7 @@ export default class ChannelPermissionsCommand extends BushCommand { { reason: 'Changing overwrites for mass channel perms command' } ); } catch (e) { - void client.console.error('channelPermissions', util.formatError(e, false)); + void client.console.error('channelPermissions', formatError(e, false)); failedChannels.push(channel); } } diff --git a/src/commands/admin/roleAll.ts b/src/commands/admin/roleAll.ts index 80952cc..c731f08 100644 --- a/src/commands/admin/roleAll.ts +++ b/src/commands/admin/roleAll.ts @@ -1,4 +1,12 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + emojis, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, PermissionFlagsBits, type GuildMember } from 'discord.js'; @@ -32,7 +40,7 @@ export default class RoleAllCommand extends BushCommand { } ], channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles]), userPermissions: [PermissionFlagsBits.Administrator], typing: true, slash: true, @@ -43,11 +51,11 @@ export default class RoleAllCommand extends BushCommand { public override async exec(message: CommandMessage | SlashMessage, args: { role: ArgType<'role'>; bots: ArgType<'flag'> }) { assert(message.inGuild()); if (!message.member!.permissions.has(PermissionFlagsBits.Administrator) && !message.member!.user.isOwner()) - return await message.util.reply(`${util.emojis.error} You must have admin perms to use this command.`); + return await message.util.reply(`${emojis.error} You must have admin perms to use this command.`); if (message.util.isSlashMessage(message)) await message.interaction.deferReply(); if (args.role.comparePositionTo(message.guild.members.me!.roles.highest) >= 0 && !args.role) { - return await message.util.reply(`${util.emojis.error} I cannot assign a role higher or equal to my highest role.`); + return await message.util.reply(`${emojis.error} I cannot assign a role higher or equal to my highest role.`); } let members = await message.guild.members.fetch(); @@ -62,7 +70,7 @@ export default class RoleAllCommand extends BushCommand { return true; }); - await message.util.reply(`${util.emojis.loading} adding roles to ${members.size} members`); + await message.util.reply(`${emojis.loading} adding roles to ${members.size} members`); const promises = members.map((member: GuildMember) => { return member.roles.add(args.role, `RoleAll Command - triggered by ${message.author.tag} (${message.author.id})`); @@ -72,7 +80,7 @@ export default class RoleAllCommand extends BushCommand { if (!failed.length) { await message.util.sendNew({ - content: `${util.emojis.success} Finished adding <@&${args.role.id}> to **${members.size}** member${ + content: `${emojis.success} Finished adding <@&${args.role.id}> to **${members.size}** member${ members.size > 1 ? 's' : '' }.`, allowedMentions: AllowedMentions.none() @@ -80,7 +88,7 @@ export default class RoleAllCommand extends BushCommand { } else { const array = [...members.values()]; await message.util.sendNew({ - content: `${util.emojis.warn} Finished adding <@&${args.role.id}> to **${members.size - failed.length}** member${ + content: `${emojis.warn} Finished adding <@&${args.role.id}> to **${members.size - failed.length}** member${ members.size - failed.length > 1 ? 's' : '' }! Failed members:\n${failed.map((_, index) => `<@${array[index].id}>`).join(' ')}`, allowedMentions: AllowedMentions.none() diff --git a/src/commands/config/_customAutomodPhrases.ts b/src/commands/config/_customAutomodPhrases.ts index 13887ae..d60688c 100644 --- a/src/commands/config/_customAutomodPhrases.ts +++ b/src/commands/config/_customAutomodPhrases.ts @@ -30,7 +30,7 @@ // ], // slash: true, // channel: 'guild', -// clientPermissions: (m) => util.clientSendAndPermCheck(m), +// clientPermissions: (m) => clientSendAndPermCheck(m), // userPermissions: [PermissionFlagsBits.ManageGuild] // }); // } diff --git a/src/commands/config/blacklist.ts b/src/commands/config/blacklist.ts index de457c0..80acd0b 100644 --- a/src/commands/config/blacklist.ts +++ b/src/commands/config/blacklist.ts @@ -1,4 +1,17 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + addOrRemoveFromArray, + AllowedMentions, + Arg, + BushCommand, + clientSendAndPermCheck, + emojis, + format, + getGlobal, + setGlobal, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, GuildMember, PermissionFlagsBits, User } from 'discord.js'; @@ -23,7 +36,7 @@ export default class BlacklistCommand extends BushCommand { { id: 'target', description: 'The channel/user to blacklist.', - type: util.arg.union('channel', 'user'), + type: Arg.union('channel', 'user'), readableType: 'channel|user', prompt: 'What channel or user that you would like to blacklist/unblacklist?', retry: '{error} Pick a valid user or channel.', @@ -41,7 +54,7 @@ export default class BlacklistCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [PermissionFlagsBits.ManageGuild] }); } @@ -59,26 +72,26 @@ export default class BlacklistCommand extends BushCommand { const global = args.global && message.author.isOwner(); const target = typeof args.target === 'string' - ? (await util.arg.cast('textChannel', message, args.target)) ?? (await util.arg.cast('user', message, args.target)) + ? (await Arg.cast('textChannel', message, args.target)) ?? (await Arg.cast('user', message, args.target)) : args.target; - if (!target) return await message.util.reply(`${util.emojis.error} Choose a valid channel or user.`); + if (!target) return await message.util.reply(`${emojis.error} Choose a valid channel or user.`); const targetID = target.id; if (!message.inGuild() && !global) - return await message.util.reply(`${util.emojis.error} You have to be in a guild to disable commands.`); + return await message.util.reply(`${emojis.error} You have to be in a guild to disable commands.`); if (!global) assert(message.inGuild()); const blacklistedUsers = global - ? util.getGlobal('blacklistedUsers') + ? getGlobal('blacklistedUsers') : (await message.guild!.getSetting('blacklistedChannels')) ?? []; const blacklistedChannels = global - ? util.getGlobal('blacklistedChannels') + ? getGlobal('blacklistedChannels') : (await message.guild!.getSetting('blacklistedUsers')) ?? []; if (action === 'toggle') { action = blacklistedUsers.includes(targetID) || blacklistedChannels.includes(targetID) ? 'unblacklist' : 'blacklist'; } - const newValue = util.addOrRemoveFromArray( + const newValue = addOrRemoveFromArray( action === 'blacklist' ? 'add' : 'remove', target instanceof User ? blacklistedUsers : blacklistedChannels, targetID @@ -87,22 +100,22 @@ export default class BlacklistCommand extends BushCommand { const key = target instanceof User ? 'blacklistedUsers' : 'blacklistedChannels'; const success = await (global - ? util.setGlobal(key, newValue) + ? setGlobal(key, newValue) : message.guild!.setSetting(key, newValue, message.member as GuildMember) ).catch(() => false); if (!success) return await message.util.reply({ - content: `${util.emojis.error} There was an error${global ? ' globally' : ''} ${action}ing ${util.format.input( + content: `${emojis.error} There was an error${global ? ' globally' : ''} ${action}ing ${format.input( target instanceof User ? target.tag : target.name )}.`, allowedMentions: AllowedMentions.none() }); else return await message.util.reply({ - content: `${util.emojis.success} Successfully ${action}ed ${util.format.input( - target instanceof User ? target.tag : target.name - )}${global ? ' globally' : ''}.`, + content: `${emojis.success} Successfully ${action}ed ${format.input(target instanceof User ? target.tag : target.name)}${ + global ? ' globally' : '' + }.`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/config/config.ts b/src/commands/config/config.ts index 689a3af..f0db467 100644 --- a/src/commands/config/config.ts +++ b/src/commands/config/config.ts @@ -1,7 +1,14 @@ import { + addOrRemoveFromArray, BushCommand, + clientSendAndPermCheck, + colors, + emojis, GuildNoArraySetting, guildSettingsObj, + inspectAndRedact, + oxford, + prefix, settingsArr, type ArgType, type CommandMessage, @@ -145,7 +152,7 @@ export default class ConfigCommand extends BushCommand { }; }), channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [PermissionFlagsBits.ManageGuild] }); } @@ -171,11 +178,11 @@ export default class ConfigCommand extends BushCommand { id: 'action', type: actionType, prompt: { - start: `Would you like to ${util.oxford( + start: `Would you like to ${oxford( actionType!.map((a) => `\`${a}\``), 'or' )} the \`${setting}\` setting?`, - retry: `{error} Choose one of the following actions to perform on the ${setting} setting: ${util.oxford( + retry: `{error} Choose one of the following actions to perform on the ${setting} setting: ${oxford( actionType!.map((a) => `\`${a}\``), 'or' )}`, @@ -219,7 +226,7 @@ export default class ConfigCommand extends BushCommand { assert(message.member); if (!message.member.permissions.has(PermissionFlagsBits.ManageGuild) && !message.member?.user.isOwner()) - return await message.util.reply(`${util.emojis.error} You must have the **Manage Server** permission to run this command.`); + return await message.util.reply(`${emojis.error} You must have the **Manage Server** permission to run this command.`); const setting = message.util.isSlash ? (camelCase(args.subcommandGroup)! as GuildSettings) : args.setting!; const action = message.util.isSlash ? args.subcommand! : args.action!; const value = args.value; @@ -238,15 +245,13 @@ export default class ConfigCommand extends BushCommand { }; if (!value && !(['clear', 'delete'] as const).includes(action)) - return await message.util.reply( - `${util.emojis.error} You must choose a value to ${action} ${this.grammar(action, setting)}` - ); + return await message.util.reply(`${emojis.error} You must choose a value to ${action} ${this.grammar(action, setting)}`); switch (action) { case 'add': case 'remove': { const existing = (await message.guild.getSetting(setting)) as string[]; - const updated = util.addOrRemoveFromArray(action, existing, parseVal(value)); + const updated = addOrRemoveFromArray(action, existing, parseVal(value)); await message.guild.setSetting(setting, updated, message.member); const messageOptions = await this.generateMessageOptions(message, setting); msg = (await message.util.reply(messageOptions)) as Message; @@ -311,7 +316,7 @@ export default class ConfigCommand extends BushCommand { ): Promise<MessageOptions & InteractionUpdateOptions> { assert(message.inGuild()); - const settingsEmbed = new EmbedBuilder().setColor(util.colors.default); + const settingsEmbed = new EmbedBuilder().setColor(colors.default); if (!setting) { settingsEmbed.setTitle(`${message.guild.name}'s Settings`); const desc = settingsArr.map((s) => `:wrench: **${guildSettingsObj[s].name}**`).join('\n'); @@ -341,7 +346,7 @@ export default class ConfigCommand extends BushCommand { const func = ((): ((v: string | any) => string) => { switch (type.replace('-array', '') as BaseSettingTypes) { case 'string': - return (v) => util.inspectAndRedact(v); + return (v) => inspectAndRedact(v); case 'channel': return (v) => `<#${v}>`; case 'role': @@ -349,7 +354,7 @@ export default class ConfigCommand extends BushCommand { case 'user': return (v) => `<@${v}>`; case 'custom': - return util.inspectAndRedact; + return inspectAndRedact; default: return (v) => v; } @@ -372,7 +377,7 @@ export default class ConfigCommand extends BushCommand { ); settingsEmbed.setFooter({ - text: `Run "${util.prefix(message)}${message.util.parsed?.alias ?? 'config'} ${ + text: `Run "${prefix(message)}${message.util.parsed?.alias ?? 'config'} ${ message.util.isSlash ? snakeCase(setting) : setting } ${guildSettingsObj[setting].type.includes('-array') ? 'add/remove' : 'set'} <value>" to set this setting.` }); diff --git a/src/commands/config/disable.ts b/src/commands/config/disable.ts index 373b5f6..4f52b7c 100644 --- a/src/commands/config/disable.ts +++ b/src/commands/config/disable.ts @@ -1,4 +1,16 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + addOrRemoveFromArray, + AllowedMentions, + Arg, + BushCommand, + clientSendAndPermCheck, + emojis, + getGlobal, + setGlobal, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, AutocompleteInteraction, PermissionFlagsBits } from 'discord.js'; import Fuse from 'fuse.js'; @@ -28,7 +40,7 @@ export default class DisableCommand extends BushCommand { { id: 'command', description: 'The command to disable/enable.', - type: util.arg.union('commandAlias', 'command'), + type: Arg.union('commandAlias', 'command'), readableType: 'command|commandAlias', prompt: 'What command would you like to enable/disable?', retry: '{error} Pick a valid command.', @@ -48,7 +60,7 @@ export default class DisableCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [PermissionFlagsBits.ManageGuild] }); } @@ -62,23 +74,23 @@ export default class DisableCommand extends BushCommand { let action = (args.action ?? message.util?.parsed?.alias ?? 'toggle') as 'disable' | 'enable' | 'toggle'; const global = args.global && message.author.isOwner(); const commandID = - args.command instanceof BushCommand ? args.command.id : (await util.arg.cast('commandAlias', message, args.command))?.id; + args.command instanceof BushCommand ? args.command.id : (await Arg.cast('commandAlias', message, args.command))?.id; - if (!commandID) return await message.util.reply(`${util.emojis.error} Invalid command.`); + if (!commandID) return await message.util.reply(`${emojis.error} Invalid command.`); if (DisableCommand.blacklistedCommands.includes(commandID)) - return message.util.send(`${util.emojis.error} the ${commandID} command cannot be disabled.`); + return message.util.send(`${emojis.error} the ${commandID} command cannot be disabled.`); - const disabledCommands = global ? util.getGlobal('disabledCommands') : await message.guild.getSetting('disabledCommands'); + const disabledCommands = global ? getGlobal('disabledCommands') : await message.guild.getSetting('disabledCommands'); if (action === 'toggle') action = disabledCommands.includes(commandID) ? 'disable' : 'enable'; - const newValue = util.addOrRemoveFromArray(action === 'disable' ? 'add' : 'remove', disabledCommands, commandID); + const newValue = addOrRemoveFromArray(action === 'disable' ? 'add' : 'remove', disabledCommands, commandID); const success = global - ? await util.setGlobal('disabledCommands', newValue).catch(() => false) + ? await setGlobal('disabledCommands', newValue).catch(() => false) : await message.guild.setSetting('disabledCommands', newValue, message.member!).catch(() => false); if (!success) return await message.util.reply({ - content: `${util.emojis.error} There was an error${global ? ' globally' : ''} **${action.substring( + content: `${emojis.error} There was an error${global ? ' globally' : ''} **${action.substring( 0, action.length - 2 )}ing** the **${commandID}** command.`, @@ -86,10 +98,9 @@ export default class DisableCommand extends BushCommand { }); else return await message.util.reply({ - content: `${util.emojis.success} Successfully **${action.substring( - 0, - action.length - 2 - )}ed** the **${commandID}** command${global ? ' globally' : ''}.`, + content: `${emojis.success} Successfully **${action.substring(0, action.length - 2)}ed** the **${commandID}** command${ + global ? ' globally' : '' + }.`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/config/features.ts b/src/commands/config/features.ts index 95ae544..e88f4b7 100644 --- a/src/commands/config/features.ts +++ b/src/commands/config/features.ts @@ -1,5 +1,8 @@ import { BushCommand, + clientSendAndPermCheck, + colors, + emojis, guildFeaturesArr, guildFeaturesObj, type CommandMessage, @@ -27,7 +30,7 @@ export default class FeaturesCommand extends BushCommand { examples: ['features'], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [PermissionFlagsBits.ManageGuild] }); } @@ -35,7 +38,7 @@ export default class FeaturesCommand extends BushCommand { public override async exec(message: CommandMessage | SlashMessage) { assert(message.inGuild()); - const featureEmbed = new EmbedBuilder().setTitle(`${message.guild.name}'s Features`).setColor(util.colors.default); + const featureEmbed = new EmbedBuilder().setTitle(`${message.guild.name}'s Features`).setColor(colors.default); const enabledFeatures = await message.guild.getSetting('enabledFeatures'); this.generateDescription(guildFeaturesArr, enabledFeatures, featureEmbed); @@ -76,8 +79,7 @@ export default class FeaturesCommand extends BushCommand { embed.setDescription( allFeatures .map( - (feature) => - `${currentFeatures.includes(feature) ? util.emojis.check : util.emojis.cross} **${guildFeaturesObj[feature].name}**` + (feature) => `${currentFeatures.includes(feature) ? emojis.check : emojis.cross} **${guildFeaturesObj[feature].name}**` ) .join('\n') ); diff --git a/src/commands/config/log.ts b/src/commands/config/log.ts index 7c76bdf..3726105 100644 --- a/src/commands/config/log.ts +++ b/src/commands/config/log.ts @@ -1,4 +1,14 @@ -import { BushCommand, guildLogsArr, type ArgType, type CommandMessage, type GuildLogType, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + emojis, + guildLogsArr, + oxford, + type ArgType, + type CommandMessage, + type GuildLogType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ArgumentGeneratorReturn } from 'discord-akairo'; import { ApplicationCommandOptionType, ChannelType, PermissionFlagsBits } from 'discord.js'; @@ -38,7 +48,7 @@ export default class LogCommand extends BushCommand { } ], channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [PermissionFlagsBits.ManageGuild] }); } @@ -49,7 +59,7 @@ export default class LogCommand extends BushCommand { type: guildLogsArr, prompt: { start: 'What log type would you like to change?', - retry: `{error} Choose either ${util.oxford( + retry: `{error} Choose either ${oxford( guildLogsArr.map((l) => `\`${l}\``), 'or' )}`, @@ -87,8 +97,8 @@ export default class LogCommand extends BushCommand { return await message.util.reply( `${ success - ? `${util.emojis.success} Successfully ${oldChannel ? 'changed' : 'set'}` - : `${util.emojis.error} Unable to ${oldChannel ? 'change' : 'set'}` + ? `${emojis.success} Successfully ${oldChannel ? 'changed' : 'set'}` + : `${emojis.error} Unable to ${oldChannel ? 'change' : 'set'}` } ${ oldChannel ? `the **${args.log_type}** log channel from <#${oldChannel}>` : `the **${args.log_type}** log channel` } to ${args.channel ? `<#${args.channel.id}>` : '`disabled`'}` diff --git a/src/commands/dev/__template.ts b/src/commands/dev/__template.ts index 7bcce32..df4d146 100644 --- a/src/commands/dev/__template.ts +++ b/src/commands/dev/__template.ts @@ -1,4 +1,12 @@ -import { BushCommand, type ArgType, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + emojis, + type ArgType, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import { ApplicationCommandOptionType } from 'discord.js'; export default class TemplateCommand extends BushCommand { @@ -33,7 +41,7 @@ export default class TemplateCommand extends BushCommand { ownerOnly: true, channel: 'guild', hidden: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -42,7 +50,7 @@ export default class TemplateCommand extends BushCommand { message: CommandMessage | SlashMessage, args: { required_argument: ArgType<'string'>; optional_argument: OptArgType<'string'> } ) { - return await message.util.reply(`${util.emojis.error} Do not use the template command.`); + return await message.util.reply(`${emojis.error} Do not use the template command.`); args; } } diff --git a/src/commands/dev/debug.ts b/src/commands/dev/debug.ts index 682a93d..dd9109c 100644 --- a/src/commands/dev/debug.ts +++ b/src/commands/dev/debug.ts @@ -1,4 +1,4 @@ -// import { BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +// import { BushCommand, clientSendAndPermCheck, emojis, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; // import { ApplicationCommandOptionType, AutocompleteInteraction, ChatInputCommandInteraction } from 'discord.js'; // import Fuse from 'fuse.js'; @@ -24,7 +24,7 @@ // slash: true, // slashGuilds: ['516977525906341928'], // superUserOnly: true, -// clientPermissions: (m) => util.clientSendAndPermCheck(m), +// clientPermissions: (m) => clientSendAndPermCheck(m), // userPermissions: [] // }); // } @@ -52,7 +52,7 @@ // embeds: [{ description: 'And an embed' }] // }); // } else { -// return await message.util.reply(`${util.emojis.error} Invalid action.`); +// return await message.util.reply(`${emojis.error} Invalid action.`); // } // } diff --git a/src/commands/dev/dm.ts b/src/commands/dev/dm.ts index 468fb20..f1e2bce 100644 --- a/src/commands/dev/dm.ts +++ b/src/commands/dev/dm.ts @@ -1,4 +1,4 @@ -import { BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, emojis, format, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; import { ApplicationCommandOptionType } from 'discord.js'; export default class DMCommand extends BushCommand { @@ -31,7 +31,7 @@ export default class DMCommand extends BushCommand { slash: false, ownerOnly: true, hidden: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -43,8 +43,8 @@ export default class DMCommand extends BushCommand { try { await client.users.send(args.user.id, args.content); } catch (e) { - return message.util.reply(`${util.emojis.error} There was an error sending ${util.format.input(args.user.tag)} a dm.`); + return message.util.reply(`${emojis.error} There was an error sending ${format.input(args.user.tag)} a dm.`); } - return message.util.reply(`${util.emojis.success} Successfully sent ${util.format.input(args.user.tag)} a dm.`); + return message.util.reply(`${emojis.success} Successfully sent ${format.input(args.user.tag)} a dm.`); } } diff --git a/src/commands/dev/eval.ts b/src/commands/dev/eval.ts index b8ee9e4..239a06a 100644 --- a/src/commands/dev/eval.ts +++ b/src/commands/dev/eval.ts @@ -1,11 +1,17 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ import { ActivePunishment, + assertAll, BushCommand, BushInspectOptions, + clientSendAndPermCheck, CodeBlockLang, + colors, + emojis, + getMethods, Global, Guild, + inspectCleanRedactCodeblock, Level, ModLog, Shared, @@ -40,8 +46,7 @@ import { PermissionFlagsBits, PermissionsBitField, ReactionCollector, - SelectMenuComponent, - Util + SelectMenuComponent } from 'discord.js'; import got from 'got'; import path from 'path'; @@ -49,15 +54,13 @@ import ts from 'typescript'; import { fileURLToPath } from 'url'; import { promisify } from 'util'; const { transpile } = ts, - emojis = util.emojis, - colors = util.colors, sh = promisify(exec), SnowflakeUtil = new Snowflake_(1420070400000n), __dirname = path.dirname(fileURLToPath(import.meta.url)); /* eslint-enable @typescript-eslint/no-unused-vars */ // prettier-ignore -util.assertAll(ActivePunishment, BushCommand, Global, Guild, Level, ModLog, Shared, StickyRole, Snowflake_, Canvas, exec, ActionRow, ButtonComponent, ButtonInteraction, Collection, Collector, CommandInteraction, ContextMenuCommandInteraction, DMChannel, Embed, Emoji, Interaction, InteractionCollector, Message, Attachment, MessageCollector, OAuth2Scopes, PermissionFlagsBits, PermissionsBitField, ReactionCollector, SelectMenuComponent, Util, path, ts, fileURLToPath, promisify, assert, got, transpile, emojis, colors, sh, SnowflakeUtil, __dirname); +assertAll(ActivePunishment, BushCommand, Global, Guild, Level, ModLog, Shared, StickyRole, Snowflake_, Canvas, exec, ActionRow, ButtonComponent, ButtonInteraction, Collection, Collector, CommandInteraction, ContextMenuCommandInteraction, DMChannel, Embed, Emoji, Interaction, InteractionCollector, Message, Attachment, MessageCollector, OAuth2Scopes, PermissionFlagsBits, PermissionsBitField, ReactionCollector, SelectMenuComponent, path, ts, fileURLToPath, promisify, assert, got, transpile, sh, SnowflakeUtil, __dirname); export default class EvalCommand extends BushCommand { public constructor() { @@ -174,7 +177,7 @@ export default class EvalCommand extends BushCommand { ], slash: true, ownerOnly: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -207,12 +210,11 @@ export default class EvalCommand extends BushCommand { no_inspect_strings: ArgType<'flag'>; } ) { - if (!message.author.isOwner()) - return await message.util.reply(`${util.emojis.error} Only my developers can run this command.`); + if (!message.author.isOwner()) return await message.util.reply(`${emojis.error} Only my developers can run this command.`); if (message.util.isSlashMessage(message)) await message.interaction.deferReply({ ephemeral: silent }); if (!sudo && ['delete', 'destroy'].some((p) => argCode.includes(p))) { - return await message.util.send(`${util.emojis.error} This eval was blocked by smooth brain protection™.`); + return await message.util.send(`${emojis.error} This eval was blocked by smooth brain protection™.`); } const isTypescript = typescript || argCode.includes('```ts'); @@ -308,12 +310,12 @@ export default class EvalCommand extends BushCommand { private async codeblock(obj: any, language: CodeBlockLang, options: CodeBlockCustomOptions = {}) { if (options.prototype) obj = Object.getPrototypeOf(obj); - if (options.methods) obj = util.getMethods(obj); + if (options.methods) obj = getMethods(obj); options.depth ??= 1; options.getters ??= true; - return util.inspectCleanRedactCodeblock(obj, language, options); + return inspectCleanRedactCodeblock(obj, language, options); } } diff --git a/src/commands/dev/javascript.ts b/src/commands/dev/javascript.ts index fd1894b..7c47f2f 100644 --- a/src/commands/dev/javascript.ts +++ b/src/commands/dev/javascript.ts @@ -1,4 +1,14 @@ -import { BushCommand, type ArgType, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + colors, + emojis, + inspectCleanRedactCodeblock, + type ArgType, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder } from 'discord.js'; import { VM } from 'vm2'; @@ -35,7 +45,7 @@ export default class JavascriptCommand extends BushCommand { ], slash: true, superUserOnly: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -44,36 +54,35 @@ export default class JavascriptCommand extends BushCommand { message: CommandMessage | SlashMessage, args: { code: ArgType<'string'>; sel_depth: OptArgType<'integer'> } ) { - if (!message.author.isSuperUser()) - return await message.util.reply(`${util.emojis.error} Only super users can run this command.`); + if (!message.author.isSuperUser()) return await message.util.reply(`${emojis.error} Only super users can run this command.`); if (message.util.isSlashMessage(message)) { await message.interaction.deferReply({ ephemeral: false }); } const code = args.code.replace(/[“”]/g, '"').replace(/```*(?:js)?/g, ''); const embed = new EmbedBuilder(); - const input = await util.inspectCleanRedactCodeblock(code, 'js'); + const input = await inspectCleanRedactCodeblock(code, 'js'); try { const rawOutput = /^(9\s*?\+\s*?10)|(10\s*?\+\s*?9)$/.test(code) ? '21' : new VM({ eval: true, wasm: true, timeout: 1_000, fixAsync: true }).run(`${code}`); - const output = await util.inspectCleanRedactCodeblock(rawOutput, 'js', { + const output = await inspectCleanRedactCodeblock(rawOutput, 'js', { depth: args.sel_depth ?? 0, getters: true, inspectStrings: true, colors: false }); - embed.setTitle(`${util.emojis.successFull} Successfully Evaluated Expression`).setColor(util.colors.success); + embed.setTitle(`${emojis.successFull} Successfully Evaluated Expression`).setColor(colors.success); embed.addFields([ { name: '📥 Input', value: input }, { name: '📤 Output', value: output } ]); } catch (e) { - embed.setTitle(`${util.emojis.errorFull} Unable to Evaluate Expression`).setColor(util.colors.error); + embed.setTitle(`${emojis.errorFull} Unable to Evaluate Expression`).setColor(colors.error); embed.addFields([ { name: '📥 Input', value: input }, - { name: '📤 Error', value: await util.inspectCleanRedactCodeblock(e, 'js', { colors: false }) } + { name: '📤 Error', value: await inspectCleanRedactCodeblock(e, 'js', { colors: false }) } ]); } diff --git a/src/commands/dev/reload.ts b/src/commands/dev/reload.ts index 96c395f..8c2000f 100644 --- a/src/commands/dev/reload.ts +++ b/src/commands/dev/reload.ts @@ -1,4 +1,13 @@ -import { BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + codeblock, + emojis, + formatError, + shell, + type CommandMessage, + type SlashMessage +} from '#lib'; export default class ReloadCommand extends BushCommand { public constructor() { @@ -22,19 +31,18 @@ export default class ReloadCommand extends BushCommand { ownerOnly: true, typing: true, slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } public override async exec(message: CommandMessage | SlashMessage /* args: { fast: ArgType<'flag'> } */) { - if (!message.author.isOwner()) - return await message.util.reply(`${util.emojis.error} Only my developers can run this command.`); + if (!message.author.isOwner()) return await message.util.reply(`${emojis.error} Only my developers can run this command.`); let output: { stdout: string; stderr: string }; try { const s = new Date(); - output = await util.shell(`yarn build:${/* args.fast ? 'esbuild' : */ 'tsc'}`); + output = await shell(`yarn build:${/* args.fast ? 'esbuild' : */ 'tsc'}`); await Promise.all([ client.commandHandler.reloadAll(), client.listenerHandler.reloadAll(), @@ -46,9 +54,7 @@ export default class ReloadCommand extends BushCommand { return message.util.send(`🔁 Successfully reloaded! (${new Date().getTime() - s.getTime()}ms)`); } catch (e) { if (output!) void client.logger.error('reloadCommand', output); - return message.util.send( - `An error occurred while reloading:\n${await util.codeblock(util.formatError(e), 2048 - 34, 'js', true)}` - ); + return message.util.send(`An error occurred while reloading:\n${await codeblock(formatError(e), 2048 - 34, 'js', true)}`); } } } diff --git a/src/commands/dev/say.ts b/src/commands/dev/say.ts index a452126..6ec52a1 100644 --- a/src/commands/dev/say.ts +++ b/src/commands/dev/say.ts @@ -1,4 +1,12 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + emojis, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import { ApplicationCommandOptionType } from 'discord.js'; export default class SayCommand extends BushCommand { @@ -21,15 +29,14 @@ export default class SayCommand extends BushCommand { } ], ownerOnly: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [], slash: true }); } public override async exec(message: CommandMessage | SlashMessage, args: { content: ArgType<'string'> }) { - if (!message.author.isOwner()) - return await message.util.reply(`${util.emojis.error} Only my developers can run this command.`); + if (!message.author.isOwner()) return await message.util.reply(`${emojis.error} Only my developers can run this command.`); await message.delete().catch(() => null); await message.util.send({ content: args.content, allowedMentions: AllowedMentions.none() }).catch(() => null); @@ -38,7 +45,7 @@ export default class SayCommand extends BushCommand { public override async execSlash(message: SlashMessage, args: { content: string }) { if (!client.config.owners.includes(message.author.id)) { return await message.interaction.reply({ - content: `${util.emojis.error} Only my developers can run this command.`, + content: `${emojis.error} Only my developers can run this command.`, ephemeral: true }); } diff --git a/src/commands/dev/servers.ts b/src/commands/dev/servers.ts index e99bcda..28a4e5d 100644 --- a/src/commands/dev/servers.ts +++ b/src/commands/dev/servers.ts @@ -1,4 +1,13 @@ -import { BushCommand, ButtonPaginator, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + ButtonPaginator, + chunk, + clientSendAndPermCheck, + colors, + format, + type CommandMessage, + type SlashMessage +} from '#lib'; import { stripIndent } from '#tags'; import { type APIEmbed, type Guild } from 'discord.js'; @@ -10,7 +19,7 @@ export default class ServersCommand extends BushCommand { description: 'Displays all the severs the bot is in', usage: ['servers'], examples: ['servers'], - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [], ownerOnly: true }); @@ -18,13 +27,13 @@ export default class ServersCommand extends BushCommand { public override async exec(message: CommandMessage | SlashMessage) { const guilds = [...client.guilds.cache.sort((a, b) => (a.memberCount < b.memberCount ? 1 : -1)).values()]; - const chunkedGuilds: Guild[][] = util.chunk(guilds, 10); + const chunkedGuilds: Guild[][] = chunk(guilds, 10); const embeds: APIEmbed[] = chunkedGuilds.map((chunk) => { return { title: `Server List [\`${guilds.length.toLocaleString()}\`]`, - color: util.colors.default, + color: colors.default, fields: chunk.map((guild) => ({ - name: util.format.input(guild.name), + name: format.input(guild.name), value: stripIndent` **ID:** ${guild.id} **Owner:** ${client.users.cache.has(guild.ownerId) ? client.users.cache.get(guild.ownerId)!.tag : guild.ownerId} diff --git a/src/commands/dev/sh.ts b/src/commands/dev/sh.ts index 8c62f5d..f7c17bd 100644 --- a/src/commands/dev/sh.ts +++ b/src/commands/dev/sh.ts @@ -1,8 +1,18 @@ -import { ArgType, BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { + ArgType, + BushCommand, + clientSendAndPermCheck, + codeblock, + colors, + emojis, + formatError, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import chalk from 'chalk'; import { exec } from 'child_process'; -import { ApplicationCommandOptionType, EmbedBuilder, Util } from 'discord.js'; +import { ApplicationCommandOptionType, cleanCodeBlockContent, EmbedBuilder } from 'discord.js'; import { promisify } from 'util'; assert(chalk); @@ -11,7 +21,7 @@ const sh = promisify(exec); const clean = (text: string | any) => { chalk.toString; if (typeof text === 'string') { - return (text = Util.cleanCodeBlockContent(text)); + return (text = cleanCodeBlockContent(text)); } else return text; }; @@ -35,24 +45,24 @@ export default class ShCommand extends BushCommand { } ], ownerOnly: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } public override async exec(message: CommandMessage | SlashMessage, args: { command: ArgType<'string'> }) { if (!client.config.owners.includes(message.author.id)) - return await message.util.reply(`${util.emojis.error} Only my developers can run this command.`); + return await message.util.reply(`${emojis.error} Only my developers can run this command.`); const input = clean(args.command); const embed = new EmbedBuilder() - .setColor(util.colors.gray) + .setColor(colors.gray) .setFooter({ text: message.author.tag, iconURL: message.author.avatarURL() ?? undefined }) .setTimestamp() .setTitle('Shell Command') .addFields([ - { name: '📥 Input', value: await util.codeblock(input, 1024, 'sh', true) }, - { name: 'Running', value: util.emojis.loading } + { name: '📥 Input', value: await codeblock(input, 1024, 'sh', true) }, + { name: 'Running', value: emojis.loading } ]); await message.util.reply({ embeds: [embed] }); @@ -69,20 +79,14 @@ export default class ShCommand extends BushCommand { const stdout = /* strip( */ clean(output.stdout); /* ) */ const stderr = /* strip( */ clean(output.stderr); /* ) */ - embed - .setTitle(`${util.emojis.successFull} Executed command successfully.`) - .setColor(util.colors.success) - .spliceFields(1, 1); + embed.setTitle(`${emojis.successFull} Executed command successfully.`).setColor(colors.success).spliceFields(1, 1); - if (stdout) embed.addFields([{ name: '📤 stdout', value: await util.codeblock(stdout, 1024, 'ansi', true) }]); - if (stderr) embed.addFields([{ name: '📤 stderr', value: await util.codeblock(stderr, 1024, 'ansi', true) }]); + if (stdout) embed.addFields([{ name: '📤 stdout', value: await codeblock(stdout, 1024, 'ansi', true) }]); + if (stderr) embed.addFields([{ name: '📤 stderr', value: await codeblock(stderr, 1024, 'ansi', true) }]); } catch (e) { - embed - .setTitle(`${util.emojis.errorFull} An error occurred while executing.`) - .setColor(util.colors.error) - .spliceFields(1, 1); + embed.setTitle(`${emojis.errorFull} An error occurred while executing.`).setColor(colors.error).spliceFields(1, 1); - embed.addFields([{ name: '📤 Output', value: await util.codeblock(util.formatError(e, true), 1024, 'ansi', true) }]); + embed.addFields([{ name: '📤 Output', value: await codeblock(formatError(e, true), 1024, 'ansi', true) }]); } await message.util.edit({ embeds: [embed] }); } diff --git a/src/commands/dev/superUser.ts b/src/commands/dev/superUser.ts index 6a2b745..3de04bf 100644 --- a/src/commands/dev/superUser.ts +++ b/src/commands/dev/superUser.ts @@ -1,4 +1,13 @@ -import { BushCommand, type ArgType, type CommandMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + emojis, + format, + getShared, + insertOrRemoveFromShared, + type ArgType, + type CommandMessage +} from '#lib'; import { type ArgumentGeneratorReturn, type ArgumentTypeCasterReturn } from 'discord-akairo'; export default class SuperUserCommand extends BushCommand { @@ -9,7 +18,7 @@ export default class SuperUserCommand extends BushCommand { description: 'A command to manage superusers.', usage: ['superuser <add/remove> <user>'], examples: ['superuser add IRONM00N'], - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [], ownerOnly: true, helpArgs: [ @@ -54,29 +63,28 @@ export default class SuperUserCommand extends BushCommand { } public override async exec(message: CommandMessage, args: { action: 'add' | 'remove'; user: ArgType<'user'> }) { - if (!message.author.isOwner()) - return await message.util.reply(`${util.emojis.error} Only my developers can run this command.`); + if (!message.author.isOwner()) return await message.util.reply(`${emojis.error} Only my developers can run this command.`); - const superUsers: string[] = util.getShared('superUsers'); + const superUsers: string[] = getShared('superUsers'); if (args.action === 'add' ? superUsers.includes(args.user.id) : !superUsers.includes(args.user.id)) return message.util.reply( - `${util.emojis.warn} ${util.format.input(args.user.tag)} is ${args.action === 'add' ? 'already' : 'not'} a superuser.` + `${emojis.warn} ${format.input(args.user.tag)} is ${args.action === 'add' ? 'already' : 'not'} a superuser.` ); - const success = await util.insertOrRemoveFromShared(args.action, 'superUsers', args.user.id).catch(() => false); + const success = await insertOrRemoveFromShared(args.action, 'superUsers', args.user.id).catch(() => false); if (success) { return await message.util.reply( - `${util.emojis.success} ${args.action == 'remove' ? '' : 'made'} ${util.format.input(args.user.tag)} ${ + `${emojis.success} ${args.action == 'remove' ? '' : 'made'} ${format.input(args.user.tag)} ${ args.action == 'remove' ? 'is no longer ' : '' }a superuser.` ); } else { return await message.util.reply( - `${util.emojis.error} There was an error ${args.action == 'remove' ? `removing` : 'making'} ${util.format.input( - args.user.tag - )} ${args.action == 'remove' ? `from` : 'to'} the superuser list.` + `${emojis.error} There was an error ${args.action == 'remove' ? `removing` : 'making'} ${format.input(args.user.tag)} ${ + args.action == 'remove' ? `from` : 'to' + } the superuser list.` ); } } diff --git a/src/commands/dev/syncAutomod.ts b/src/commands/dev/syncAutomod.ts index 9954e70..c78e6c0 100644 --- a/src/commands/dev/syncAutomod.ts +++ b/src/commands/dev/syncAutomod.ts @@ -1,4 +1,4 @@ -import { BushCommand, Shared, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, emojis, Shared, type CommandMessage, type SlashMessage } from '#lib'; import got from 'got'; import typescript from 'typescript'; import { NodeVM } from 'vm2'; @@ -13,14 +13,14 @@ export default class SyncAutomodCommand extends BushCommand { examples: ['sync-automod'], slash: false, hidden: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } public override async exec(message: CommandMessage | SlashMessage) { if (!message.author.isOwner() && message.author.id !== '497789163555389441') - return await message.util.reply(`${util.emojis.error} Only a very select few may use this command.`); + return await message.util.reply(`${emojis.error} Only a very select few may use this command.`); const badLinks = (await got.get('https://raw.githubusercontent.com/NotEnoughUpdates/bush-bot/master/src/lib/badlinks.ts')) .body; @@ -38,6 +38,6 @@ export default class SyncAutomodCommand extends BushCommand { row.badWords = badWordsParsed; await row.save(); - return await message.util.reply(`${util.emojis.success} Automod info synced.`); + return await message.util.reply(`${emojis.success} Automod info synced.`); } } diff --git a/src/commands/dev/test.ts b/src/commands/dev/test.ts index d54d544..9491d19 100644 --- a/src/commands/dev/test.ts +++ b/src/commands/dev/test.ts @@ -1,4 +1,13 @@ -import { BushCommand, ButtonPaginator, OptArgType, Shared, type CommandMessage } from '#lib'; +import { + BushCommand, + ButtonPaginator, + clientSendAndPermCheck, + colors, + emojis, + OptArgType, + Shared, + type CommandMessage +} from '#lib'; import { ActionRowBuilder, ButtonBuilder, @@ -33,7 +42,7 @@ export default class TestCommand extends BushCommand { } ], superUserOnly: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -65,7 +74,7 @@ export default class TestCommand extends BushCommand { const embed = new EmbedBuilder() .addFields([{ name: 'Field Name', value: 'Field Content' }]) .setAuthor({ name: 'Author', iconURL: 'https://www.w3schools.com/w3css/img_snowtops.jpg', url: 'https://google.com/' }) - .setColor(message.member?.displayColor ?? util.colors.default) + .setColor(message.member?.displayColor ?? colors.default) .setDescription('Description') .setFooter({ text: 'Footer', iconURL: message.author.avatarURL() ?? undefined }) .setURL('https://duckduckgo.com/') @@ -106,12 +115,12 @@ export default class TestCommand extends BushCommand { const fields = Array(25) .fill(0) .map((_, i) => ({ name: `Field ${i}`, value: 'Field Value' })); - const c = util.colors; const o = { description, author, footer, fields, time: Date.now() }; - const colors = [c.red, c.orange, c.gold, c.yellow, c.green, c.darkGreen, c.aqua, c.blue, c.purple, c.pink]; + const c = colors; + const embedColors = [c.red, c.orange, c.gold, c.yellow, c.green, c.darkGreen, c.aqua, c.blue, c.purple, c.pink]; - const embeds = colors.map((c, i) => ({ ...o, title: `Embed Title ${i}`, color: c })); + const embeds = embedColors.map((c, i) => ({ ...o, title: `Embed Title ${i}`, color: c })); const ButtonRows: ActionRowBuilder<ButtonBuilder>[] = []; for (let a = 1; a <= 5; a++) { @@ -125,7 +134,7 @@ export default class TestCommand extends BushCommand { } return await message.util.reply({ content: 'this is content', components: ButtonRows, embeds }); } else if (['delete slash commands'].includes(args.feature?.toLowerCase())) { - if (!message.guild) return await message.util.reply(`${util.emojis.error} This test can only be run in a guild.`); + if (!message.guild) return await message.util.reply(`${emojis.error} This test can only be run in a guild.`); await client.guilds.fetch(); const promises: Promise<Collection<string, ApplicationCommand>>[] = []; client.guilds.cache.each((guild) => { @@ -136,16 +145,16 @@ export default class TestCommand extends BushCommand { await client.application!.commands.fetch(); await client.application!.commands.set([]); - return await message.util.reply(`${util.emojis.success} Removed guild commands and global commands.`); + return await message.util.reply(`${emojis.success} Removed guild commands and global commands.`); } else if (['drop down', 'drop downs', 'select menu', 'select menus'].includes(args.feature?.toLowerCase())) { - return message.util.reply(`${util.emojis.error} no`); + 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(`${util.emojis.success} Synced automod.`); + return await message.util.reply(`${emojis.success} Synced automod.`); } else if (['modal'].includes(args.feature?.toLowerCase())) { const m = await message.util.reply({ content: 'Click for modal', diff --git a/src/commands/fun/coinFlip.ts b/src/commands/fun/coinFlip.ts index fea5cb5..3adf7f2 100644 --- a/src/commands/fun/coinFlip.ts +++ b/src/commands/fun/coinFlip.ts @@ -1,4 +1,4 @@ -import { BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, type CommandMessage, type SlashMessage } from '#lib'; export default class CoinFlipCommand extends BushCommand { public constructor() { @@ -8,7 +8,7 @@ export default class CoinFlipCommand extends BushCommand { description: 'Flip a virtual coin.', usage: ['coinflip'], examples: ['coinflip'], - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [], slash: true }); diff --git a/src/commands/fun/dice.ts b/src/commands/fun/dice.ts index b2bc7e4..e7e5927 100644 --- a/src/commands/fun/dice.ts +++ b/src/commands/fun/dice.ts @@ -1,4 +1,4 @@ -import { BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, type CommandMessage, type SlashMessage } from '#lib'; export default class DiceCommand extends BushCommand { public constructor() { @@ -8,7 +8,7 @@ export default class DiceCommand extends BushCommand { description: 'Roll virtual dice.', usage: ['dice'], examples: ['dice'], - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [], slash: true }); diff --git a/src/commands/fun/eightBall.ts b/src/commands/fun/eightBall.ts index 66fcc45..eb5aee8 100644 --- a/src/commands/fun/eightBall.ts +++ b/src/commands/fun/eightBall.ts @@ -1,4 +1,4 @@ -import { BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, type CommandMessage, type SlashMessage } from '#lib'; import { ApplicationCommandOptionType } from 'discord.js'; export default class EightBallCommand extends BushCommand { @@ -21,7 +21,7 @@ export default class EightBallCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } diff --git a/src/commands/fun/minesweeper.ts b/src/commands/fun/minesweeper.ts index d25cb5d..c2fdccf 100644 --- a/src/commands/fun/minesweeper.ts +++ b/src/commands/fun/minesweeper.ts @@ -1,4 +1,12 @@ -import { BushCommand, OptArgType, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + emojis, + OptArgType, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import { Minesweeper } from '@notenoughupdates/discord.js-minesweeper'; import assert from 'assert'; import { ApplicationCommandOptionType } from 'discord.js'; @@ -63,7 +71,7 @@ export default class MinesweeperCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -95,14 +103,14 @@ export default class MinesweeperCommand extends BushCommand { if (args.rows * args.columns <= args.mines * 2) return message.util.reply( - `${util.emojis.error} The number of roles multiplied by the number of columns must be greater than or equal to the number of mines multiplied by two.` + `${emojis.error} The number of roles multiplied by the number of columns must be greater than or equal to the number of mines multiplied by two.` ); - if (!matrix) return await message.util.reply(`${util.emojis.error} Something went wrong.`); + if (!matrix) return await message.util.reply(`${emojis.error} Something went wrong.`); const res = matrix.toString().replaceAll(':zero:', ':blue_square:'); - if (res.length > 2000) return message.util.reply(`${util.emojis.error} The minesweeper generated is over 2,000 characters.`); + if (res.length > 2000) return message.util.reply(`${emojis.error} The minesweeper generated is over 2,000 characters.`); return await message.util.reply(res); } diff --git a/src/commands/info/avatar.ts b/src/commands/info/avatar.ts index 544c30a..3eae98c 100644 --- a/src/commands/info/avatar.ts +++ b/src/commands/info/avatar.ts @@ -1,4 +1,4 @@ -import { BushCommand, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { Arg, BushCommand, clientSendAndPermCheck, colors, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; import { ApplicationCommandOptionType, EmbedBuilder, GuildMember, PermissionFlagsBits } from 'discord.js'; export default class AvatarCommand extends BushCommand { @@ -13,7 +13,7 @@ export default class AvatarCommand extends BushCommand { { id: 'user', description: 'The user you would like to find the avatar of.', - type: util.arg.union('member', 'globalUser'), + type: Arg.union('member', 'globalUser'), readableType: 'member|user', prompt: 'Who would you like to see the avatar of?', retry: '{error} Choose a valid user.', @@ -21,7 +21,7 @@ export default class AvatarCommand extends BushCommand { slashType: ApplicationCommandOptionType.User } ], - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], slash: true }); @@ -37,7 +37,7 @@ export default class AvatarCommand extends BushCommand { const guildAvatar = member?.avatarURL(params); - const embed = new EmbedBuilder().setTimestamp().setColor(util.colors.default).setTitle(`${user.tag}'s Avatar`); + const embed = new EmbedBuilder().setTimestamp().setColor(colors.default).setTitle(`${user.tag}'s Avatar`); guildAvatar ? embed.setImage(guildAvatar).setThumbnail(user.avatarURL(params) ?? defaultAvatar) : embed.setImage(user.avatarURL(params) ?? defaultAvatar); diff --git a/src/commands/info/botInfo.ts b/src/commands/info/botInfo.ts index 4a8a36a..decbe04 100644 --- a/src/commands/info/botInfo.ts +++ b/src/commands/info/botInfo.ts @@ -1,4 +1,13 @@ -import { BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + colors, + humanizeDuration, + mapIDs, + shell, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { EmbedBuilder, PermissionFlagsBits, version as discordJSVersion } from 'discord.js'; import * as os from 'os'; @@ -15,7 +24,7 @@ export default class BotInfoCommand extends BushCommand { usage: ['bot-info'], examples: ['bot-info'], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -35,14 +44,14 @@ export default class BotInfoCommand extends BushCommand { haiku = 'Haiku' } - const developers = (await util.mapIDs(client.config.owners)).map((u) => u?.tag).join('\n'); - const currentCommit = (await util.shell('git rev-parse HEAD')).stdout.replace('\n', ''); - let repoUrl = (await util.shell('git remote get-url origin')).stdout.replace('\n', ''); + const developers = (await mapIDs(client.config.owners)).map((u) => u?.tag).join('\n'); + const currentCommit = (await shell('git rev-parse HEAD')).stdout.replace('\n', ''); + let repoUrl = (await shell('git remote get-url origin')).stdout.replace('\n', ''); if (repoUrl.includes('.git')) repoUrl = repoUrl.substring(0, repoUrl.length - 4); const embed = new EmbedBuilder() .setTitle('Bot Info:') .addFields([ - { name: '**Uptime**', value: util.humanizeDuration(client.uptime!, 2), inline: true }, + { name: '**Uptime**', value: humanizeDuration(client.uptime!, 2), inline: true }, { name: '**Memory Usage**', value: `System: ${prettyBytes(os.totalmem() - os.freemem(), { binary: true })}/${prettyBytes(os.totalmem(), { @@ -73,7 +82,7 @@ export default class BotInfoCommand extends BushCommand { { name: '**Developers**', value: developers, inline: true } ]) .setTimestamp() - .setColor(util.colors.default); + .setColor(colors.default); await message.util.reply({ embeds: [embed] }); } } diff --git a/src/commands/info/color.ts b/src/commands/info/color.ts index f60e28a..84c4b3c 100644 --- a/src/commands/info/color.ts +++ b/src/commands/info/color.ts @@ -1,4 +1,13 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + Arg, + BushCommand, + clientSendAndPermCheck, + emojis, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder, GuildMember, PermissionFlagsBits, Role } from 'discord.js'; import tinycolor from 'tinycolor2'; @@ -16,7 +25,7 @@ export default class ColorCommand extends BushCommand { { id: 'color', description: 'The color string, role, or member to find the color of.', - type: util.arg.union('tinyColor', 'role', 'member'), + type: Arg.union('tinyColor', 'role', 'member'), readableType: 'color|role|member', match: 'restContent', prompt: 'What color code, role, or user would you like to find the color of?', @@ -25,7 +34,7 @@ export default class ColorCommand extends BushCommand { } ], channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -36,10 +45,7 @@ export default class ColorCommand extends BushCommand { public override async exec(message: CommandMessage | SlashMessage, args: { color: ArgType<'tinyColor' | 'role' | 'member'> }) { const _color = message.util.isSlashMessage(message) - ? ((await util.arg.cast(util.arg.union('tinyColor', 'role', 'member'), message, args.color as string)) as - | string - | Role - | GuildMember) + ? ((await Arg.cast(Arg.union('tinyColor', 'role', 'member'), message, args.color as string)) as string | Role | GuildMember) : args.color; const color = @@ -51,7 +57,7 @@ export default class ColorCommand extends BushCommand { if (_color instanceof Role && _color.hexColor === '#000000') { return await message.util.reply({ - content: `${util.emojis.error} <@&${_color.id}> does not have a color.`, + content: `${emojis.error} <@&${_color.id}> does not have a color.`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/info/guildInfo.ts b/src/commands/info/guildInfo.ts index 572cf06..92999a5 100644 --- a/src/commands/info/guildInfo.ts +++ b/src/commands/info/guildInfo.ts @@ -1,9 +1,23 @@ -import { BushCommand, type ArgType, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + akairo, + Arg, + BushCommand, + clientSendAndPermCheck, + colors, + emojis, + mappings, + timestampAndDelta, + type ArgType, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, ChannelType, EmbedBuilder, + escapeMarkdown, Guild, GuildDefaultMessageNotifications, GuildExplicitContentFilter, @@ -29,7 +43,7 @@ export default class GuildInfoCommand extends BushCommand { { id: 'guild', description: 'The guild to find information about.', - type: util.arg.union('guild', 'snowflake'), + type: Arg.union('guild', 'snowflake'), readableType: 'guild|snowflake', prompt: 'What server would you like to find information about?', retry: '{error} Choose a valid server to find information about.', @@ -38,7 +52,7 @@ export default class GuildInfoCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -46,7 +60,7 @@ export default class GuildInfoCommand extends BushCommand { public override async exec(message: CommandMessage | SlashMessage, args: { guild: OptArgType<'guild' | 'snowflake'> }) { if (!args.guild && !message.inGuild()) { return await message.util.reply( - `${util.emojis.error} You must either provide an server to provide info about or run this command in a server.` + `${emojis.error} You must either provide an server to provide info about or run this command in a server.` ); } @@ -54,7 +68,7 @@ export default class GuildInfoCommand extends BushCommand { if (typeof guild === 'string') { const preview = await client.fetchGuildPreview(`${args.guild}` as Snowflake).catch(() => undefined); if (preview) guild = preview; - else return await message.util.reply(`${util.emojis.error} That guild is not discoverable or does not exist.`); + else return await message.util.reply(`${emojis.error} That guild is not discoverable or does not exist.`); } assert(guild); @@ -63,7 +77,7 @@ export default class GuildInfoCommand extends BushCommand { await guild.fetch(); } - const guildInfoEmbed = new EmbedBuilder().setTitle(guild.name).setColor(util.colors.default); + const guildInfoEmbed = new EmbedBuilder().setTitle(guild.name).setColor(colors.default); if (guild.icon) guildInfoEmbed.setThumbnail(guild.iconURL({ size: 2048, extension: 'png' })); await this.generateAboutField(guildInfoEmbed, guild); @@ -79,16 +93,16 @@ export default class GuildInfoCommand extends BushCommand { private generateDescription(embed: EmbedBuilder, guild: Guild | GuildPreview) { const description: string[] = []; - const otherEmojis = client.consts.mappings.otherEmojis; + const otherEmojis = mappings.otherEmojis; - const verifiedGuilds = Object.values(client.consts.mappings.guilds); + 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}`]); } - const features = client.consts.mappings.features; + const features = mappings.features; const guildFeatures = guild.features.sort((a, b): number => { const aWeight = features[a]?.weight; const bWeight = features[b]?.weight; @@ -103,7 +117,7 @@ export default class GuildInfoCommand extends BushCommand { guildFeatures.forEach((feature) => { if (features[feature]?.emoji) description.push(`${features[feature].emoji}`); else if (features[feature]?.name) description.push(`\`${features[feature].name}\``); - else description.push(`\`${feature.charAt(0) + util.akairo.snakeToCamelCase(feature).substring(1)}\``); + else description.push(`\`${feature.charAt(0) + akairo.snakeToCamelCase(feature).substring(1)}\``); }); } @@ -125,12 +139,12 @@ export default class GuildInfoCommand extends BushCommand { ] as RTCRegion[]; guildAbout.push( - `**Owner:** ${util.discord.escapeMarkdown(guild.members.cache.get(guild.ownerId)?.user.tag ?? '¯\\_(ツ)_/¯')}`, - `**Created** ${util.timestampAndDelta(guild.createdAt, 'd')}`, - `**Members:** ${guild.memberCount.toLocaleString() ?? 0} (${util.emojis.onlineCircle} ${ + `**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 - }, ${util.emojis.offlineCircle} ${(guild.memberCount - (guild.approximatePresenceCount ?? 0)).toLocaleString() ?? 0})`, - `**Regions:** ${guildRegions.map((region) => client.consts.mappings.regions[region] || region).join(', ')}` + }, ${emojis.offlineCircle} ${(guild.memberCount - (guild.approximatePresenceCount ?? 0)).toLocaleString() ?? 0})`, + `**Regions:** ${guildRegions.map((region) => mappings.regions[region] || region).join(', ')}` ); if (guild.premiumSubscriptionCount) guildAbout.push(`**Boosts:** Level ${guild.premiumTier} with ${guild.premiumSubscriptionCount ?? 0} boosts`); @@ -144,9 +158,9 @@ export default class GuildInfoCommand extends BushCommand { if (guild.splash) guildAbout.push(`**Splash:** [link](${guild.splashURL({ size: 4096, extension: 'png' })})`); } else { guildAbout.push( - `**Members:** ${guild.approximateMemberCount?.toLocaleString() ?? 0} (${util.emojis.onlineCircle} ${ + `**Members:** ${guild.approximateMemberCount?.toLocaleString() ?? 0} (${emojis.onlineCircle} ${ guild.approximatePresenceCount?.toLocaleString() ?? 0 - }, ${util.emojis.offlineCircle} ${( + }, ${emojis.offlineCircle} ${( (guild.approximateMemberCount ?? 0) - (guild.approximatePresenceCount ?? 0) ).toLocaleString()})`, `**Emojis:** ${(guild as GuildPreview).emojis.size?.toLocaleString() ?? 0}`, @@ -173,7 +187,7 @@ export default class GuildInfoCommand extends BushCommand { ] as const ).map( (type) => - `${client.consts.mappings.otherEmojis[`Channel${type[0]}`]} ${guild.channels.cache + `${mappings.otherEmojis[`Channel${type[0]}`]} ${guild.channels.cache .filter((channel) => type[1].some((type) => channel.type === type)) .size.toLocaleString()}` ); diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index af44980..051fce5 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -1,4 +1,15 @@ -import { BushCommand, type ArgType, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + colors, + format, + invite, + prefix, + type ArgType, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ActionRowBuilder, @@ -48,7 +59,7 @@ export default class HelpCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -71,11 +82,11 @@ export default class HelpCommand extends BushCommand { } private helpAll(message: CommandMessage | SlashMessage, args: HelpArgs, row: ActionRowBuilder<ButtonBuilder>) { - const prefix = util.prefix(message); + const prefix_ = prefix(message); const embed = new EmbedBuilder() - .setColor(util.colors.default) + .setColor(colors.default) .setTimestamp() - .setFooter({ text: `For more information about a command use ${prefix}help <command>` }); + .setFooter({ text: `For more information about a command use ${prefix_}help <command>` }); for (const [, category] of this.handler.categories) { const categoryFilter = category.filter((command) => { if (command.pseudo) return false; @@ -100,7 +111,7 @@ export default class HelpCommand extends BushCommand { } private helpIndividual(message: CommandMessage | SlashMessage, row: ActionRowBuilder<ButtonBuilder>, command: BushCommand) { - const embed = new EmbedBuilder().setColor(util.colors.default).setTitle(`${command.id} Command`); + const embed = new EmbedBuilder().setColor(colors.default).setTitle(`${command.id} Command`); let description = `${command.description ?? '*This command does not have a description.*'}`; if (command.note) description += `\n\n${command.note}`; @@ -200,7 +211,7 @@ export default class HelpCommand extends BushCommand { if (command.restrictedGuilds?.length) restrictions.push( `__Restricted Servers__: ${command.restrictedGuilds - .map((g) => util.format.inlineCode(client.guilds.cache.find((g1) => g1.id === g)?.name ?? 'Unknown')) + .map((g) => format.inlineCode(client.guilds.cache.find((g1) => g1.id === g)?.name ?? 'Unknown')) .join(' ')}` ); if (restrictions.length) embed.addFields([{ name: '» Restrictions', value: restrictions.join('\n') }]); @@ -211,7 +222,7 @@ export default class HelpCommand extends BushCommand { const row = new ActionRowBuilder<ButtonBuilder>(); if (!client.config.isDevelopment && !client.guilds.cache.some((guild) => guild.ownerId === message.author.id)) { - row.addComponents([new ButtonBuilder({ style: ButtonStyle.Link, label: 'Invite Me', url: util.invite })]); + row.addComponents([new ButtonBuilder({ style: ButtonStyle.Link, label: 'Invite Me', url: invite(this.client) })]); } if (!client.guilds.cache.get(client.config.supportGuild.id)?.members.cache.has(message.author.id)) { row.addComponents([ diff --git a/src/commands/info/icon.ts b/src/commands/info/icon.ts index 9c9556b..e66f900 100644 --- a/src/commands/info/icon.ts +++ b/src/commands/info/icon.ts @@ -1,6 +1,6 @@ -import { BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, colors, type CommandMessage, type SlashMessage } from '#lib'; import assert from 'assert'; -import { EmbedBuilder, PermissionFlagsBits } from 'discord.js'; +import { EmbedBuilder, escapeMarkdown, PermissionFlagsBits } from 'discord.js'; export default class IconCommand extends BushCommand { public constructor() { @@ -10,7 +10,7 @@ export default class IconCommand extends BushCommand { description: "A command to get the server's icon", usage: ['icon'], examples: ['icon'], - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], channel: 'guild', slash: true @@ -22,14 +22,14 @@ export default class IconCommand extends BushCommand { const embed = new EmbedBuilder() .setTimestamp() - .setColor(util.colors.default) + .setColor(colors.default) .setImage( message.guild.iconURL({ size: 2048, extension: 'png' })! ) - .setTitle(util.discord.escapeMarkdown(message.guild.name)); + .setTitle(escapeMarkdown(message.guild.name)); await message.util.reply({ embeds: [embed] }); } } diff --git a/src/commands/info/links.ts b/src/commands/info/links.ts index 0d5bd15..a7ff30e 100644 --- a/src/commands/info/links.ts +++ b/src/commands/info/links.ts @@ -1,4 +1,4 @@ -import { BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, invite, type CommandMessage, type SlashMessage } from '#lib'; import assert from 'assert'; import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js'; import packageDotJSON from '../../../package.json' assert { type: 'json' }; @@ -13,7 +13,7 @@ export default class LinksCommand extends BushCommand { description: 'Sends bot links', usage: ['links'], examples: ['links'], - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [], slash: true }); @@ -22,7 +22,7 @@ export default class LinksCommand extends BushCommand { public override async exec(message: CommandMessage | SlashMessage) { const buttonRow = new ActionRowBuilder<ButtonBuilder>(); if (!client.config.isDevelopment || message.author.isOwner()) { - buttonRow.addComponents([new ButtonBuilder({ style: ButtonStyle.Link, label: 'Invite Me', url: util.invite })]); + buttonRow.addComponents([new ButtonBuilder({ style: ButtonStyle.Link, label: 'Invite Me', url: invite(this.client) })]); } buttonRow.addComponents([ new ButtonBuilder({ style: ButtonStyle.Link, label: 'Support Server', url: client.config.supportGuild.invite }), diff --git a/src/commands/info/ping.ts b/src/commands/info/ping.ts index ad7fdcc..060b1f6 100644 --- a/src/commands/info/ping.ts +++ b/src/commands/info/ping.ts @@ -1,4 +1,4 @@ -import { BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, colors, format, type CommandMessage, type SlashMessage } from '#lib'; import { EmbedBuilder, PermissionFlagsBits, type Message } from 'discord.js'; export default class PingCommand extends BushCommand { @@ -10,7 +10,7 @@ export default class PingCommand extends BushCommand { usage: ['ping'], examples: ['ping'], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -30,8 +30,8 @@ export default class PingCommand extends BushCommand { } private command(message: CommandMessage | SlashMessage, msgLatency: number) { - const botLatency = util.format.codeBlock(`${Math.round(msgLatency)}ms`); - const apiLatency = util.format.codeBlock(`${Math.round(message.client.ws.ping)}ms`); + const botLatency = format.codeBlock(`${Math.round(msgLatency)}ms`); + const apiLatency = format.codeBlock(`${Math.round(message.client.ws.ping)}ms`); const embed = new EmbedBuilder() .setTitle('Pong! 🏓') .addFields([ @@ -39,7 +39,7 @@ export default class PingCommand extends BushCommand { { name: 'API Latency', value: apiLatency, inline: true } ]) .setFooter({ text: message.author.username, iconURL: message.author.displayAvatarURL() }) - .setColor(util.colors.default) + .setColor(colors.default) .setTimestamp(); return message.util.reply({ content: null, diff --git a/src/commands/info/pronouns.ts b/src/commands/info/pronouns.ts index f916687..e87ca1f 100644 --- a/src/commands/info/pronouns.ts +++ b/src/commands/info/pronouns.ts @@ -1,5 +1,13 @@ -import { AllowedMentions, BushCommand, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; -import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + getPronounsOf, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; +import { ApplicationCommandOptionType, EmbedBuilder, escapeMarkdown, PermissionFlagsBits } from 'discord.js'; export default class PronounsCommand extends BushCommand { public constructor() { @@ -20,7 +28,7 @@ export default class PronounsCommand extends BushCommand { slashType: ApplicationCommandOptionType.User } ], - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], slash: true }); @@ -32,21 +40,19 @@ export default class PronounsCommand extends BushCommand { if (message.util.isSlashMessage(message)) await message.interaction.deferReply(); - const pronouns = await util.getPronounsOf(user); + const pronouns = await getPronounsOf(user); if (!pronouns) { return await message.util.reply({ - content: `${ - author ? 'You do' : `${util.discord.escapeMarkdown(user.tag)} does` - } not appear to have any pronouns set. Please${author ? '' : ' tell them to'} go to https://pronoundb.org/ and set ${ - author ? 'your' : 'their' - } pronouns.`, + content: `${author ? 'You do' : `${escapeMarkdown(user.tag)} does`} not appear to have any pronouns set. Please${ + author ? '' : ' tell them to' + } go to https://pronoundb.org/ and set ${author ? 'your' : 'their'} pronouns.`, allowedMentions: AllowedMentions.none() }); } else { return await message.util.reply({ embeds: [ new EmbedBuilder({ - title: `${author ? 'Your' : `${util.discord.escapeMarkdown(user.tag)}'s`} pronouns:`, + title: `${author ? 'Your' : `${escapeMarkdown(user.tag)}'s`} pronouns:`, description: pronouns, footer: { text: 'Data provided by https://pronoundb.org/' diff --git a/src/commands/info/snowflake.ts b/src/commands/info/snowflake.ts index e74756f..a28f4c5 100644 --- a/src/commands/info/snowflake.ts +++ b/src/commands/info/snowflake.ts @@ -1,9 +1,18 @@ -import { BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + colors, + timestamp, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import { stripIndent } from '#tags'; import { ApplicationCommandOptionType, ChannelType, EmbedBuilder, + escapeMarkdown, PermissionFlagsBits, SnowflakeUtil, type DeconstructedSnowflake, @@ -31,7 +40,7 @@ export default class SnowflakeCommand extends BushCommand { slashType: ApplicationCommandOptionType.String } ], - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], slash: true }); @@ -39,7 +48,7 @@ export default class SnowflakeCommand extends BushCommand { public override async exec(message: CommandMessage | SlashMessage, args: { snowflake: ArgType<'snowflake'> }) { const snowflake = `${args.snowflake}` as Snowflake; - const snowflakeEmbed = new EmbedBuilder().setTitle('Unknown :snowflake:').setColor(util.colors.default); + const snowflakeEmbed = new EmbedBuilder().setTitle('Unknown :snowflake:').setColor(colors.default); // Channel if (client.channels.cache.has(snowflake)) { @@ -47,13 +56,9 @@ export default class SnowflakeCommand extends BushCommand { const channelInfo = [`**Type:** ${BushChannelType[channel.type] ?? ChannelType[channel.type]}`]; if (channel.type === ChannelType.DM) { channelInfo.push( - `**Recipient:** ${util.discord.escapeMarkdown(channel.recipient?.tag ?? '¯\\_(ツ)_/¯')} (${ - channel.recipient?.id ?? '¯\\_(ツ)_/¯' - })` - ); - snowflakeEmbed.setTitle( - `:snowflake: DM with ${util.discord.escapeMarkdown(channel.recipient?.tag ?? '¯\\_(ツ)_/¯')} \`[Channel]\`` + `**Recipient:** ${escapeMarkdown(channel.recipient?.tag ?? '¯\\_(ツ)_/¯')} (${channel.recipient?.id ?? '¯\\_(ツ)_/¯'})` ); + snowflakeEmbed.setTitle(`:snowflake: DM with ${escapeMarkdown(channel.recipient?.tag ?? '¯\\_(ツ)_/¯')} \`[Channel]\``); } else if ( channel.type === ChannelType.GuildCategory || channel.type === ChannelType.GuildNews || @@ -63,10 +68,10 @@ export default class SnowflakeCommand extends BushCommand { channel.isThread() ) { channelInfo.push( - `**Channel Name:** <#${channel.id}> (${util.discord.escapeMarkdown(channel.name)})`, - `**Channel's Server:** ${util.discord.escapeMarkdown(channel.guild.name)} (${channel.guild.id})` + `**Channel Name:** <#${channel.id}> (${escapeMarkdown(channel.name)})`, + `**Channel's Server:** ${escapeMarkdown(channel.guild.name)} (${channel.guild.id})` ); - snowflakeEmbed.setTitle(`:snowflake: ${util.discord.escapeMarkdown(channel.name)} \`[Channel]\``); + snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(channel.name)} \`[Channel]\``); } snowflakeEmbed.addFields([{ name: '» Channel Info', value: channelInfo.join('\n') }]); } @@ -75,12 +80,12 @@ export default class SnowflakeCommand extends BushCommand { if (client.guilds.cache.has(snowflake)) { const guild: Guild = client.guilds.cache.get(snowflake)!; const guildInfo = stripIndent` - **Name:** ${util.discord.escapeMarkdown(guild.name)} - **Owner:** ${util.discord.escapeMarkdown(client.users.cache.get(guild.ownerId)?.tag ?? '¯\\_(ツ)_/¯')} (${guild.ownerId}) + **Name:** ${escapeMarkdown(guild.name)} + **Owner:** ${escapeMarkdown(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: ${util.discord.escapeMarkdown(guild.name)} \`[Server]\``); + snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(guild.name)} \`[Server]\``); } // User @@ -88,28 +93,28 @@ export default class SnowflakeCommand extends BushCommand { if (client.users.cache.has(snowflake) || fetchedUser) { const user: User = (client.users.cache.get(snowflake) ?? fetchedUser)!; const userInfo = stripIndent` - **Name:** <@${user.id}> (${util.discord.escapeMarkdown(user.tag)})`; + **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: ${util.discord.escapeMarkdown(user.tag)} \`[User]\``); + snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(user.tag)} \`[User]\``); } // Emoji if (client.emojis.cache.has(snowflake)) { const emoji = client.emojis.cache.get(snowflake)!; const emojiInfo = stripIndent` - **Name:** ${util.discord.escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} + **Name:** ${escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} **Animated:** ${emoji.animated}`; if (emoji.url) snowflakeEmbed.setThumbnail(emoji.url); snowflakeEmbed.addFields([{ name: '» Emoji Info', value: emojiInfo }]); - snowflakeEmbed.setTitle(`:snowflake: ${util.discord.escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} \`[Emoji]\``); + snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(emoji.name ?? '¯\\_(ツ)_/¯')} \`[Emoji]\``); } // Role if (message.guild && message.guild.roles.cache.has(snowflake)) { const role: Role = message.guild.roles.cache.get(snowflake)!; const roleInfo = stripIndent` - **Name:** <@&${role.id}> (${util.discord.escapeMarkdown(role.name)}) + **Name:** <@&${role.id}> (${escapeMarkdown(role.name)}) **Members:** ${role.members.size} **Hoisted:** ${role.hoist} **Managed:** ${role.managed} @@ -117,14 +122,14 @@ export default class SnowflakeCommand extends BushCommand { **Hex Color:** ${role.hexColor}`; if (role.color) snowflakeEmbed.setColor(role.color); snowflakeEmbed.addFields([{ name: '» Role Info', value: roleInfo }]); - snowflakeEmbed.setTitle(`:snowflake: ${util.discord.escapeMarkdown(role.name)} \`[Role]\``); + snowflakeEmbed.setTitle(`:snowflake: ${escapeMarkdown(role.name)} \`[Role]\``); } // SnowflakeInfo const deconstructedSnowflake: DeconstructedSnowflake = SnowflakeUtil.deconstruct(snowflake); const snowflakeInfo = stripIndent` **Timestamp:** ${deconstructedSnowflake.timestamp} - **Created:** ${util.timestamp(new Date(Number(deconstructedSnowflake.timestamp)))} + **Created:** ${timestamp(new Date(Number(deconstructedSnowflake.timestamp)))} **Worker ID:** ${deconstructedSnowflake.workerId} **Process ID:** ${deconstructedSnowflake.processId} **Increment:** ${deconstructedSnowflake.increment}`; diff --git a/src/commands/info/userInfo.ts b/src/commands/info/userInfo.ts index d617756..a39e28a 100644 --- a/src/commands/info/userInfo.ts +++ b/src/commands/info/userInfo.ts @@ -1,9 +1,26 @@ -import { BushCommand, Time, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + clientSendAndPermCheck, + colors, + emojis, + getPronounsOf, + getShared, + mappings, + oxford, + sleep, + Time, + timestampAndDelta, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import { ActivityType, ApplicationCommandOptionType, ApplicationFlagsBitField, EmbedBuilder, + escapeMarkdown, PermissionFlagsBits, TeamMemberMembershipState, UserFlags, @@ -26,7 +43,7 @@ export default class UserInfoCommand extends BushCommand { { id: 'user', description: 'The user you would like to find information about.', - type: util.arg.union('user', 'snowflake'), + type: Arg.union('user', 'snowflake'), readableType: 'user|snowflake', prompt: 'What user would you like to find information about?', retry: '{error} Choose a valid user to find information about.', @@ -35,7 +52,7 @@ export default class UserInfoCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -47,7 +64,7 @@ export default class UserInfoCommand extends BushCommand { : typeof args.user === 'object' ? args.user : await client.users.fetch(`${args.user}`).catch(() => undefined); - if (user === undefined) return message.util.reply(`${util.emojis.error} Invalid user.`); + if (user === undefined) return message.util.reply(`${emojis.error} Invalid user.`); const member = message.guild ? await message.guild.members.fetch(user.id).catch(() => undefined) : undefined; await user.fetch(true); // gets banner info and accent color @@ -58,23 +75,23 @@ export default class UserInfoCommand extends BushCommand { public static async makeUserInfoEmbed(user: User, member?: GuildMember, guild?: Guild | null) { const emojis = []; - const superUsers = util.getShared('superUsers'); + const superUsers = getShared('superUsers'); const userEmbed = new EmbedBuilder() - .setTitle(util.discord.escapeMarkdown(user.tag)) + .setTitle(escapeMarkdown(user.tag)) .setThumbnail(user.displayAvatarURL({ size: 2048, extension: 'png' })) .setTimestamp() .setFooter({ text: user.tag }) - .setColor(member?.displayColor ?? util.colors.default); + .setColor(member?.displayColor ?? colors.default); // Flags - if (client.config.owners.includes(user.id)) emojis.push(client.consts.mappings.otherEmojis.Developer); - if (superUsers.includes(user.id)) emojis.push(client.consts.mappings.otherEmojis.Superuser); + if (client.config.owners.includes(user.id)) emojis.push(mappings.otherEmojis.Developer); + if (superUsers.includes(user.id)) emojis.push(mappings.otherEmojis.Superuser); const flags = user.flags?.toArray(); if (flags) { flags.forEach((f) => { - if (client.consts.mappings.userFlags[f] !== undefined) { - emojis.push(client.consts.mappings.userFlags[f]); + if (mappings.userFlags[f] !== undefined) { + emojis.push(mappings.userFlags[f]); } else emojis.push(`\`${f}\``); }); } @@ -82,18 +99,18 @@ export default class UserInfoCommand extends BushCommand { // Since discord bald I just guess if someone has nitro if ( Number(user.discriminator) < 10 || - client.consts.mappings.maybeNitroDiscrims.includes(user.discriminator) || + mappings.maybeNitroDiscrims.includes(user.discriminator) || user.displayAvatarURL()?.endsWith('.gif') || user.flags?.has(UserFlags.Partner) || user.flags?.has(UserFlags.Staff) || member?.avatar // server avatar ) { - emojis.push(client.consts.mappings.otherEmojis.Nitro); + emojis.push(mappings.otherEmojis.Nitro); } - if (guild?.ownerId == user.id) emojis.push(client.consts.mappings.otherEmojis.Owner); - else if (member?.permissions.has(PermissionFlagsBits.Administrator)) emojis.push(client.consts.mappings.otherEmojis.Admin); - if (member?.premiumSinceTimestamp) emojis.push(client.consts.mappings.otherEmojis.Booster); + if (guild?.ownerId == user.id) emojis.push(mappings.otherEmojis.Owner); + else if (member?.permissions.has(PermissionFlagsBits.Administrator)) emojis.push(mappings.otherEmojis.Admin); + if (member?.premiumSinceTimestamp) emojis.push(mappings.otherEmojis.Booster); await this.generateGeneralInfoField(userEmbed, user); @@ -121,12 +138,12 @@ export default class UserInfoCommand extends BushCommand { const generalInfo = [ `**Mention:** <@${user.id}>`, `**ID:** ${user.id}`, - `**Created:** ${util.timestampAndDelta(user.createdAt, 'd')}` + `**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([util.getPronounsOf(user), util.sleep(2 * Time.Second)]); // cut off request after 2 seconds + const pronouns = await Promise.race([getPronounsOf(user), sleep(2 * Time.Second)]); // cut off request after 2 seconds if (pronouns && typeof pronouns === 'string' && pronouns !== 'Unspecified') generalInfo.push(`**Pronouns:** ${pronouns}`); @@ -140,21 +157,21 @@ export default class UserInfoCommand extends BushCommand { const serverUserInfo = []; if (member.joinedTimestamp) serverUserInfo.push( - `**${member.guild!.ownerId == member.user.id ? 'Created Server' : 'Joined'}:** ${util.timestampAndDelta( + `**${member.guild!.ownerId == member.user.id ? 'Created Server' : 'Joined'}:** ${timestampAndDelta( member.joinedAt!, 'd' )}` ); - if (member.premiumSince) serverUserInfo.push(`**Booster Since:** ${util.timestampAndDelta(member.premiumSince, '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 == '322862723090219008' && member.guild?.id == client.consts.mappings.guilds.bush) + if (member.user.id == '322862723090219008' && member.guild?.id == mappings.guilds.bush) serverUserInfo.push(`**General Deletions:** 1⅓`); if ( (['384620942577369088', '496409778822709251'] as const).includes(member.user.id) && - member.guild.id == client.consts.mappings.guilds.bush + member.guild.id == mappings.guilds.bush ) serverUserInfo.push(`**General Deletions:** ⅓`); - if (member?.nickname) serverUserInfo.push(`**Nickname:** ${util.discord.escapeMarkdown(member?.nickname)}`); + if (member?.nickname) serverUserInfo.push(`**Nickname:** ${escapeMarkdown(member?.nickname)}`); if (serverUserInfo.length) embed.addFields([{ name: title, value: serverUserInfo.join('\n') }]); } @@ -179,10 +196,10 @@ export default class UserInfoCommand extends BushCommand { const presenceInfo = []; if (member?.presence.status) presenceInfo.push(`**Status:** ${member.presence.status}`); if (devices && devices.length) - presenceInfo.push(`**${devices.length - 1 ? 'Devices' : 'Device'}:** ${util.oxford(devices, 'and', '')}`); + presenceInfo.push(`**${devices.length - 1 ? 'Devices' : 'Device'}:** ${oxford(devices, 'and', '')}`); if (activitiesNames.length) - presenceInfo.push(`**Activit${activitiesNames.length - 1 ? 'ies' : 'y'}:** ${util.oxford(activitiesNames, 'and', '')}`); - if (customStatus && customStatus.length) presenceInfo.push(`**Custom Status:** ${util.discord.escapeMarkdown(customStatus)}`); + presenceInfo.push(`**Activit${activitiesNames.length - 1 ? 'ies' : 'y'}:** ${oxford(activitiesNames, 'and', '')}`); + if (customStatus && customStatus.length) presenceInfo.push(`**Custom Status:** ${escapeMarkdown(customStatus)}`); embed.addFields([{ name: title, value: presenceInfo.join('\n') }]); enum statusEmojis { @@ -229,8 +246,8 @@ export default class UserInfoCommand extends BushCommand { perms.push('`Administrator`'); } else if (member?.permissions.toArray().length) { member.permissions.toArray().forEach((permission) => { - if (client.consts.mappings.permissions[permission]?.important) { - perms.push(`\`${client.consts.mappings.permissions[permission].name}\``); + if (mappings.permissions[permission]?.important) { + perms.push(`\`${mappings.permissions[permission].name}\``); } }); } @@ -247,14 +264,14 @@ export default class UserInfoCommand extends BushCommand { const flags = new ApplicationFlagsBitField(applicationInfo.flags); const intent = (check: ApplicationFlagsString, warn: ApplicationFlagsString) => { - if (flags.has(check)) return util.emojis.check; - if (flags.has(warn)) return util.emojis.warn; - return util.emojis.cross; + if (flags.has(check)) return emojis.check; + if (flags.has(warn)) return emojis.warn; + return emojis.cross; }; const botInfo = [ `**Publicity:** ${applicationInfo.bot_public ? 'Public' : 'Private'}`, - `**Requires Code Grant:** ${applicationInfo.bot_require_code_grant ? util.emojis.check : util.emojis.cross}`, + `**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')}` diff --git a/src/commands/leveling/leaderboard.ts b/src/commands/leveling/leaderboard.ts index 040ed4a..d81d88b 100644 --- a/src/commands/leveling/leaderboard.ts +++ b/src/commands/leveling/leaderboard.ts @@ -1,4 +1,15 @@ -import { BushCommand, ButtonPaginator, Level, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + BushCommand, + ButtonPaginator, + chunk, + clientSendAndPermCheck, + emojis, + Level, + prefix, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; @@ -23,7 +34,7 @@ export default class LeaderboardCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -33,9 +44,9 @@ export default class LeaderboardCommand extends BushCommand { if (!(await message.guild.hasFeature('leveling'))) return await message.util.reply( - `${util.emojis.error} This command can only be run in servers with the leveling feature enabled.${ + `${emojis.error} This command can only be run in servers with the leveling feature enabled.${ message.member?.permissions.has(PermissionFlagsBits.ManageGuild) - ? ` You can toggle features using the \`${util.prefix(message)}features\` command.` + ? ` You can toggle features using the \`${prefix(message)}features\` command.` : '' }` ); @@ -44,7 +55,7 @@ export default class LeaderboardCommand extends BushCommand { const mappedRanks = ranks.map( (val, index) => `\`${index + 1}\` <@${val.user}> - Level ${val.level} (${val.xp.toLocaleString()} xp)` ); - const chunked = util.chunk(mappedRanks, 25); + const chunked = chunk(mappedRanks, 25); const embeds = chunked.map((c) => new EmbedBuilder().setTitle(`${message.guild.name}'s Leaderboard`).setDescription(c.join('\n')) ); diff --git a/src/commands/leveling/level.ts b/src/commands/leveling/level.ts index 34a839a..df3e5b2 100644 --- a/src/commands/leveling/level.ts +++ b/src/commands/leveling/level.ts @@ -2,7 +2,10 @@ import { AllowedMentions, BushCommand, CanvasProgressBar, + clientSendAndPermCheck, + emojis, Level, + prefix, type CommandMessage, type OptArgType, type SlashMessage @@ -39,7 +42,7 @@ export default class LevelCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -49,9 +52,9 @@ export default class LevelCommand extends BushCommand { if (!(await message.guild.hasFeature('leveling'))) return await message.util.reply( - `${util.emojis.error} This command can only be run in servers with the leveling feature enabled.${ + `${emojis.error} This command can only be run in servers with the leveling feature enabled.${ message.member?.permissions.has(PermissionFlagsBits.ManageGuild) - ? ` You can toggle features using the \`${util.prefix(message)}features\` command.` + ? ` You can toggle features using the \`${prefix(message)}features\` command.` : '' }` ); @@ -63,7 +66,7 @@ export default class LevelCommand extends BushCommand { } catch (e) { if (e instanceof Error && e.message === 'User does not have a level') { return await message.util.reply({ - content: `${util.emojis.error} ${user} does not have a level.`, + content: `${emojis.error} ${user} does not have a level.`, allowedMentions: AllowedMentions.none() }); } else throw e; diff --git a/src/commands/leveling/levelRoles.ts b/src/commands/leveling/levelRoles.ts index afa4ab6..470cf58 100644 --- a/src/commands/leveling/levelRoles.ts +++ b/src/commands/leveling/levelRoles.ts @@ -1,4 +1,13 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + emojis, + type ArgType, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, PermissionFlagsBits } from 'discord.js'; @@ -33,7 +42,7 @@ export default class LevelRolesCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles]), userPermissions: [PermissionFlagsBits.ManageGuild, PermissionFlagsBits.ManageRoles] }); } @@ -46,20 +55,20 @@ export default class LevelRolesCommand extends BushCommand { assert(message.member); if (!(await message.guild.hasFeature('leveling'))) { - return await reply(`${util.emojis.error} This command can only be run in servers with the leveling feature enabled.`); + return await reply(`${emojis.error} This command can only be run in servers with the leveling feature enabled.`); } - if (args.level < 1) return await reply(`${util.emojis.error} You cannot set a level role less than **1**.`); + if (args.level < 1) return await reply(`${emojis.error} You cannot set a level role less than **1**.`); if (args.role) { if (args.role.managed) - return await reply(`${util.emojis.error} You cannot set <@${args.role.id}> as a level role since it is managed.`); + return await reply(`${emojis.error} You cannot set <@${args.role.id}> as a level role since it is managed.`); else if (args.role.id === message.guild.id) - return await reply(`${util.emojis.error} You cannot set the @everyone role as a level role.`); + return await reply(`${emojis.error} You cannot set the @everyone role as a level role.`); else if (args.role.comparePositionTo(message.member.roles.highest) >= 0) - return await reply(`${util.emojis.error} <@${args.role.id}> is higher or equal to your highest role.`); + return await reply(`${emojis.error} <@${args.role.id}> is higher or equal to your highest role.`); else if (args.role.comparePositionTo(message.guild.members.me!.roles.highest) >= 0) - return await reply(`${util.emojis.error} <@${args.role.id}> is higher or equal to my highest role.`); + return await reply(`${emojis.error} <@${args.role.id}> is higher or equal to my highest role.`); } const oldRoles = Object.freeze(await message.guild.getSetting('levelRoles')); @@ -74,17 +83,17 @@ export default class LevelRolesCommand extends BushCommand { const success = await message.guild.setSetting('levelRoles', newRoles, message.member).catch(() => false); - if (!success) return await reply(`${util.emojis.error} An error occurred while setting the level roles.`); + if (!success) return await reply(`${emojis.error} An error occurred while setting the level roles.`); if (!oldRoles[args.level] && newRoles[args.level]) { - return await reply(`${util.emojis.success} The level role for **${args.level}** is now <@&${newRoles[args.level]}>.`); + return await reply(`${emojis.success} The level role for **${args.level}** is now <@&${newRoles[args.level]}>.`); } else if (oldRoles[args.level] && !newRoles[args.level]) { return await reply( - `${util.emojis.success} The level role for **${args.level}** was <@&${oldRoles[args.level]}> but is now disabled.` + `${emojis.success} The level role for **${args.level}** was <@&${oldRoles[args.level]}> but is now disabled.` ); } else if (oldRoles[args.level] && newRoles[args.level]) { return await reply( - `${util.emojis.success} The level role for **${args.level}** has been updated from <@&${oldRoles[args.level]}> to <@&${ + `${emojis.success} The level role for **${args.level}** has been updated from <@&${oldRoles[args.level]}> to <@&${ newRoles[args.level] }>.` ); diff --git a/src/commands/leveling/setLevel.ts b/src/commands/leveling/setLevel.ts index 8abdb57..b1d9516 100644 --- a/src/commands/leveling/setLevel.ts +++ b/src/commands/leveling/setLevel.ts @@ -1,4 +1,14 @@ -import { AllowedMentions, BushCommand, Level, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + emojis, + format, + Level, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, PermissionFlagsBits } from 'discord.js'; @@ -30,7 +40,7 @@ export default class SetLevelCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [PermissionFlagsBits.Administrator] }); } @@ -43,9 +53,9 @@ export default class SetLevelCommand extends BushCommand { assert(user.id); if (isNaN(level) || !Number.isInteger(level)) - return await message.util.reply(`${util.emojis.error} Provide a valid number to set the user's level to.`); + 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(`${util.emojis.error} You cannot set a level higher than **6,553**.`); + return await message.util.reply(`${emojis.error} You cannot set a level higher than **6,553**.`); const [levelEntry] = await Level.findOrBuild({ where: { user: user.id, guild: message.guild.id }, @@ -53,7 +63,7 @@ export default class SetLevelCommand extends BushCommand { }); await levelEntry.update({ xp: Level.convertLevelToXp(level), user: user.id, guild: message.guild.id }); return await message.util.send({ - content: `Successfully set level of <@${user.id}> to ${util.format.input(level.toLocaleString())} (${util.format.input( + content: `Successfully set level of <@${user.id}> to ${format.input(level.toLocaleString())} (${format.input( levelEntry.xp.toLocaleString() )} XP)`, allowedMentions: AllowedMentions.none() diff --git a/src/commands/leveling/setXp.ts b/src/commands/leveling/setXp.ts index 60e0b94..96b3ad7 100644 --- a/src/commands/leveling/setXp.ts +++ b/src/commands/leveling/setXp.ts @@ -1,4 +1,14 @@ -import { AllowedMentions, BushCommand, Level, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + emojis, + format, + Level, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, PermissionFlagsBits } from 'discord.js'; @@ -31,7 +41,7 @@ export default class SetXpCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [PermissionFlagsBits.Administrator] }); } @@ -43,10 +53,10 @@ export default class SetXpCommand extends BushCommand { assert(message.inGuild()); assert(user.id); - if (isNaN(xp)) return await message.util.reply(`${util.emojis.error} Provide a valid number.`); + if (isNaN(xp)) return await message.util.reply(`${emojis.error} Provide a valid number.`); if (xp > 2147483647 || xp < 0) return await message.util.reply( - `${util.emojis.error} Provide an positive integer under **2,147,483,647** to set the user's xp to.` + `${emojis.error} Provide an positive integer under **2,147,483,647** to set the user's xp to.` ); const [levelEntry] = await Level.findOrBuild({ @@ -57,9 +67,9 @@ export default class SetXpCommand extends BushCommand { await levelEntry.update({ xp: xp, user: user.id, guild: message.guild.id }); return await message.util.send({ - content: `Successfully set <@${user.id}>'s xp to ${util.format.input( - levelEntry.xp.toLocaleString() - )} (level ${util.format.input(Level.convertXpToLevel(levelEntry.xp).toLocaleString())}).`, + content: `Successfully set <@${user.id}>'s xp to ${format.input(levelEntry.xp.toLocaleString())} (level ${format.input( + Level.convertXpToLevel(levelEntry.xp).toLocaleString() + )}).`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/moderation/_activePunishments.ts b/src/commands/moderation/_activePunishments.ts index 92b4242..80cecf2 100644 --- a/src/commands/moderation/_activePunishments.ts +++ b/src/commands/moderation/_activePunishments.ts @@ -37,8 +37,8 @@ // slash: true, // channel: 'guild', // hidden: true, -// clientPermissions: (m) => util.clientSendAndPermCheck(m), -// userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) +// clientPermissions: (m) => clientSendAndPermCheck(m), +// userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) // }); // } @@ -66,7 +66,7 @@ // where.type = { [Op.or]: ['PERM_PUNISHMENT_ROLE', 'TEMP_PUNISHMENT_ROLE', 'REMOVE_PUNISHMENT_ROLE'] }; // break; // default: -// return message.util.reply(`${util.emojis.error} You supplied an invalid case type to filter by.`); +// return message.util.reply(`${emojis.error} You supplied an invalid case type to filter by.`); // } // } diff --git a/src/commands/moderation/ban.ts b/src/commands/moderation/ban.ts index f4bd52b..e301fb2 100644 --- a/src/commands/moderation/ban.ts +++ b/src/commands/moderation/ban.ts @@ -1,8 +1,13 @@ import { AllowedMentions, + Arg, banResponse, BushCommand, + castDurationContent, + emojis, + format, Moderation, + resolveNonCachedUser, type ArgType, type CommandMessage, type OptArgType, @@ -23,7 +28,7 @@ export default class BanCommand extends BushCommand { { id: 'user', description: 'The user that will be banned.', - type: util.arg.union('user', 'snowflake'), + type: Arg.union('user', 'snowflake'), readableType: 'user|snowflake', prompt: 'What user would you like to ban?', retry: '{error} Choose a valid user to ban.', @@ -46,7 +51,7 @@ export default class BanCommand extends BushCommand { match: 'option', prompt: "How many days of the user's messages would you like to delete?", retry: '{error} Choose between 0 and 7 days to delete messages from the user for.', - type: util.arg.range('integer', 0, 7, true), + type: Arg.range('integer', 0, 7, true), readableType: 'integer [0, 7]', optional: true, slashType: ApplicationCommandOptionType.Integer, @@ -82,12 +87,12 @@ export default class BanCommand extends BushCommand { assert(message.inGuild()); assert(message.member); - const { duration, content } = await util.castDurationContent(args.reason_and_duration, message); + const { duration, content } = await castDurationContent(args.reason_and_duration, message); args.days ??= message.util.parsed?.alias === 'dban' ? 1 : 0; const member = message.guild.members.cache.get(typeof args.user === 'string' ? args.user : args.user.id); - const user = member?.user ?? (await util.resolveNonCachedUser(typeof args.user === 'string' ? args.user : args.user.id)); - if (!user) return message.util.reply(`${util.emojis.error} Invalid user.`); + const user = member?.user ?? (await resolveNonCachedUser(typeof args.user === 'string' ? args.user : args.user.id)); + 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; @@ -97,7 +102,7 @@ export default class BanCommand extends BushCommand { } if (!Number.isInteger(args.days) || args.days! < 0 || args.days! > 7) { - return message.util.reply(`${util.emojis.error} The delete days must be an integer between 0 and 7.`); + return message.util.reply(`${emojis.error} The delete days must be an integer between 0 and 7.`); } const opts = { reason: content, moderator: message.member, duration: duration, deleteDays: args.days }; @@ -105,24 +110,24 @@ export default class BanCommand extends BushCommand { const responseCode = member ? await member.bushBan(opts) : await message.guild.bushBan({ user, ...opts }); const responseMessage = (): string => { - const victim = util.format.input(user.tag); + const victim = format.input(user.tag); switch (responseCode) { case banResponse.ALREADY_BANNED: - return `${util.emojis.error} ${victim} is already banned.`; + return `${emojis.error} ${victim} is already banned.`; case banResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} Could not ban ${victim} because I am missing the **Ban Members** permission.`; + return `${emojis.error} Could not ban ${victim} because I am missing the **Ban Members** permission.`; case banResponse.ACTION_ERROR: - return `${util.emojis.error} An error occurred while trying to ban ${victim}.`; + return `${emojis.error} An error occurred while trying to ban ${victim}.`; case banResponse.PUNISHMENT_ENTRY_ADD_ERROR: - return `${util.emojis.error} While banning ${victim}, there was an error creating a ban entry, please report this to my developers.`; + return `${emojis.error} While banning ${victim}, there was an error creating a ban entry, please report this to my developers.`; case banResponse.MODLOG_ERROR: - return `${util.emojis.error} While banning ${victim}, there was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} While banning ${victim}, there was an error creating a modlog entry, please report this to my developers.`; case banResponse.DM_ERROR: - return `${util.emojis.warn} Banned ${victim} however I could not send them a dm.`; + return `${emojis.warn} Banned ${victim} however I could not send them a dm.`; case banResponse.SUCCESS: - return `${util.emojis.success} Successfully banned ${victim}.`; + return `${emojis.success} Successfully banned ${victim}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/block.ts b/src/commands/moderation/block.ts index 16beb6f..fc93fb1 100644 --- a/src/commands/moderation/block.ts +++ b/src/commands/moderation/block.ts @@ -2,7 +2,12 @@ import { AllowedMentions, blockResponse, BushCommand, + castDurationContent, + clientSendAndPermCheck, + emojis, + format, Moderation, + userGuildPermCheck, type ArgType, type CommandMessage, type OptArgType, @@ -51,8 +56,8 @@ export default class BlockCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]), lock: 'channel' }); } @@ -70,13 +75,13 @@ export default class BlockCommand extends BushCommand { assert(message.channel); if (!message.channel.isTextBased()) - return message.util.send(`${util.emojis.error} This command can only be used in text based channels.`); + return message.util.send(`${emojis.error} This command can only be used in text based channels.`); - const { duration, content } = await util.castDurationContent(args.reason_and_duration, message); + const { duration, content } = await castDurationContent(args.reason_and_duration, message); const member = await message.guild.members.fetch(args.user.id).catch(() => null); if (!member) - return await message.util.reply(`${util.emojis.error} The user you selected is not in the server or is not a valid user.`); + 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); @@ -93,24 +98,24 @@ export default class BlockCommand extends BushCommand { }); const responseMessage = (): string => { - const victim = util.format.input(member.user.tag); + const victim = format.input(member.user.tag); switch (responseCode) { case blockResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} Could not block ${victim} because I am missing the **Manage Channel** permission.`; + return `${emojis.error} Could not block ${victim} because I am missing the **Manage Channel** permission.`; case blockResponse.INVALID_CHANNEL: - return `${util.emojis.error} Could not block ${victim}, you can only block users in text or thread channels.`; + return `${emojis.error} Could not block ${victim}, you can only block users in text or thread channels.`; case blockResponse.ACTION_ERROR: - return `${util.emojis.error} An unknown error occurred while trying to block ${victim}.`; + return `${emojis.error} An unknown error occurred while trying to block ${victim}.`; case blockResponse.MODLOG_ERROR: - return `${util.emojis.error} There was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a modlog entry, please report this to my developers.`; case blockResponse.PUNISHMENT_ENTRY_ADD_ERROR: - return `${util.emojis.error} There was an error creating a punishment entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a punishment entry, please report this to my developers.`; case blockResponse.DM_ERROR: - return `${util.emojis.warn} Blocked ${victim} however I could not send them a dm.`; + return `${emojis.warn} Blocked ${victim} however I could not send them a dm.`; case blockResponse.SUCCESS: - return `${util.emojis.success} Successfully blocked ${victim}.`; + return `${emojis.success} Successfully blocked ${victim}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/evidence.ts b/src/commands/moderation/evidence.ts index f1fac0d..3c9e726 100644 --- a/src/commands/moderation/evidence.ts +++ b/src/commands/moderation/evidence.ts @@ -1,4 +1,16 @@ -import { BushCommand, ModLog, OptArgType, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + emojis, + format, + ModLog, + OptArgType, + regex, + userGuildPermCheck, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { Argument, ArgumentGeneratorReturn } from 'discord-akairo'; import { ApplicationCommandOptionType, PermissionFlagsBits, type Message } from 'discord.js'; @@ -42,8 +54,8 @@ export default class EvidenceCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) + clientPermissions: (m) => clientSendAndPermCheck(m), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) }); } @@ -89,18 +101,18 @@ export default class EvidenceCommand extends BushCommand { assert(message.inGuild()); if (message.interaction && !caseID && !user) - return message.util.send(`${util.emojis.error} You must provide either a user or a case ID.`); + return message.util.send(`${emojis.error} You must provide either a user or a case ID.`); const entry = messageCommandTarget - ? util.consts.regex.snowflake.test(messageCommandTarget) + ? regex.snowflake.test(messageCommandTarget) ? await ModLog.findOne({ where: { user: messageCommandTarget }, order: [['createdAt', 'DESC']] }) : await ModLog.findByPk(messageCommandTarget) : caseID ? await ModLog.findByPk(caseID) : await ModLog.findOne({ where: { user: user!.id }, order: [['createdAt', 'DESC']] }); - if (!entry || entry.pseudo) return message.util.send(`${util.emojis.error} Invalid modlog entry.`); - if (entry.guild !== message.guild.id) return message.util.reply(`${util.emojis.error} This modlog is from another server.`); + if (!entry || entry.pseudo) return message.util.send(`${emojis.error} Invalid modlog entry.`); + if (entry.guild !== message.guild.id) return message.util.reply(`${emojis.error} This modlog is from another server.`); const oldEntry = entry.evidence; @@ -112,14 +124,12 @@ export default class EvidenceCommand extends BushCommand { client.emit('bushUpdateModlog', message.member!, entry.id, 'evidence', oldEntry, entry.evidence); - return message.util.reply( - `${util.emojis.success} Successfully updated the evidence for case ${util.format.input(entry.id)}.` - ); + return message.util.reply(`${emojis.success} Successfully updated the evidence for case ${format.input(entry.id)}.`); } public static getEvidence(message: CommandMessage | SlashMessage, evidenceArg: OptArgType<'string'>): null | string { if (evidenceArg && (message as Message).attachments?.size) { - void message.util.reply(`${util.emojis.error} Please either attach an image or a reason not both.`); + void message.util.reply(`${emojis.error} Please either attach an image or a reason not both.`); return null; } @@ -129,7 +139,7 @@ export default class EvidenceCommand extends BushCommand { ? (message as Message).attachments.first()?.url : undefined; if (!_evidence) { - void message.util.reply(`${util.emojis.error} You must provide evidence for this modlog.`); + void message.util.reply(`${emojis.error} You must provide evidence for this modlog.`); return null; } diff --git a/src/commands/moderation/hideCase.ts b/src/commands/moderation/hideCase.ts index fc5baf4..0cc3de4 100644 --- a/src/commands/moderation/hideCase.ts +++ b/src/commands/moderation/hideCase.ts @@ -1,4 +1,13 @@ -import { BushCommand, ModLog, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + emojis, + format, + ModLog, + userGuildPermCheck, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, PermissionFlagsBits } from 'discord.js'; @@ -21,8 +30,8 @@ export default class HideCaseCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]), + clientPermissions: (m) => clientSendAndPermCheck(m), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]), channel: 'guild' }); } @@ -31,8 +40,8 @@ export default class HideCaseCommand extends BushCommand { assert(message.inGuild()); const entry = await ModLog.findByPk(caseID); - if (!entry || entry.pseudo) return message.util.send(`${util.emojis.error} Invalid entry.`); - if (entry.guild !== message.guild.id) return message.util.reply(`${util.emojis.error} This modlog is from another server.`); + if (!entry || entry.pseudo) return message.util.send(`${emojis.error} Invalid entry.`); + if (entry.guild !== message.guild.id) return message.util.reply(`${emojis.error} This modlog is from another server.`); const action = entry.hidden ? 'no longer hidden' : 'now hidden'; const oldEntry = entry.hidden; entry.hidden = !entry.hidden; @@ -40,6 +49,6 @@ export default class HideCaseCommand extends BushCommand { client.emit('bushUpdateModlog', message.member!, entry.id, 'hidden', oldEntry, entry.hidden); - return await message.util.reply(`${util.emojis.success} CaseID ${util.format.input(caseID)} is ${action}.`); + return await message.util.reply(`${emojis.success} CaseID ${format.input(caseID)} is ${action}.`); } } diff --git a/src/commands/moderation/kick.ts b/src/commands/moderation/kick.ts index a9a0336..bf079f3 100644 --- a/src/commands/moderation/kick.ts +++ b/src/commands/moderation/kick.ts @@ -1,6 +1,9 @@ import { AllowedMentions, BushCommand, + clientSendAndPermCheck, + emojis, + format, kickResponse, Moderation, type ArgType, @@ -50,7 +53,7 @@ export default class KickCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.KickMembers]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.KickMembers]), userPermissions: [PermissionFlagsBits.KickMembers] }); } @@ -65,7 +68,7 @@ export default class KickCommand extends BushCommand { const member = await message.guild.members.fetch(user.id); if (!member) - return await message.util.reply(`${util.emojis.error} The user you selected is not in the server or is not a valid user.`); + 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); @@ -79,20 +82,20 @@ export default class KickCommand extends BushCommand { }); const responseMessage = (): string => { - const victim = util.format.input(member.user.tag); + const victim = format.input(member.user.tag); switch (responseCode) { case kickResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} Could not kick ${victim} because I am missing the **Kick Members** permission.`; + return `${emojis.error} Could not kick ${victim} because I am missing the **Kick Members** permission.`; case kickResponse.ACTION_ERROR: - return `${util.emojis.error} An error occurred while trying to kick ${victim}.`; + return `${emojis.error} An error occurred while trying to kick ${victim}.`; case kickResponse.MODLOG_ERROR: - return `${util.emojis.error} While muting ${victim}, there was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} While muting ${victim}, there was an error creating a modlog entry, please report this to my developers.`; case kickResponse.DM_ERROR: - return `${util.emojis.warn} Kicked ${victim} however I could not send them a dm.`; + return `${emojis.warn} Kicked ${victim} however I could not send them a dm.`; case kickResponse.SUCCESS: - return `${util.emojis.success} Successfully kicked ${victim}.`; + return `${emojis.success} Successfully kicked ${victim}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/lockdown.ts b/src/commands/moderation/lockdown.ts index 7d8211c..76d61d0 100644 --- a/src/commands/moderation/lockdown.ts +++ b/src/commands/moderation/lockdown.ts @@ -1,7 +1,12 @@ import { AllowedMentions, + Arg, BushCommand, + clientSendAndPermCheck, + colors, ConfirmationPrompt, + emojis, + format, type ArgType, type CommandMessage, type OptArgType, @@ -31,7 +36,7 @@ export default class LockdownCommand extends BushCommand { { id: 'channel', description: 'Specify a different channel to lockdown instead of the one you trigger the command in.', - type: util.arg.union('textChannel', 'newsChannel', 'threadChannel', 'voiceChannel'), + type: Arg.union('textChannel', 'newsChannel', 'threadChannel', 'voiceChannel'), prompt: 'What channel would you like to lockdown?', slashType: ApplicationCommandOptionType.Channel, channelTypes: [ @@ -65,7 +70,7 @@ export default class LockdownCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), userPermissions: [PermissionFlagsBits.ManageChannels], lock: 'channel' }); @@ -95,7 +100,7 @@ export default class LockdownCommand extends BushCommand { if (message.util.isSlashMessage(message)) await message.interaction.deferReply(); if (args.channel && args.all) - return await message.util.reply(`${util.emojis.error} You can't specify a channel and set all to true at the same time.`); + return await message.util.reply(`${emojis.error} You can't specify a channel and set all to true at the same time.`); const channel = args.channel ?? message.channel; @@ -108,14 +113,14 @@ export default class LockdownCommand extends BushCommand { ) ) return await message.util.reply( - `${util.emojis.error} You can only ${action} text channels, news channels, and thread channels.` + `${emojis.error} You can only ${action} text channels, news channels, and thread channels.` ); if (args.all) { const confirmation = await ConfirmationPrompt.send(message, { content: `Are you sure you want to ${action} all channels?` }); - if (!confirmation) return message.util.sendNew(`${util.emojis.error} Lockdown cancelled.`); + if (!confirmation) return message.util.sendNew(`${emojis.error} Lockdown cancelled.`); } const response = await message.guild.lockdown({ @@ -128,33 +133,33 @@ export default class LockdownCommand extends BushCommand { if (response instanceof Collection) { return await message.util.sendNew({ - content: `${util.emojis.error} The following channels failed to ${action}:`, + content: `${emojis.error} The following channels failed to ${action}:`, embeds: [ { description: response.map((e, c) => `<#${c}> : ${e.message}`).join('\n'), - color: util.colors.warn + color: colors.warn } ] }); } else { let messageResponse; if (response === 'all not chosen and no channel specified') { - messageResponse = `${util.emojis.error} You must specify a channel to ${action}.`; + messageResponse = `${emojis.error} You must specify a channel to ${action}.`; } else if (response.startsWith('invalid channel configured: ')) { const channels = response.replace('invalid channel configured: ', ''); const actionFormatted = `${action.replace('down', '')}ed`; - messageResponse = `${util.emojis.error} Some of the channels configured to be ${actionFormatted} cannot be resolved: ${channels}}`; + messageResponse = `${emojis.error} Some of the channels configured to be ${actionFormatted} cannot be resolved: ${channels}}`; } else if (response === 'no channels configured') { - messageResponse = `${util.emojis.error} The all option is selected but there are no channels configured to be locked down.`; + messageResponse = `${emojis.error} The all option is selected but there are no channels configured to be locked down.`; } else if (response === 'moderator not found') { - messageResponse = `${util.emojis.error} For some reason I could not resolve you?`; + messageResponse = `${emojis.error} For some reason I could not resolve you?`; } else if (response.startsWith('success: ')) { const num = Number.parseInt(response.replace('success: ', '')); - messageResponse = `${util.emojis.success} Successfully ${ + messageResponse = `${emojis.success} Successfully ${ action === 'lockdown' ? 'locked down' : 'unlocked' } **${num}** channel${num > 0 ? 's' : ''}.`; } else { - return `${util.emojis.error} An error occurred: ${util.format.input(response)}}`; + return `${emojis.error} An error occurred: ${format.input(response)}}`; } assert(messageResponse); diff --git a/src/commands/moderation/massBan.ts b/src/commands/moderation/massBan.ts index a25c64f..ab9fbc8 100644 --- a/src/commands/moderation/massBan.ts +++ b/src/commands/moderation/massBan.ts @@ -1,7 +1,13 @@ import { + Arg, BanResponse, banResponse, BushCommand, + clientSendAndPermCheck, + colors, + emojis, + overflowEmbed, + regex, type ArgType, type CommandMessage, type OptArgType, @@ -45,7 +51,7 @@ export default class MassBanCommand extends BushCommand { match: 'option', prompt: "How many days of the user's messages would you like to delete?", retry: '{error} Choose between 0 and 7 days to delete messages from the user for.', - type: util.arg.range('integer', 0, 7, true), + type: Arg.range('integer', 0, 7, true), optional: true, slashType: ApplicationCommandOptionType.Integer, choices: [...Array(8).keys()].map((v) => ({ name: v.toString(), value: v })) @@ -54,7 +60,7 @@ export default class MassBanCommand extends BushCommand { quoted: true, slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [PermissionFlagsBits.BanMembers], lock: 'user' }); @@ -69,14 +75,13 @@ export default class MassBanCommand extends BushCommand { args.days ??= message.util.parsed?.alias?.includes('dban') ? 1 : 0; const ids = args.users.split(/\n| /).filter((id) => id.length > 0); - if (ids.length === 0) return message.util.send(`${util.emojis.error} You must provide at least one user id.`); + if (ids.length === 0) return message.util.send(`${emojis.error} You must provide at least one user id.`); for (const id of ids) { - if (!client.constants.regex.snowflake.test(id)) - return message.util.send(`${util.emojis.error} ${id} is not a valid snowflake.`); + if (!regex.snowflake.test(id)) return message.util.send(`${emojis.error} ${id} is not a valid snowflake.`); } if (!Number.isInteger(args.days) || args.days! < 0 || args.days! > 7) { - return message.util.reply(`${util.emojis.error} The delete days must be an integer between 0 and 7.`); + return message.util.reply(`${emojis.error} The delete days must be an integer between 0 and 7.`); } const promises = ids.map((id) => @@ -99,13 +104,13 @@ export default class MassBanCommand extends BushCommand { const id = ids[i]; const status = res[i]; const isSuccess = success(status); - const emoji = isSuccess ? util.emojis.success : util.emojis.error; + const emoji = isSuccess ? emojis.success : emojis.error; return `${emoji} ${id}${isSuccess ? '' : ` - ${status}`}`; }); - const embeds = util.overflowEmbed( + const embeds = overflowEmbed( { - color: util.colors.DarkRed, + color: colors.DarkRed, title: 'Mass Ban Results' }, lines diff --git a/src/commands/moderation/massEvidence.ts b/src/commands/moderation/massEvidence.ts index 468d43c..ffe85d2 100644 --- a/src/commands/moderation/massEvidence.ts +++ b/src/commands/moderation/massEvidence.ts @@ -1,4 +1,16 @@ -import { BushCommand, ModLog, type ArgType, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + colors, + emojis, + ModLog, + overflowEmbed, + regex, + type ArgType, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, PermissionFlagsBits } from 'discord.js'; import { EvidenceCommand } from '../index.js'; @@ -37,7 +49,7 @@ export default class MassEvidenceCommand extends BushCommand { quoted: true, slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [PermissionFlagsBits.ManageMessages], lock: 'user' }); @@ -53,10 +65,9 @@ export default class MassEvidenceCommand extends BushCommand { if (!evidence) return; const ids = args.users.split(/\n| /).filter((id) => id.length > 0); - if (ids.length === 0) return message.util.send(`${util.emojis.error} You must provide at least one user id.`); + if (ids.length === 0) return message.util.send(`${emojis.error} You must provide at least one user id.`); for (const id of ids) { - if (!client.constants.regex.snowflake.test(id)) - return message.util.send(`${util.emojis.error} ${id} is not a valid snowflake.`); + if (!regex.snowflake.test(id)) return message.util.send(`${emojis.error} ${id} is not a valid snowflake.`); } const caseMap = ( @@ -78,15 +89,15 @@ export default class MassEvidenceCommand extends BushCommand { const lines = ids.map((id, i) => { const case_ = res[i]; - if (!case_) return `${util.emojis.error} ${id} - no case found.`; - return `${util.emojis.success} ${id} - ${case_.id}`; + if (!case_) return `${emojis.error} ${id} - no case found.`; + return `${emojis.success} ${id} - ${case_.id}`; }); client.emit('massEvidence', message.member!, message.guild, evidence, lines); - const embeds = util.overflowEmbed( + const embeds = overflowEmbed( { - color: util.colors.DarkRed, + color: colors.DarkRed, title: 'Mass Evidence' }, lines diff --git a/src/commands/moderation/modlog.ts b/src/commands/moderation/modlog.ts index 71ed975..2c0e33a 100644 --- a/src/commands/moderation/modlog.ts +++ b/src/commands/moderation/modlog.ts @@ -1,6 +1,22 @@ -import { BushCommand, ButtonPaginator, ModLog, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + ButtonPaginator, + chunk, + clientSendAndPermCheck, + colors, + emojis, + humanizeDuration, + ModLog, + resolveUserAsync, + timestamp, + userGuildPermCheck, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; -import { ApplicationCommandOptionType, PermissionFlagsBits, User } from 'discord.js'; +import { ApplicationCommandOptionType, escapeMarkdown, PermissionFlagsBits, User } from 'discord.js'; export default class ModlogCommand extends BushCommand { public static separator = '\n━━━━━━━━━━━━━━━\n'; @@ -16,7 +32,7 @@ export default class ModlogCommand extends BushCommand { { id: 'search', description: 'The case id or user to search for modlogs by.', - type: util.arg.union('user', 'string'), + type: Arg.union('user', 'string'), prompt: 'What case id or user would you like to see?', retry: '{error} Choose a valid case id or user.', slashType: ApplicationCommandOptionType.String @@ -34,8 +50,8 @@ export default class ModlogCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) + clientPermissions: (m) => clientSendAndPermCheck(m), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) }); } @@ -45,7 +61,7 @@ export default class ModlogCommand extends BushCommand { ) { assert(message.inGuild()); - const foundUser = search instanceof User ? search : await util.resolveUserAsync(search); + const foundUser = search instanceof User ? search : await resolveUserAsync(search); if (foundUser) { const logs = await ModLog.findAll({ where: { @@ -59,23 +75,23 @@ export default class ModlogCommand extends BushCommand { .filter((log) => !(log.hidden && hidden)) .map((log) => ModlogCommand.generateModlogInfo(log, false)); if (!logs.length || !niceLogs.length) - return message.util.reply(`${util.emojis.error} **${foundUser.tag}** does not have any modlogs.`); - const chunked: string[][] = util.chunk(niceLogs, 4); + 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 Mod Logs`, description: chunk.join(ModlogCommand.separator), - color: util.colors.default + 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)) - return message.util.send(`${util.emojis.error} That modlog does not exist.`); - if (entry.guild !== message.guild.id) return message.util.reply(`${util.emojis.error} This modlog is from another server.`); + 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.`); const embed = { title: `Case ${entry.id}`, description: ModlogCommand.generateModlogInfo(entry, true), - color: util.colors.default + color: colors.default }; return await ButtonPaginator.send(message, [embed]); } @@ -83,12 +99,12 @@ export default class ModlogCommand extends BushCommand { public static generateModlogInfo(log: ModLog, showUser: boolean): string { const trim = (str: string): string => (str.endsWith('\n') ? str.substring(0, str.length - 1).trim() : str.trim()); - const modLog = [`**Case ID:** ${util.discord.escapeMarkdown(log.id)}`, `**Type:** ${log.type.toLowerCase()}`]; + const modLog = [`**Case ID:** ${escapeMarkdown(log.id)}`, `**Type:** ${log.type.toLowerCase()}`]; if (showUser) modLog.push(`**User:** <@!${log.user}>`); modLog.push(`**Moderator:** <@!${log.moderator}>`); - if (log.duration) modLog.push(`**Duration:** ${util.humanizeDuration(log.duration)}`); + if (log.duration) modLog.push(`**Duration:** ${humanizeDuration(log.duration)}`); modLog.push(`**Reason:** ${trim(log.reason ?? 'No Reason Specified.')}`); - modLog.push(`**Date:** ${util.timestamp(log.createdAt)}`); + modLog.push(`**Date:** ${timestamp(log.createdAt)}`); if (log.evidence) modLog.push(`**Evidence:** ${trim(log.evidence)}`); return modLog.join(`\n`); } diff --git a/src/commands/moderation/mute.ts b/src/commands/moderation/mute.ts index a665670..7ad023a 100644 --- a/src/commands/moderation/mute.ts +++ b/src/commands/moderation/mute.ts @@ -1,8 +1,14 @@ import { AllowedMentions, BushCommand, + castDurationContent, + clientSendAndPermCheck, + emojis, + format, Moderation, muteResponse, + prefix, + userGuildPermCheck, type ArgType, type CommandMessage, type OptArgType, @@ -51,8 +57,8 @@ export default class MuteCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles]), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles]), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) }); } @@ -67,11 +73,11 @@ export default class MuteCommand extends BushCommand { assert(message.inGuild()); assert(message.member); - const { duration, content } = await util.castDurationContent(args.reason_and_duration, message); + const { duration, content } = await castDurationContent(args.reason_and_duration, message); const member = await message.guild.members.fetch(args.user.id).catch(() => null); if (!member) - return await message.util.reply(`${util.emojis.error} The user you selected is not in the server or is not a valid user.`); + 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); @@ -87,29 +93,29 @@ export default class MuteCommand extends BushCommand { }); const responseMessage = (): string => { - const prefix = util.prefix(message); - const victim = util.format.input(member.user.tag); + const prefix_ = prefix(message); + const victim = format.input(member.user.tag); switch (responseCode) { case muteResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} Could not mute ${victim} because I am missing the **Manage Roles** permission.`; + return `${emojis.error} Could not mute ${victim} because I am missing the **Manage Roles** permission.`; case muteResponse.NO_MUTE_ROLE: - return `${util.emojis.error} Could not mute ${victim}, you must set a mute role with \`${prefix}config muteRole\`.`; + return `${emojis.error} Could not mute ${victim}, you must set a mute role with \`${prefix_}config muteRole\`.`; case muteResponse.MUTE_ROLE_INVALID: - return `${util.emojis.error} Could not mute ${victim} because the current mute role no longer exists. Please set a new mute role with \`${prefix}config muteRole\`.`; + return `${emojis.error} Could not mute ${victim} because the current mute role no longer exists. Please set a new mute role with \`${prefix_}config muteRole\`.`; case muteResponse.MUTE_ROLE_NOT_MANAGEABLE: - return `${util.emojis.error} Could not mute ${victim} because I cannot assign the current mute role, either change the role's position or set a new mute role with \`${prefix}config muteRole\`.`; + return `${emojis.error} Could not mute ${victim} because I cannot assign the current mute role, either change the role's position or set a new mute role with \`${prefix_}config muteRole\`.`; case muteResponse.ACTION_ERROR: - return `${util.emojis.error} Could not mute ${victim}, there was an error assigning them the mute role.`; + return `${emojis.error} Could not mute ${victim}, there was an error assigning them the mute role.`; case muteResponse.MODLOG_ERROR: - return `${util.emojis.error} There was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a modlog entry, please report this to my developers.`; case muteResponse.PUNISHMENT_ENTRY_ADD_ERROR: - return `${util.emojis.error} There was an error creating a punishment entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a punishment entry, please report this to my developers.`; case muteResponse.DM_ERROR: - return `${util.emojis.warn} Muted ${victim} however I could not send them a dm.`; + return `${emojis.warn} Muted ${victim} however I could not send them a dm.`; case muteResponse.SUCCESS: - return `${util.emojis.success} Successfully muted ${victim}.`; + return `${emojis.success} Successfully muted ${victim}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/purge.ts b/src/commands/moderation/purge.ts index 1652f6f..acf3897 100644 --- a/src/commands/moderation/purge.ts +++ b/src/commands/moderation/purge.ts @@ -1,4 +1,13 @@ -import { BushCommand, OptArgType, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + clientSendAndPermCheck, + emojis, + OptArgType, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, Collection, PermissionFlagsBits, type Message } from 'discord.js'; @@ -14,7 +23,7 @@ export default class PurgeCommand extends BushCommand { { id: 'amount', description: 'The amount of messages to purge.', - type: util.arg.range('integer', 1, 100, true), + type: Arg.range('integer', 1, 100, true), readableType: 'integer', prompt: 'How many messages would you like to purge?', retry: '{error} Please pick a number between 1 and 100.', @@ -43,7 +52,7 @@ export default class PurgeCommand extends BushCommand { ], slash: true, clientPermissions: (m) => - util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageMessages, PermissionFlagsBits.EmbedLinks], true), + clientSendAndPermCheck(m, [PermissionFlagsBits.ManageMessages, PermissionFlagsBits.EmbedLinks], true), userPermissions: [PermissionFlagsBits.ManageMessages], channel: 'guild' }); @@ -55,7 +64,7 @@ export default class PurgeCommand extends BushCommand { ) { assert(message.inGuild()); - if (args.amount > 100 || args.amount < 1) return message.util.reply(`${util.emojis.error} `); + if (args.amount > 100 || args.amount < 1) return message.util.reply(`${emojis.error} `); const messageFilter = (filterMessage: Message): boolean => { const shouldFilter: boolean[] = []; @@ -72,13 +81,13 @@ export default class PurgeCommand extends BushCommand { ); const purged = await message.channel!.bulkDelete(messages, true).catch(() => null); - if (!purged) return message.util.reply(`${util.emojis.error} Failed to purge messages.`).catch(() => null); + if (!purged) return message.util.reply(`${emojis.error} Failed to purge messages.`).catch(() => null); else { client.emit('bushPurge', message.author, message.guild, message.channel!, messages); - await message.util.send(`${util.emojis.success} Successfully purged **${purged.size}** messages.`); + await message.util.send(`${emojis.success} Successfully purged **${purged.size}** messages.`); /* .then(async (purgeMessage) => { if (!message.util.isSlashMessage(message)) { - await util.sleep(5); + await sleep(5); await purgeMessage.delete().catch(() => {}); } }); */ diff --git a/src/commands/moderation/removeReactionEmoji.ts b/src/commands/moderation/removeReactionEmoji.ts index 4359c5b..a088287 100644 --- a/src/commands/moderation/removeReactionEmoji.ts +++ b/src/commands/moderation/removeReactionEmoji.ts @@ -1,4 +1,13 @@ -import { BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + clientSendAndPermCheck, + emojis, + format, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, Message, PermissionFlagsBits } from 'discord.js'; @@ -14,7 +23,7 @@ export default class RemoveReactionEmojiCommand extends BushCommand { { id: 'message', description: 'The message to remove all the reactions of a certain emoji from.', - type: util.arg.union('message', 'messageLink'), + type: Arg.union('message', 'messageLink'), readableType: 'message|messageLink', prompt: 'What message would you like to remove a reaction from?', retry: '{error} Please pick a valid message.', @@ -23,7 +32,7 @@ export default class RemoveReactionEmojiCommand extends BushCommand { { id: 'emoji', description: 'The emoji to remove all the reactions of from a message.', - type: util.arg.union('emoji', 'snowflake'), + type: Arg.union('emoji', 'snowflake'), readableType: 'emoji|snowflake', match: 'restContent', prompt: 'What emoji would you like to remove?', @@ -34,7 +43,7 @@ export default class RemoveReactionEmojiCommand extends BushCommand { slash: true, channel: 'guild', clientPermissions: (m) => - util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageMessages, PermissionFlagsBits.EmbedLinks], true), + clientSendAndPermCheck(m, [PermissionFlagsBits.ManageMessages, PermissionFlagsBits.EmbedLinks], true), userPermissions: [PermissionFlagsBits.ManageMessages, PermissionFlagsBits.ManageEmojisAndStickers] // Can't undo the removal of 1000s of reactions }); } @@ -54,15 +63,15 @@ export default class RemoveReactionEmojiCommand extends BushCommand { if (success) { return await message.util.reply( - `${util.emojis.success} Removed all reactions of ${util.format.input( - emojiID! - )} from the message with the id of ${util.format.input(resolvedMessage.id)}.` + `${emojis.success} Removed all reactions of ${format.input(emojiID!)} from the message with the id of ${format.input( + resolvedMessage.id + )}.` ); } else { return await message.util.reply( - `${util.emojis.error} There was an error removing all reactions of ${util.format.input( + `${emojis.error} There was an error removing all reactions of ${format.input( emojiID! - )} from the message with the id of ${util.format.input(resolvedMessage.id)}.` + )} from the message with the id of ${format.input(resolvedMessage.id)}.` ); } } diff --git a/src/commands/moderation/role.ts b/src/commands/moderation/role.ts index b9e1490..6febaa6 100644 --- a/src/commands/moderation/role.ts +++ b/src/commands/moderation/role.ts @@ -2,6 +2,11 @@ import { addRoleResponse, AllowedMentions, BushCommand, + clientSendAndPermCheck, + emojis, + format, + humanizeDuration, + mappings, removeRoleResponse, type ArgType, type CommandMessage, @@ -63,7 +68,7 @@ export default class RoleCommand extends BushCommand { flags: ['--force'], typing: true, clientPermissions: (m) => - util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles, PermissionFlagsBits.EmbedLinks], true), + clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles, PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -130,14 +135,13 @@ export default class RoleCommand extends BushCommand { } ) { assert(message.inGuild()); - if (!args.role) return await message.util.reply(`${util.emojis.error} You must specify a role.`); + if (!args.role) return await message.util.reply(`${emojis.error} You must specify a role.`); args.duration ??= 0; if ( !message.member!.permissions.has(PermissionFlagsBits.ManageRoles) && message.member!.id !== message.guild?.ownerId && !message.member!.user.isOwner() ) { - const mappings = client.consts.mappings; let mappedRole: { name: string; id: string }; for (let i = 0; i < mappings.roleMap.length; i++) { const a = mappings.roleMap[i]; @@ -145,7 +149,7 @@ export default class RoleCommand extends BushCommand { } if (!mappedRole! || !(mappedRole.name in mappings.roleWhitelist)) { return await message.util.reply({ - content: `${util.emojis.error} <@&${args.role.id}> is not whitelisted, and you do not have manage roles permission.`, + content: `${emojis.error} <@&${args.role.id}> is not whitelisted, and you do not have manage roles permission.`, allowedMentions: AllowedMentions.none() }); } @@ -157,7 +161,7 @@ export default class RoleCommand extends BushCommand { }); if (!message.member!.roles.cache.some((role) => (allowedRoles as Snowflake[]).includes(role.id))) { return await message.util.reply({ - content: `${util.emojis.error} <@&${args.role.id}> is whitelisted, but you do not have any of the roles required to manage it.`, + content: `${emojis.error} <@&${args.role.id}> is whitelisted, but you do not have any of the roles required to manage it.`, allowedMentions: AllowedMentions.none() }); } @@ -173,33 +177,33 @@ export default class RoleCommand extends BushCommand { }); const responseMessage = (): string => { - const victim = util.format.input(args.member.user.tag); + const victim = format.input(args.member.user.tag); switch (responseCode) { case addRoleResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} I don't have the **Manage Roles** permission.`; + return `${emojis.error} I don't have the **Manage Roles** permission.`; case addRoleResponse.USER_HIERARCHY: - return `${util.emojis.error} <@&${args.role.id}> is higher or equal to your highest role.`; + return `${emojis.error} <@&${args.role.id}> is higher or equal to your highest role.`; case addRoleResponse.ROLE_MANAGED: - return `${util.emojis.error} <@&${args.role.id}> is managed by an integration and cannot be managed.`; + return `${emojis.error} <@&${args.role.id}> is managed by an integration and cannot be managed.`; case addRoleResponse.CLIENT_HIERARCHY: - return `${util.emojis.error} <@&${args.role.id}> is higher or equal to my highest role.`; + return `${emojis.error} <@&${args.role.id}> is higher or equal to my highest role.`; case addRoleResponse.MODLOG_ERROR: - return `${util.emojis.error} There was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a modlog entry, please report this to my developers.`; case addRoleResponse.PUNISHMENT_ENTRY_ADD_ERROR: case removeRoleResponse.PUNISHMENT_ENTRY_REMOVE_ERROR: - return `${util.emojis.error} There was an error ${ + return `${emojis.error} There was an error ${ args.action === 'add' ? 'creating' : 'removing' } a punishment entry, please report this to my developers.`; case addRoleResponse.ACTION_ERROR: - return `${util.emojis.error} An error occurred while trying to ${args.action} <@&${args.role.id}> ${ + return `${emojis.error} An error occurred while trying to ${args.action} <@&${args.role.id}> ${ args.action === 'add' ? 'to' : 'from' } ${victim}.`; case addRoleResponse.SUCCESS: - return `${util.emojis.success} Successfully ${args.action === 'add' ? 'added' : 'removed'} <@&${args.role.id}> ${ + return `${emojis.success} Successfully ${args.action === 'add' ? 'added' : 'removed'} <@&${args.role.id}> ${ args.action === 'add' ? 'to' : 'from' - } ${victim}${args.duration ? ` for ${util.humanizeDuration(args.duration)}` : ''}.`; + } ${victim}${args.duration ? ` for ${humanizeDuration(args.duration)}` : ''}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; diff --git a/src/commands/moderation/slowmode.ts b/src/commands/moderation/slowmode.ts index e657b76..641f88e 100644 --- a/src/commands/moderation/slowmode.ts +++ b/src/commands/moderation/slowmode.ts @@ -1,4 +1,15 @@ -import { BushCommand, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + clientSendAndPermCheck, + emojis, + format, + humanizeDuration, + userGuildPermCheck, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { Argument } from 'discord-akairo'; import { ApplicationCommandOptionType, ChannelType, PermissionFlagsBits } from 'discord.js'; @@ -36,8 +47,8 @@ export default class SlowmodeCommand extends BushCommand { slash: true, channel: 'guild', clientPermissions: (m) => - util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels, PermissionFlagsBits.EmbedLinks], true), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) + clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels, PermissionFlagsBits.EmbedLinks], true), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) }); } @@ -58,11 +69,11 @@ export default class SlowmodeCommand extends BushCommand { args.channel.type !== ChannelType.GuildVoice && !args.channel.isThread() ) - return await message.util.reply(`${util.emojis.error} <#${args.channel.id}> is not a text or thread channel.`); + return await message.util.reply(`${emojis.error} <#${args.channel.id}> is not a text or thread channel.`); args.length = typeof args.length === 'string' && !(['off', 'none', 'disable'] as const).includes(args.length) - ? await util.arg.cast('duration', message, args.length) + ? await Arg.cast('duration', message, args.length) : args.length; const length2: number = (['off', 'none', 'disable'] as const).includes(args.length) || args.length === null ? 0 : args.length; @@ -71,11 +82,11 @@ export default class SlowmodeCommand extends BushCommand { .setRateLimitPerUser(length2 / 1000, `Changed by ${message.author.tag} (${message.author.id}).`) .catch(() => {}); if (!setSlowmode) - return await message.util.reply(`${util.emojis.error} There was an error changing the slowmode of <#${args.channel.id}>.`); + return await message.util.reply(`${emojis.error} There was an error changing the slowmode of <#${args.channel.id}>.`); else return await message.util.reply( - `${util.emojis.success} Successfully changed the slowmode of <#${args.channel.id}> ${ - length2 ? `to ${util.format.input(util.humanizeDuration(length2))}` : '**off**' + `${emojis.success} Successfully changed the slowmode of <#${args.channel.id}> ${ + length2 ? `to ${format.input(humanizeDuration(length2))}` : '**off**' }.` ); } diff --git a/src/commands/moderation/timeout.ts b/src/commands/moderation/timeout.ts index ed3562d..7be8ecb 100644 --- a/src/commands/moderation/timeout.ts +++ b/src/commands/moderation/timeout.ts @@ -1,6 +1,10 @@ import { AllowedMentions, BushCommand, + castDurationContent, + clientSendAndPermCheck, + emojis, + format, Moderation, timeoutResponse, type ArgType, @@ -49,7 +53,7 @@ export default class TimeoutCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ModerateMembers]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ModerateMembers]), userPermissions: [PermissionFlagsBits.ModerateMembers] }); } @@ -61,12 +65,12 @@ export default class TimeoutCommand extends BushCommand { assert(message.inGuild()); assert(message.member); - const { duration, content } = await util.castDurationContent(args.reason_and_duration, message); + const { duration, content } = await castDurationContent(args.reason_and_duration, message); - if (!duration) return await message.util.reply(`${util.emojis.error} You must specify a duration for timeouts.`); + if (!duration) return await message.util.reply(`${emojis.error} You must specify a duration for timeouts.`); const member = await message.guild.members.fetch(args.user.id).catch(() => null); if (!member) - return await message.util.reply(`${util.emojis.error} The user you selected is not in the server or is not a valid user.`); + 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); @@ -82,22 +86,22 @@ export default class TimeoutCommand extends BushCommand { }); const responseMessage = (): string => { - const victim = util.format.input(member.user.tag); + const victim = format.input(member.user.tag); switch (responseCode) { case timeoutResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} Could not timeout ${victim} because I am missing the **Timeout Members** permission.`; + return `${emojis.error} Could not timeout ${victim} because I am missing the **Timeout Members** permission.`; case timeoutResponse.INVALID_DURATION: - return `${util.emojis.error} The duration you specified is too long, the longest you can timeout someone for is 28 days.`; + return `${emojis.error} The duration you specified is too long, the longest you can timeout someone for is 28 days.`; case timeoutResponse.ACTION_ERROR: - return `${util.emojis.error} An unknown error occurred while trying to timeout ${victim}.`; + return `${emojis.error} An unknown error occurred while trying to timeout ${victim}.`; case timeoutResponse.MODLOG_ERROR: - return `${util.emojis.error} There was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a modlog entry, please report this to my developers.`; case timeoutResponse.DM_ERROR: - return `${util.emojis.warn} Timed out ${victim} however I could not send them a dm.`; + return `${emojis.warn} Timed out ${victim} however I could not send them a dm.`; case timeoutResponse.SUCCESS: - return `${util.emojis.success} Successfully timed out ${victim}.`; + return `${emojis.success} Successfully timed out ${victim}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/unban.ts b/src/commands/moderation/unban.ts index d7549ab..a4c4992 100644 --- a/src/commands/moderation/unban.ts +++ b/src/commands/moderation/unban.ts @@ -1,6 +1,9 @@ import { AllowedMentions, + Arg, BushCommand, + emojis, + format, unbanResponse, type ArgType, type CommandMessage, @@ -22,7 +25,7 @@ export default class UnbanCommand extends BushCommand { { id: 'user', description: 'The user to unban.', - type: util.arg.union('user', 'globalUser'), + type: Arg.union('user', 'globalUser'), prompt: 'What user would you like to unban?', retry: '{error} Choose a valid user to unban.', slashType: ApplicationCommandOptionType.User @@ -58,23 +61,23 @@ export default class UnbanCommand extends BushCommand { }); const responseMessage = (): string => { - const victim = util.format.input(user.tag); + const victim = format.input(user.tag); switch (responseCode) { case unbanResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} Could not unban ${victim} because I am missing the **Ban Members** permission.`; + return `${emojis.error} Could not unban ${victim} because I am missing the **Ban Members** permission.`; case unbanResponse.ACTION_ERROR: - return `${util.emojis.error} An error occurred while trying to unban ${victim}.`; + return `${emojis.error} An error occurred while trying to unban ${victim}.`; case unbanResponse.PUNISHMENT_ENTRY_REMOVE_ERROR: - return `${util.emojis.error} While unbanning ${victim}, there was an error removing their ban entry, please report this to my developers.`; + return `${emojis.error} While unbanning ${victim}, there was an error removing their ban entry, please report this to my developers.`; case unbanResponse.MODLOG_ERROR: - return `${util.emojis.error} While unbanning ${victim}, there was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} While unbanning ${victim}, there was an error creating a modlog entry, please report this to my developers.`; case unbanResponse.NOT_BANNED: - return `${util.emojis.warn} ${victim} is not banned but I tried to unban them anyways.`; + return `${emojis.warn} ${victim} is not banned but I tried to unban them anyways.`; case unbanResponse.DM_ERROR: case unbanResponse.SUCCESS: - return `${util.emojis.success} Successfully unbanned ${victim}.`; + return `${emojis.success} Successfully unbanned ${victim}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/unblock.ts b/src/commands/moderation/unblock.ts index 886d546..09ec281 100644 --- a/src/commands/moderation/unblock.ts +++ b/src/commands/moderation/unblock.ts @@ -1,8 +1,12 @@ import { AllowedMentions, BushCommand, + clientSendAndPermCheck, + emojis, + format, Moderation, unblockResponse, + userGuildPermCheck, type ArgType, type CommandMessage, type OptArgType, @@ -51,8 +55,8 @@ export default class UnblockCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) }); } @@ -65,11 +69,11 @@ export default class UnblockCommand extends BushCommand { assert(message.channel); if (!message.channel.isTextBased()) - return message.util.send(`${util.emojis.error} This command can only be used in text based channels.`); + return message.util.send(`${emojis.error} This command can only be used in text based channels.`); const member = await message.guild.members.fetch(args.user.id).catch(() => null); if (!member) - return await message.util.reply(`${util.emojis.error} The user you selected is not in the server or is not a valid user.`); + 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); @@ -85,24 +89,24 @@ export default class UnblockCommand extends BushCommand { }); const responseMessage = (): string => { - const victim = util.format.input(member.user.tag); + const victim = format.input(member.user.tag); switch (responseCode) { case unblockResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} Could not unblock ${victim} because I am missing the **Manage Channel** permission.`; + return `${emojis.error} Could not unblock ${victim} because I am missing the **Manage Channel** permission.`; case unblockResponse.INVALID_CHANNEL: - return `${util.emojis.error} Could not unblock ${victim}, you can only unblock users in text or thread channels.`; + return `${emojis.error} Could not unblock ${victim}, you can only unblock users in text or thread channels.`; case unblockResponse.ACTION_ERROR: - return `${util.emojis.error} An unknown error occurred while trying to unblock ${victim}.`; + return `${emojis.error} An unknown error occurred while trying to unblock ${victim}.`; case unblockResponse.MODLOG_ERROR: - return `${util.emojis.error} There was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a modlog entry, please report this to my developers.`; case unblockResponse.PUNISHMENT_ENTRY_REMOVE_ERROR: - return `${util.emojis.error} There was an error creating a punishment entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a punishment entry, please report this to my developers.`; case unblockResponse.DM_ERROR: - return `${util.emojis.warn} Unblocked ${victim} however I could not send them a dm.`; + return `${emojis.warn} Unblocked ${victim} however I could not send them a dm.`; case unblockResponse.SUCCESS: - return `${util.emojis.success} Successfully unblocked ${victim}.`; + return `${emojis.success} Successfully unblocked ${victim}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/unlockdown.ts b/src/commands/moderation/unlockdown.ts index dbcd429..db1a09d 100644 --- a/src/commands/moderation/unlockdown.ts +++ b/src/commands/moderation/unlockdown.ts @@ -1,5 +1,13 @@ import { LockdownCommand } from '#commands'; -import { BushCommand, type ArgType, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + clientSendAndPermCheck, + type ArgType, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import { ApplicationCommandOptionType, ChannelType, PermissionFlagsBits } from 'discord.js'; export default class UnlockdownCommand extends BushCommand { @@ -14,7 +22,7 @@ export default class UnlockdownCommand extends BushCommand { { id: 'channel', description: 'Specify a different channel to unlockdown instead of the one you trigger the command in.', - type: util.arg.union('textChannel', 'newsChannel', 'threadChannel', 'voiceChannel'), + type: Arg.union('textChannel', 'newsChannel', 'threadChannel', 'voiceChannel'), prompt: 'What channel would you like to unlockdown?', slashType: ApplicationCommandOptionType.Channel, channelTypes: [ @@ -48,7 +56,7 @@ export default class UnlockdownCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageChannels]), userPermissions: [PermissionFlagsBits.ManageChannels] }); } diff --git a/src/commands/moderation/unmute.ts b/src/commands/moderation/unmute.ts index 202e341..9ac13ce 100644 --- a/src/commands/moderation/unmute.ts +++ b/src/commands/moderation/unmute.ts @@ -1,8 +1,13 @@ import { AllowedMentions, BushCommand, + clientSendAndPermCheck, + emojis, + format, Moderation, + prefix, unmuteResponse, + userGuildPermCheck, type ArgType, type CommandMessage, type OptArgType, @@ -51,8 +56,8 @@ export default class UnmuteCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles]), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageRoles]), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) }); } @@ -63,7 +68,7 @@ export default class UnmuteCommand extends BushCommand { assert(message.inGuild()); assert(message.member); - const error = util.emojis.error; + const error = emojis.error; const member = message.guild.members.cache.get(user.id)!; const useForce = force && message.author.isOwner(); @@ -79,17 +84,17 @@ export default class UnmuteCommand extends BushCommand { }); const responseMessage = (): string => { - const prefix = util.prefix(message); - const victim = util.format.input(member.user.tag); + const prefix_ = prefix(message); + const victim = format.input(member.user.tag); switch (responseCode) { case unmuteResponse.MISSING_PERMISSIONS: return `${error} Could not unmute ${victim} because I am missing the **Manage Roles** permission.`; case unmuteResponse.NO_MUTE_ROLE: - return `${error} Could not unmute ${victim}, you must set a mute role with \`${prefix}config muteRole\`.`; + return `${error} Could not unmute ${victim}, you must set a mute role with \`${prefix_}config muteRole\`.`; case unmuteResponse.MUTE_ROLE_INVALID: - return `${error} Could not unmute ${victim} because the current mute role no longer exists. Please set a new mute role with \`${prefix}config muteRole\`.`; + return `${error} Could not unmute ${victim} because the current mute role no longer exists. Please set a new mute role with \`${prefix_}config muteRole\`.`; case unmuteResponse.MUTE_ROLE_NOT_MANAGEABLE: - return `${error} Could not unmute ${victim} because I cannot assign the current mute role, either change the role's position or set a new mute role with \`${prefix}config muteRole\`.`; + return `${error} Could not unmute ${victim} because I cannot assign the current mute role, either change the role's position or set a new mute role with \`${prefix_}config muteRole\`.`; case unmuteResponse.ACTION_ERROR: return `${error} Could not unmute ${victim}, there was an error removing their mute role.`; case unmuteResponse.MODLOG_ERROR: @@ -97,11 +102,11 @@ export default class UnmuteCommand extends BushCommand { case unmuteResponse.PUNISHMENT_ENTRY_REMOVE_ERROR: return `${error} While muting ${victim}, there was an error removing their mute entry, please report this to my developers.`; case unmuteResponse.DM_ERROR: - return `${util.emojis.warn} unmuted ${victim} however I could not send them a dm.`; + return `${emojis.warn} unmuted ${victim} however I could not send them a dm.`; case unmuteResponse.SUCCESS: - return `${util.emojis.success} Successfully unmuted ${victim}.`; + return `${emojis.success} Successfully unmuted ${victim}.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/untimeout.ts b/src/commands/moderation/untimeout.ts index 7622f29..c6860c5 100644 --- a/src/commands/moderation/untimeout.ts +++ b/src/commands/moderation/untimeout.ts @@ -1,6 +1,9 @@ import { AllowedMentions, BushCommand, + clientSendAndPermCheck, + emojis, + format, Moderation, removeTimeoutResponse, type ArgType, @@ -51,7 +54,7 @@ export default class UntimeoutCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ModerateMembers]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ModerateMembers]), userPermissions: [PermissionFlagsBits.ModerateMembers] }); } @@ -65,9 +68,9 @@ export default class UntimeoutCommand extends BushCommand { const member = await message.guild.members.fetch(args.user.id).catch(() => null); if (!member) - return await message.util.reply(`${util.emojis.error} The user you selected is not in the server or is not a valid user.`); + return await message.util.reply(`${emojis.error} The user you selected is not in the server or is not a valid user.`); - if (!member.isCommunicationDisabled()) return message.util.reply(`${util.emojis.error} That user is not timed out.`); + 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); @@ -82,20 +85,20 @@ export default class UntimeoutCommand extends BushCommand { }); const responseMessage = (): string => { - const victim = util.format.input(member.user.tag); + const victim = format.input(member.user.tag); switch (responseCode) { case removeTimeoutResponse.MISSING_PERMISSIONS: - return `${util.emojis.error} Could not untimeout ${victim} because I am missing the **Timeout Members** permission.`; + return `${emojis.error} Could not untimeout ${victim} because I am missing the **Timeout Members** permission.`; case removeTimeoutResponse.ACTION_ERROR: - return `${util.emojis.error} An unknown error occurred while trying to timeout ${victim}.`; + return `${emojis.error} An unknown error occurred while trying to timeout ${victim}.`; case removeTimeoutResponse.MODLOG_ERROR: - return `${util.emojis.error} There was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} There was an error creating a modlog entry, please report this to my developers.`; case removeTimeoutResponse.DM_ERROR: - return `${util.emojis.warn} Removed ${victim}'s timeout however I could not send them a dm.`; + return `${emojis.warn} Removed ${victim}'s timeout however I could not send them a dm.`; case removeTimeoutResponse.SUCCESS: - return `${util.emojis.success} Successfully removed ${victim}'s timeout.`; + return `${emojis.success} Successfully removed ${victim}'s timeout.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(responseCode)}}`; + return `${emojis.error} An error occurred: ${format.input(responseCode)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moderation/warn.ts b/src/commands/moderation/warn.ts index b3bf965..81b2937 100644 --- a/src/commands/moderation/warn.ts +++ b/src/commands/moderation/warn.ts @@ -1,7 +1,12 @@ import { AllowedMentions, BushCommand, + clientSendAndPermCheck, + emojis, + format, Moderation, + ordinal, + userGuildPermCheck, warnResponse, type ArgType, type CommandMessage, @@ -50,8 +55,8 @@ export default class WarnCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), - userPermissions: (m) => util.userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) + clientPermissions: (m) => clientSendAndPermCheck(m), + userPermissions: (m) => userGuildPermCheck(m, [PermissionFlagsBits.ManageMessages]) }); } @@ -63,7 +68,7 @@ export default class WarnCommand extends BushCommand { assert(message.member); const member = message.guild.members.cache.get(user.id); - if (!member) return message.util.reply(`${util.emojis.error} I cannot warn users that are not in the server.`); + 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); @@ -77,19 +82,19 @@ export default class WarnCommand extends BushCommand { }); const responseMessage = (): string => { - const victim = util.format.input(member.user.tag); + const victim = format.input(member.user.tag); switch (response) { case warnResponse.MODLOG_ERROR: - return `${util.emojis.error} While warning ${victim}, there was an error creating a modlog entry, please report this to my developers.`; + return `${emojis.error} While warning ${victim}, there was an error creating a modlog entry, please report this to my developers.`; case warnResponse.ACTION_ERROR: case warnResponse.DM_ERROR: - return `${util.emojis.warn} ${victim} has been warned for the ${util.ordinal( + return `${emojis.warn} ${victim} has been warned for the ${ordinal( caseNum ?? 0 )} time, however I could not send them a dm.`; case warnResponse.SUCCESS: - return `${util.emojis.success} Successfully warned ${victim} for the ${util.ordinal(caseNum ?? 0)} time.`; + return `${emojis.success} Successfully warned ${victim} for the ${ordinal(caseNum ?? 0)} time.`; default: - return `${util.emojis.error} An error occurred: ${util.format.input(response)}}`; + return `${emojis.error} An error occurred: ${format.input(response)}}`; } }; return await message.util.reply({ content: responseMessage(), allowedMentions: AllowedMentions.none() }); diff --git a/src/commands/moulberry-bush/capePermissions.ts b/src/commands/moulberry-bush/capePermissions.ts index 5f15d9e..3ad9602 100644 --- a/src/commands/moulberry-bush/capePermissions.ts +++ b/src/commands/moulberry-bush/capePermissions.ts @@ -1,4 +1,15 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + colors, + emojis, + format, + mcUUID, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; import got from 'got'; @@ -21,7 +32,7 @@ export default class CapePermissionsCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], channel: 'guild' }); @@ -30,10 +41,10 @@ export default class CapePermissionsCommand extends BushCommand { public override async exec(message: CommandMessage | SlashMessage, args: { ign: ArgType<'string'> }) { let capePerms: CapePerms | null, uuid: string; try { - uuid = await util.mcUUID(args.ign); + uuid = await mcUUID(args.ign); } catch (e) { return await message.util.reply({ - content: `${util.emojis.error} ${util.format.input(args.ign)} doesn't appear to be a valid username.`, + content: `${emojis.error} ${format.input(args.ign)} doesn't appear to be a valid username.`, allowedMentions: AllowedMentions.none() }); } @@ -44,9 +55,7 @@ export default class CapePermissionsCommand extends BushCommand { capePerms = null; } if (capePerms == null) { - return await message.util.reply( - `${util.emojis.error} There was an error finding cape perms for ${util.format.input(args.ign)}.` - ); + return await message.util.reply(`${emojis.error} There was an error finding cape perms for ${format.input(args.ign)}.`); } else { if (capePerms?.perms) { let index = null; @@ -59,17 +68,15 @@ export default class CapePermissionsCommand extends BushCommand { continue; } if (index == null) - return await message.util.reply( - `${util.emojis.error} ${util.format.input(args.ign)} does not appear to have any capes.` - ); + return await message.util.reply(`${emojis.error} ${format.input(args.ign)} does not appear to have any capes.`); const userPerm: string[] = capePerms.perms[index].perms; const embed = new EmbedBuilder() .setTitle(`${args.ign}'s Capes`) .setDescription(userPerm.join('\n')) - .setColor(util.colors.default); + .setColor(colors.default); await message.util.reply({ embeds: [embed] }); } else { - return await message.util.reply(`${util.emojis.error} There was an error finding cape perms for ${args.ign}.`); + return await message.util.reply(`${emojis.error} There was an error finding cape perms for ${args.ign}.`); } } } diff --git a/src/commands/moulberry-bush/capes.ts b/src/commands/moulberry-bush/capes.ts index 6bf7854..c2dae4d 100644 --- a/src/commands/moulberry-bush/capes.ts +++ b/src/commands/moulberry-bush/capes.ts @@ -2,7 +2,12 @@ import { AllowedMentions, BushCommand, ButtonPaginator, + clientSendAndPermCheck, + colors, DeleteButton, + emojis, + format, + mappings, type CommandMessage, type OptArgType, type SlashMessage @@ -36,7 +41,7 @@ export default class CapesCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -53,11 +58,11 @@ export default class CapesCommand extends BushCommand { .filter((f) => f.match !== null); const capes: { name: string; url: string; index: number; purchasable?: boolean }[] = [ - ...client.consts.mappings.capes + ...mappings.capes .filter((c) => !rawCapes.some((gitCape) => gitCape.match!.groups!.name === c.name) && c.custom) .map((c) => ({ name: c.name, url: c.custom!, index: c.index, purchasable: c.purchasable })), ...rawCapes.map((c) => { - const mapCape = client.consts.mappings.capes.find((a) => a.name === c.match!.groups!.name); + const mapCape = mappings.capes.find((a) => a.name === c.match!.groups!.name); const url = mapCape?.custom ?? `https://github.com/Moulberry/NotEnoughUpdates/raw/master/${c.f.path}`; const index = mapCape?.index !== undefined ? mapCape.index : null; return { name: c.match!.groups!.name, url, index: index!, purchasable: mapCape?.purchasable }; @@ -76,7 +81,7 @@ export default class CapesCommand extends BushCommand { await DeleteButton.send(message, { embeds: [embed] }); } else { await message.util.reply({ - content: `${util.emojis.error} Cannot find a cape called ${util.format.input(args.cape)}.`, + content: `${emojis.error} Cannot find a cape called ${format.input(args.cape)}.`, allowedMentions: AllowedMentions.none() }); } @@ -89,7 +94,7 @@ export default class CapesCommand extends BushCommand { private makeEmbed(cape: { name: string; url: string; index: number; purchasable?: boolean | undefined }): APIEmbed { return { title: `${cape.name} cape`, - color: util.colors.default, + color: colors.default, timestamp: new Date().toISOString(), image: { url: cape.url }, description: cape.purchasable @@ -99,7 +104,7 @@ export default class CapesCommand extends BushCommand { } public override autocomplete(interaction: AutocompleteInteraction) { - const capes = client.consts.mappings.capes.map((v) => v.name); + const capes = mappings.capes.map((v) => v.name); const fuzzy = new Fuse(capes, { threshold: 0.5, diff --git a/src/commands/moulberry-bush/giveawayPing.ts b/src/commands/moulberry-bush/giveawayPing.ts index 23a6a20..0cadd6a 100644 --- a/src/commands/moulberry-bush/giveawayPing.ts +++ b/src/commands/moulberry-bush/giveawayPing.ts @@ -1,4 +1,4 @@ -import { AllowedMentions, BushCommand, type CommandMessage } from '#lib'; +import { AllowedMentions, BushCommand, clientSendAndPermCheck, emojis, type CommandMessage } from '#lib'; import { PermissionFlagsBits } from 'discord.js'; export default class GiveawayPingCommand extends BushCommand { @@ -9,7 +9,7 @@ export default class GiveawayPingCommand extends BushCommand { description: 'Pings the giveaway role.', usage: ['giveaway-ping'], examples: ['giveaway-ping'], - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageMessages], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageMessages], true), userPermissions: [ PermissionFlagsBits.ManageGuild, PermissionFlagsBits.ManageMessages, @@ -30,7 +30,7 @@ export default class GiveawayPingCommand extends BushCommand { public override async exec(message: CommandMessage) { if (!message.member!.permissions.has(PermissionFlagsBits.ManageGuild) && !message.member!.user.isOwner()) - await message.util.reply(`${util.emojis.error} You are missing the **ManageGuild** permission.`); + await message.util.reply(`${emojis.error} You are missing the **ManageGuild** permission.`); await message.delete().catch(() => {}); diff --git a/src/commands/moulberry-bush/moulHammer.ts b/src/commands/moulberry-bush/moulHammer.ts index f07511a..0eeb769 100644 --- a/src/commands/moulberry-bush/moulHammer.ts +++ b/src/commands/moulberry-bush/moulHammer.ts @@ -1,4 +1,4 @@ -import { BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, colors, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; @@ -24,7 +24,7 @@ export default class MoulHammerCommand extends BushCommand { channel: 'guild', slashGuilds: ['516977525906341928'], restrictedGuilds: ['516977525906341928'], - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -37,7 +37,7 @@ export default class MoulHammerCommand extends BushCommand { const embed = new EmbedBuilder() .setTitle('L') .setDescription(`${user.username} got moul'ed <:wideberry1:756223352598691942><:wideberry2:756223336832303154>`) - .setColor(util.colors.purple); + .setColor(colors.purple); await message.util.send({ embeds: [embed] }); } } diff --git a/src/commands/moulberry-bush/report.ts b/src/commands/moulberry-bush/report.ts index 29eee76..06c1ad2 100644 --- a/src/commands/moulberry-bush/report.ts +++ b/src/commands/moulberry-bush/report.ts @@ -1,4 +1,13 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + colors, + emojis, + timestampAndDelta, + type ArgType, + type CommandMessage +} from '#lib'; import { stripIndent } from '#tags'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; @@ -32,7 +41,7 @@ export default class ReportCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], channel: 'guild' }); @@ -42,23 +51,21 @@ export default class ReportCommand extends BushCommand { assert(message.inGuild()); if (!(await message.guild.hasFeature('reporting'))) - return await message.util.reply( - `${util.emojis.error} This command can only be used in servers where reporting is enabled.` - ); + return await message.util.reply(`${emojis.error} This command can only be used in servers where reporting is enabled.`); - if (!member) return await message.util.reply(`${util.emojis.error} Choose someone to report`); + if (!member) return await message.util.reply(`${emojis.error} Choose someone to report`); if (member.user.id === '322862723090219008') return await message.util.reply({ content: `Thank you for your report! We take these allegations very seriously and have reported <@${member.user.id}> to the FBI!`, allowedMentions: AllowedMentions.none() }); if (member.user.bot) - return await message.util.reply(`${util.emojis.error} You cannot report a bot <:WeirdChamp:756283321301860382>.`); + return await message.util.reply(`${emojis.error} You cannot report a bot <:WeirdChamp:756283321301860382>.`); const reportChannel = await message.guild.getLogChannel('report'); if (!reportChannel) return await message.util.reply( - `${util.emojis.error} This server has not setup a report logging channel or the channel no longer exists.` + `${emojis.error} This server has not setup a report logging channel or the channel no longer exists.` ); //The formatting of the report is mostly copied from carl since it is pretty good when it actually works @@ -70,24 +77,24 @@ export default class ReportCommand extends BushCommand { iconURL: message.author.avatarURL() ?? undefined }) .setTitle('New Report') - .setColor(util.colors.red) + .setColor(colors.red) .setDescription(evidence) .addFields([ { name: 'Reporter', value: stripIndent` **Name:**${message.author.tag} <@${message.author.id}> - **Joined:** $${util.timestampAndDelta(message.member!.joinedAt!)} - **Created:** ${util.timestampAndDelta(message.author.createdAt)} + **Joined:** $${timestampAndDelta(message.member!.joinedAt!)} + **Created:** ${timestampAndDelta(message.author.createdAt)} **Sent From**: <#${message.channel.id}> [Jump to context](${message.url})`, inline: true }, { name: 'Reported User', value: stripIndent` - **Name:**${member.user.tag} <@${member.user.id}> - **Joined:** $${util.timestampAndDelta(member.joinedAt!)} - **Created:** ${util.timestampAndDelta(member.user.createdAt)}`, + **Name:** ${member.user.tag} <@${member.user.id}> + **Joined:** ${timestampAndDelta(member.joinedAt!)} + **Created:** ${timestampAndDelta(member.user.createdAt)}`, inline: true } ]); @@ -102,8 +109,8 @@ export default class ReportCommand extends BushCommand { } await reportChannel.send({ embeds: [reportEmbed] }).then(async (ReportMessage) => { try { - await ReportMessage.react(util.emojis.check); - await ReportMessage.react(util.emojis.cross); + await ReportMessage.react(emojis.check); + await ReportMessage.react(emojis.cross); } catch { void client.console.warn('ReportCommand', 'Could not react to report message.'); } diff --git a/src/commands/moulberry-bush/rule.ts b/src/commands/moulberry-bush/rule.ts index 17f1bd8..574334a 100644 --- a/src/commands/moulberry-bush/rule.ts +++ b/src/commands/moulberry-bush/rule.ts @@ -1,4 +1,12 @@ -import { AllowedMentions, BushCommand, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + AllowedMentions, + Arg, + BushCommand, + clientSendAndPermCheck, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; import { stripIndent } from '../../lib/common/tags.js'; @@ -70,7 +78,7 @@ export default class RuleCommand extends BushCommand { { id: 'rule', description: 'The rule to view.', - type: util.arg.range('integer', 1, rules.length, true), + type: Arg.range('integer', 1, rules.length, true), readableType: 'integer', prompt: 'What rule would you like to have cited?', retry: '{error} Choose a valid rule.', @@ -92,7 +100,7 @@ export default class RuleCommand extends BushCommand { slash: true, slashGuilds: ['516977525906341928'], channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], restrictedGuilds: ['516977525906341928'] }); diff --git a/src/commands/moulberry-bush/serverStatus.ts b/src/commands/moulberry-bush/serverStatus.ts index ad3903a..c0c0518 100644 --- a/src/commands/moulberry-bush/serverStatus.ts +++ b/src/commands/moulberry-bush/serverStatus.ts @@ -1,4 +1,4 @@ -import { BushCommand, type CommandMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, colors, emojis, type CommandMessage } from '#lib'; import assert from 'assert'; import { EmbedBuilder, PermissionFlagsBits } from 'discord.js'; import got from 'got'; @@ -13,7 +13,7 @@ export default class ServerStatusCommand extends BushCommand { description: "Gives the status of moulberry's server", usage: ['server-status'], examples: ['server-status', 'ss'], - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], slash: true }); @@ -22,24 +22,24 @@ export default class ServerStatusCommand extends BushCommand { public override async exec(message: CommandMessage) { const msgEmbed = new EmbedBuilder() .setTitle('Server status') - .setDescription(`Checking server:\n${util.emojis.loading}`) - .setColor(util.colors.default) + .setDescription(`Checking server:\n${emojis.loading}`) + .setColor(colors.default) .setFooter({ text: 'Checking https://moulberry.codes/lowestbin.json' }); await message.util.reply({ embeds: [msgEmbed] }); let main; try { await got.get('https://moulberry.codes/lowestbin.json').json(); - main = util.emojis.success; + main = emojis.success; } catch (e) { - main = util.emojis.error; + main = emojis.error; } await message.util.edit({ embeds: [msgEmbed.setDescription(`Checking server:\n${main}`)] }); - if (main == util.emojis.success) { + if (main == emojis.success) { await message.util.edit({ embeds: [ msgEmbed .addFields([{ name: 'Status', value: 'The server is online, all features related to prices will likely work.' }]) - .setColor(util.colors.success) + .setColor(colors.success) ] }); } else { @@ -53,7 +53,7 @@ export default class ServerStatusCommand extends BushCommand { "It appears Moulberry's server is offline, this means that everything related to prices will likely not work." } ]) - .setColor(util.colors.error) + .setColor(colors.error) ] }); } diff --git a/src/commands/utilities/_poll.ts b/src/commands/utilities/_poll.ts index a843561..fdf6381 100644 --- a/src/commands/utilities/_poll.ts +++ b/src/commands/utilities/_poll.ts @@ -29,7 +29,7 @@ // } // ], // slash: true, -// clientPermissions: (m) => util.clientSendAndPermCheck(m), +// clientPermissions: (m) => clientSendAndPermCheck(m), // userPermissions: [] // }); // } @@ -38,8 +38,8 @@ // const { question, options } = this.parseArgs(message, args); // if (!question || !options.length) return; -// if (question.length > 256) return await message.util.reply(`${util.emojis.error} Question must be 256 characters or less.`); -// if (options.length > 10) return await message.util.reply(`${util.emojis.error} You can only have upto 10 options.`); +// if (question.length > 256) return await message.util.reply(`${emojis.error} Question must be 256 characters or less.`); +// if (options.length > 10) return await message.util.reply(`${emojis.error} You can only have upto 10 options.`); // return message.util.send({ // embeds: [ @@ -64,13 +64,13 @@ // const split = args.options.split(/[,|]/).filter((s) => s.trim().length > 0); // if (message.util.isSlash) { // if (split.length < 2) { -// void message.util.reply(`${util.emojis.error} You must provide at least two options.`); +// void message.util.reply(`${emojis.error} You must provide at least two options.`); // return { question: '', options: [] }; // } // return { question: args.question!, options: split }; // } else { // if (split.length < 3) { -// void message.util.reply(`${util.emojis.error} You must provide a question and at least two options.`); +// void message.util.reply(`${emojis.error} You must provide a question and at least two options.`); // return { question: '', options: [] }; // } diff --git a/src/commands/utilities/activity.ts b/src/commands/utilities/activity.ts index 14cc5a0..dfbccfb 100644 --- a/src/commands/utilities/activity.ts +++ b/src/commands/utilities/activity.ts @@ -1,4 +1,13 @@ -import { BushCommand, type ArgType, type BushArgumentTypeCaster, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + clientSendAndPermCheck, + emojis, + regex, + type ArgType, + type BushArgumentTypeCaster, + type CommandMessage, + type SlashMessage +} from '#lib'; import { type ArgumentGeneratorReturn, type ArgumentTypeCaster } from 'discord-akairo'; import { ApplicationCommandOptionType, ChannelType, type DiscordAPIError, type Snowflake } from 'discord.js'; @@ -55,7 +64,7 @@ interface Activity { } function map(phase: string): Activity | null { - if (client.consts.regex.snowflake.test(phase)) return { id: phase, aliases: [] }; + if (regex.snowflake.test(phase)) return { id: phase, aliases: [] }; else if (phase in activityMap) return activityMap[phase as keyof typeof activityMap]; for (const activity in activityMap) { @@ -115,7 +124,7 @@ export default class ActivityCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -155,8 +164,7 @@ export default class ActivityCommand extends BushCommand { args: { channel: ArgType<'voiceChannel'>; activity: string } ) { const channel = typeof args.channel === 'string' ? message.guild?.channels.cache.get(args.channel) : args.channel; - if (channel?.type !== ChannelType.GuildVoice) - return await message.util.reply(`${util.emojis.error} Choose a valid voice channel`); + if (channel?.type !== ChannelType.GuildVoice) return await message.util.reply(`${emojis.error} Choose a valid voice channel`); const target_application_id = message.util.isSlashMessage(message) ? args.activity @@ -177,14 +185,12 @@ export default class ActivityCommand extends BushCommand { .catch((e: Error | DiscordAPIError) => { if ((e as DiscordAPIError)?.code === 50013) { - response = `${util.emojis.error} I am missing permissions to make an invite in that channel.`; + response = `${emojis.error} I am missing permissions to make an invite in that channel.`; return; - } else response = `${util.emojis.error} An error occurred while generating your invite: ${e?.message ?? e}`; + } else response = `${emojis.error} An error occurred while generating your invite: ${e?.message ?? e}`; }); if (response! || !invite || !invite.code) - return await message.util.reply( - response! ?? `${util.emojis.error} An unknown error occurred while generating your invite.` - ); + return await message.util.reply(response! ?? `${emojis.error} An unknown error occurred while generating your invite.`); else return await message.util.send(`https://discord.gg/${invite.code}`); } } diff --git a/src/commands/utilities/calculator.ts b/src/commands/utilities/calculator.ts index a318a79..75d63a1 100644 --- a/src/commands/utilities/calculator.ts +++ b/src/commands/utilities/calculator.ts @@ -1,4 +1,13 @@ -import { AllowedMentions, BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + colors, + emojis, + inspectCleanRedactCodeblock, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder } from 'discord.js'; import { evaluate } from 'mathjs'; @@ -25,7 +34,7 @@ export default class CalculatorCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -34,22 +43,20 @@ export default class CalculatorCommand extends BushCommand { const decodedEmbed = new EmbedBuilder().addFields([ { name: '📥 Input', - value: await util.inspectCleanRedactCodeblock(args.expression, 'mma') + value: await inspectCleanRedactCodeblock(args.expression, 'mma') } ]); try { const calculated = /^(9\s*?\+\s*?10)|(10\s*?\+\s*?9)$/.test(args.expression) ? '21' : evaluate(args.expression); decodedEmbed - .setTitle(`${util.emojis.successFull} Successfully Calculated Expression`) - .setColor(util.colors.success) - .addFields([{ name: '📤 Output', value: await util.inspectCleanRedactCodeblock(calculated.toString(), 'mma') }]); + .setTitle(`${emojis.successFull} Successfully Calculated Expression`) + .setColor(colors.success) + .addFields([{ name: '📤 Output', value: await inspectCleanRedactCodeblock(calculated.toString(), 'mma') }]); } catch (error) { decodedEmbed - .setTitle(`${util.emojis.errorFull} Unable to Calculate Expression`) - .setColor(util.colors.error) - .addFields([ - { name: `📤 Error`, value: await util.inspectCleanRedactCodeblock(`${error.name}: ${error.message}`, 'js') } - ]); + .setTitle(`${emojis.errorFull} Unable to Calculate Expression`) + .setColor(colors.error) + .addFields([{ name: `📤 Error`, value: await inspectCleanRedactCodeblock(`${error.name}: ${error.message}`, 'js') }]); } return await message.util.reply({ embeds: [decodedEmbed], allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/utilities/decode.ts b/src/commands/utilities/decode.ts index 8c82fcc..cc742c8 100644 --- a/src/commands/utilities/decode.ts +++ b/src/commands/utilities/decode.ts @@ -1,4 +1,14 @@ -import { AllowedMentions, BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + capitalize, + clientSendAndPermCheck, + colors, + formatError, + inspectCleanRedactCodeblock, + type CommandMessage, + type SlashMessage +} from '#lib'; import { ApplicationCommandOptionType, EmbedBuilder } from 'discord.js'; const encodingTypesArray = ['ascii', 'utf8', 'utf-8', 'utf16le', 'ucs2', 'ucs-2', 'base64', 'latin1', 'binary', 'hex']; @@ -42,7 +52,7 @@ export default class DecodeCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -51,20 +61,18 @@ export default class DecodeCommand extends BushCommand { message: CommandMessage | SlashMessage, { from, to, data }: { from: BufferEncoding; to: BufferEncoding; data: string } ) { - const encodeOrDecode = util.capitalizeFirstLetter(message?.util?.parsed?.alias ?? 'decoded'); + const encodeOrDecode = capitalize(message?.util?.parsed?.alias ?? 'decoded'); const decodedEmbed = new EmbedBuilder() .setTitle(`${encodeOrDecode} Information`) - .addFields([{ name: '📥 Input', value: await util.inspectCleanRedactCodeblock(data) }]); + .addFields([{ name: '📥 Input', value: await inspectCleanRedactCodeblock(data) }]); try { const decoded = Buffer.from(data, from).toString(to); - decodedEmbed - .setColor(util.colors.success) - .addFields([{ name: '📤 Output', value: await util.inspectCleanRedactCodeblock(decoded) }]); + decodedEmbed.setColor(colors.success).addFields([{ name: '📤 Output', value: await inspectCleanRedactCodeblock(decoded) }]); } catch (error) { - decodedEmbed.setColor(util.colors.error).addFields([ + decodedEmbed.setColor(colors.error).addFields([ { name: `📤 Error ${encodeOrDecode.slice(1)}ing`, - value: await util.inspectCleanRedactCodeblock(util.formatError(error)) + value: await inspectCleanRedactCodeblock(formatError(error)) } ]); } diff --git a/src/commands/utilities/hash.ts b/src/commands/utilities/hash.ts index f47c388..6e8c37f 100644 --- a/src/commands/utilities/hash.ts +++ b/src/commands/utilities/hash.ts @@ -1,4 +1,4 @@ -import { BushCommand, type CommandMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, type CommandMessage } from '#lib'; import assert from 'assert'; import crypto from 'crypto'; import { ApplicationCommandOptionType } from 'discord.js'; @@ -25,7 +25,7 @@ export default class HashCommand extends BushCommand { slashType: ApplicationCommandOptionType.String } ], - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } diff --git a/src/commands/utilities/highlight-!.ts b/src/commands/utilities/highlight-!.ts index 6dca545..6847737 100644 --- a/src/commands/utilities/highlight-!.ts +++ b/src/commands/utilities/highlight-!.ts @@ -1,4 +1,4 @@ -import { BushCommand, Highlight, HighlightWord, type SlashMessage } from '#lib'; +import { BushCommand, clientSendAndPermCheck, Highlight, HighlightWord, type SlashMessage } from '#lib'; import { Flag, type ArgumentGeneratorReturn, type SlashOption } from 'discord-akairo'; import { ApplicationCommandOptionType, @@ -123,7 +123,7 @@ export default class HighlightCommand extends BushCommand { }), slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } diff --git a/src/commands/utilities/highlight-add.ts b/src/commands/utilities/highlight-add.ts index 726b887..9624a7e 100644 --- a/src/commands/utilities/highlight-add.ts +++ b/src/commands/utilities/highlight-add.ts @@ -1,4 +1,4 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { AllowedMentions, BushCommand, emojis, format, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; import assert from 'assert'; import { highlightCommandArgs, highlightSubcommands } from './highlight-!.js'; @@ -44,16 +44,16 @@ export default class HighlightAddCommand extends BushCommand { if (!args.regex) { if (args.word.length < 2) - return message.util.send(`${util.emojis.error} You can only highlight words that are longer than 2 characters.`); + return message.util.send(`${emojis.error} You can only highlight words that are longer than 2 characters.`); if (args.word.length > 50) - return await message.util.reply(`${util.emojis.error} You can only highlight words that are shorter than 50 characters.`); + return await message.util.reply(`${emojis.error} You can only highlight words that are shorter than 50 characters.`); } else { try { new RegExp(args.word); } catch (e) { assert(e instanceof SyntaxError); return message.util.send({ - content: `${util.emojis.error} Invalid regex ${util.format.inlineCode(e.message)}.`, + content: `${emojis.error} Invalid regex ${format.inlineCode(e.message)}.`, allowedMentions: AllowedMentions.none() }); } @@ -65,15 +65,15 @@ export default class HighlightAddCommand extends BushCommand { }); if (typeof res === 'string') - return await message.util.reply({ content: `${util.emojis.error} ${res}`, allowedMentions: AllowedMentions.none() }); + return await message.util.reply({ content: `${emojis.error} ${res}`, allowedMentions: AllowedMentions.none() }); else if (!res) return await message.util.reply({ - content: `${util.emojis.error} There was an error highlighting "${args.word}".`, + content: `${emojis.error} There was an error highlighting "${args.word}".`, allowedMentions: AllowedMentions.none() }); return await message.util.reply({ - content: `${util.emojis.success} Successfully added "${args.word}" to your highlight list.`, + content: `${emojis.success} Successfully added "${args.word}" to your highlight list.`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/utilities/highlight-block.ts b/src/commands/utilities/highlight-block.ts index 61e1254..5429071 100644 --- a/src/commands/utilities/highlight-block.ts +++ b/src/commands/utilities/highlight-block.ts @@ -1,4 +1,14 @@ -import { AllowedMentions, BushCommand, Highlight, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + addToArray, + AllowedMentions, + Arg, + BushCommand, + emojis, + Highlight, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { Argument, ArgumentGeneratorReturn } from 'discord-akairo'; import { Channel, GuildMember } from 'discord.js'; @@ -35,15 +45,13 @@ export default class HighlightBlockCommand extends BushCommand { assert(message.inGuild()); args.target = - typeof args.target === 'string' - ? (await util.arg.cast(util.arg.union('member', 'channel'), message, args.target))! - : args.target; + typeof args.target === 'string' ? (await Arg.cast(Arg.union('member', 'channel'), message, args.target))! : args.target; if (!args.target || !(args.target instanceof GuildMember || args.target instanceof Channel)) - return await message.util.reply(`${util.emojis.error} You can only block users or channels.`); + return await message.util.reply(`${emojis.error} You can only block users or channels.`); if (args.target instanceof Channel && !args.target.isTextBased()) - return await message.util.reply(`${util.emojis.error} You can only block text-based channels.`); + return await message.util.reply(`${emojis.error} You can only block text-based channels.`); const [highlight] = await Highlight.findOrCreate({ where: { guild: message.guild.id, user: message.author.id } @@ -54,16 +62,16 @@ export default class HighlightBlockCommand extends BushCommand { if (highlight[key].includes(args.target.id)) return await message.util.reply({ // eslint-disable-next-line @typescript-eslint/no-base-to-string - content: `${util.emojis.error} You have already blocked ${args.target}.`, + content: `${emojis.error} You have already blocked ${args.target}.`, allowedMentions: AllowedMentions.none() }); - highlight[key] = util.addToArray(highlight[key], args.target.id); + highlight[key] = addToArray(highlight[key], args.target.id); await highlight.save(); return await message.util.reply({ // eslint-disable-next-line @typescript-eslint/no-base-to-string - content: `${util.emojis.success} Successfully blocked ${args.target} from triggering your highlights.`, + content: `${emojis.success} Successfully blocked ${args.target} from triggering your highlights.`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/utilities/highlight-clear.ts b/src/commands/utilities/highlight-clear.ts index b905f3b..df9f387 100644 --- a/src/commands/utilities/highlight-clear.ts +++ b/src/commands/utilities/highlight-clear.ts @@ -1,4 +1,4 @@ -import { BushCommand, ConfirmationPrompt, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, ConfirmationPrompt, emojis, type CommandMessage, type SlashMessage } from '#lib'; import assert from 'assert'; import { highlightSubcommands } from './highlight-!.js'; @@ -21,11 +21,11 @@ export default class HighlightClearCommand extends BushCommand { if (message.util.isSlashMessage(message)) await message.interaction.deferReply(); const confirm = await ConfirmationPrompt.send(message, { content: `Are you sure you want to clear your highlight list?` }); - if (!confirm) return await message.util.reply(`${util.emojis.warn} You decided not to clear your highlight list.`); + if (!confirm) return await message.util.reply(`${emojis.warn} You decided not to clear your highlight list.`); const success = await client.highlightManager.removeAllHighlights(message.guild.id, message.author.id); - if (!success) return await message.util.reply(`${util.emojis.error} There was an error clearing your highlight list.`); + if (!success) return await message.util.reply(`${emojis.error} There was an error clearing your highlight list.`); - return await message.util.reply(`${util.emojis.success} Successfully cleared your highlight list.`); + return await message.util.reply(`${emojis.success} Successfully cleared your highlight list.`); } } diff --git a/src/commands/utilities/highlight-matches.ts b/src/commands/utilities/highlight-matches.ts index 40020cd..b458550 100644 --- a/src/commands/utilities/highlight-matches.ts +++ b/src/commands/utilities/highlight-matches.ts @@ -1,4 +1,4 @@ -import { BushCommand, ButtonPaginator, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { BushCommand, ButtonPaginator, chunk, colors, emojis, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; import assert from 'assert'; import { type ArgumentGeneratorReturn } from 'discord-akairo'; import { type APIEmbed } from 'discord.js'; @@ -36,18 +36,16 @@ export default class HighlightMatchesCommand extends BushCommand { const res = await client.highlightManager.checkPhrase(message.guild.id, message.author.id, args.phrase); - if (!res.size) return await message.util.reply(`${util.emojis.error} You are not highlighting any words`); + if (!res.size) return await message.util.reply(`${emojis.error} You are not highlighting any words`); - const lines = res.map( - (passed, hl) => `${passed ? util.emojis.check : util.emojis.cross} ${hl.regex ? `/${hl.word}/gi` : hl.word}` - ); - const chunked = util.chunk(lines, 10); + const lines = res.map((passed, hl) => `${passed ? emojis.check : emojis.cross} ${hl.regex ? `/${hl.word}/gi` : hl.word}`); + const chunked = chunk(lines, 10); const pages = chunked.map( (chunk): APIEmbed => ({ title: `Matches`, description: chunk.join('\n'), - color: util.colors.default + color: colors.default }) ); diff --git a/src/commands/utilities/highlight-remove.ts b/src/commands/utilities/highlight-remove.ts index a2f2367..bb1300a 100644 --- a/src/commands/utilities/highlight-remove.ts +++ b/src/commands/utilities/highlight-remove.ts @@ -1,4 +1,4 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { AllowedMentions, BushCommand, emojis, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; import assert from 'assert'; import { highlightCommandArgs, highlightSubcommands } from './highlight-!.js'; @@ -34,15 +34,15 @@ export default class HighlightRemoveCommand extends BushCommand { const res = await client.highlightManager.removeHighlight(message.guild.id, message.author.id, args.word); if (typeof res === 'string') - return await message.util.reply({ content: `${util.emojis.error} ${res}`, allowedMentions: AllowedMentions.none() }); + return await message.util.reply({ content: `${emojis.error} ${res}`, allowedMentions: AllowedMentions.none() }); else if (!res) return await message.util.reply({ - content: `${util.emojis.error} There was an error unhighlighting "${args.word}".`, + content: `${emojis.error} There was an error unhighlighting "${args.word}".`, allowedMentions: AllowedMentions.none() }); return await message.util.reply({ - content: `${util.emojis.success} Successfully removed "${args.word}" from your highlight list.`, + content: `${emojis.success} Successfully removed "${args.word}" from your highlight list.`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/utilities/highlight-show.ts b/src/commands/utilities/highlight-show.ts index 80ba4ca..d966f3a 100644 --- a/src/commands/utilities/highlight-show.ts +++ b/src/commands/utilities/highlight-show.ts @@ -1,4 +1,4 @@ -import { AllowedMentions, BushCommand, Highlight, type CommandMessage, type SlashMessage } from '#lib'; +import { AllowedMentions, BushCommand, colors, emojis, Highlight, type CommandMessage, type SlashMessage } from '#lib'; import assert from 'assert'; import { EmbedBuilder } from 'discord.js'; import { highlightSubcommands } from './highlight-!.js'; @@ -25,7 +25,7 @@ export default class HighlightShowCommand extends BushCommand { void client.highlightManager.syncCache(); - if (!highlight.words.length) return message.util.reply(`${util.emojis.error} You are not highlighting any words.`); + if (!highlight.words.length) return message.util.reply(`${emojis.error} You are not highlighting any words.`); const embed = new EmbedBuilder() .setTitle('Highlight List') @@ -35,7 +35,7 @@ export default class HighlightShowCommand extends BushCommand { .join('\n') .substring(0, 4096) ) - .setColor(util.colors.default); + .setColor(colors.default); if (highlight.blacklistedChannels.length) embed.addFields([ diff --git a/src/commands/utilities/highlight-unblock.ts b/src/commands/utilities/highlight-unblock.ts index b738ee9..7f416eb 100644 --- a/src/commands/utilities/highlight-unblock.ts +++ b/src/commands/utilities/highlight-unblock.ts @@ -1,4 +1,13 @@ -import { AllowedMentions, BushCommand, Highlight, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + emojis, + Highlight, + removeFromArray, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { Argument, ArgumentGeneratorReturn } from 'discord-akairo'; import { Channel, GuildMember } from 'discord.js'; @@ -35,10 +44,10 @@ export default class HighlightUnblockCommand extends BushCommand { assert(message.inGuild()); if (!(args.target instanceof GuildMember || args.target instanceof Channel)) - return await message.util.reply(`${util.emojis.error} You can only unblock users or channels.`); + return await message.util.reply(`${emojis.error} You can only unblock users or channels.`); if (args.target instanceof Channel && !args.target.isTextBased()) - return await message.util.reply(`${util.emojis.error} You can only unblock text-based channels.`); + return await message.util.reply(`${emojis.error} You can only unblock text-based channels.`); const [highlight] = await Highlight.findOrCreate({ where: { guild: message.guild.id, user: message.author.id } @@ -48,15 +57,15 @@ export default class HighlightUnblockCommand extends BushCommand { if (!highlight[key].includes(args.target.id)) return await message.util.reply({ - content: `${util.emojis.error} ${args.target} is not blocked so cannot be unblock.`, + content: `${emojis.error} ${args.target} is not blocked so cannot be unblock.`, allowedMentions: AllowedMentions.none() }); - highlight[key] = util.removeFromArray(highlight[key], args.target.id); + highlight[key] = removeFromArray(highlight[key], args.target.id); await highlight.save(); return await message.util.reply({ - content: `${util.emojis.success} Successfully allowed ${args.target} to trigger your highlights.`, + content: `${emojis.success} Successfully allowed ${args.target} to trigger your highlights.`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/utilities/price.ts b/src/commands/utilities/price.ts index a4f4c03..c569437 100644 --- a/src/commands/utilities/price.ts +++ b/src/commands/utilities/price.ts @@ -1,4 +1,4 @@ -import { ArgType, BushCommand, type CommandMessage } from '#lib'; +import { ArgType, BushCommand, clientSendAndPermCheck, colors, emojis, format, oxford, type CommandMessage } from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, AutocompleteInteraction, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; import Fuse from 'fuse.js'; @@ -39,7 +39,7 @@ export default class PriceCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [], typing: true }); @@ -58,12 +58,12 @@ export default class PriceCommand extends BushCommand { ])) as [Bazaar | undefined, LowestBIN | undefined, LowestBIN | undefined, AuctionAverages | undefined]; let parsedItem = args.item.toString().toUpperCase().replace(/ /g, '_').replace(/'S/g, ''); - const priceEmbed = new EmbedBuilder().setColor(errors?.length ? util.colors.warn : util.colors.success).setTimestamp(); + const priceEmbed = new EmbedBuilder().setColor(errors?.length ? colors.warn : colors.success).setTimestamp(); if (bazaar?.success === false) errors.push('bazaar'); if (errors.length) { - priceEmbed.setFooter({ text: `Could not fetch data for ${util.oxford(errors, 'and')}` }); + priceEmbed.setFooter({ text: `Could not fetch data for ${oxford(errors, 'and')}` }); } // create a set from all the item names so that there are no duplicates for the fuzzy search @@ -86,7 +86,7 @@ export default class PriceCommand extends BushCommand { // if its a bazaar item then it there should not be any ah data if (bazaar?.products?.[parsedItem]) { - priceEmbed.setTitle(`Bazaar Information for ${util.format.input(parsedItem)}`).addFields([ + priceEmbed.setTitle(`Bazaar Information for ${format.input(parsedItem)}`).addFields([ { name: 'Sell Price', value: addBazaarInformation('sellPrice', 2, true) }, { name: 'Buy Price', value: addBazaarInformation('buyPrice', 2, true) }, { @@ -103,7 +103,7 @@ export default class PriceCommand extends BushCommand { // checks if the item exists in any of the action information otherwise it is not a valid item if (currentLowestBIN?.[parsedItem] || averageLowestBIN?.[parsedItem] || auctionAverages?.[parsedItem]) { - priceEmbed.setTitle(`Price Information for ${util.format.input(parsedItem)}`).setFooter({ + priceEmbed.setTitle(`Price Information for ${format.input(parsedItem)}`).setFooter({ text: `${ priceEmbed.data.footer?.text ? `${priceEmbed.data.footer.text} | ` : '' }All information is based on the last 3 days.` @@ -111,10 +111,8 @@ export default class PriceCommand extends BushCommand { } else { const errorEmbed = new EmbedBuilder(); errorEmbed - .setColor(util.colors.error) - .setDescription( - `${util.emojis.error} ${util.format.input(parsedItem)} is not a valid item id, or it has no auction data.` - ); + .setColor(colors.error) + .setDescription(`${emojis.error} ${format.input(parsedItem)} is not a valid item id, or it has no auction data.`); return await message.util.reply({ embeds: [errorEmbed] }); } diff --git a/src/commands/utilities/remind.ts b/src/commands/utilities/remind.ts index 8727879..3a1cd18 100644 --- a/src/commands/utilities/remind.ts +++ b/src/commands/utilities/remind.ts @@ -1,4 +1,17 @@ -import { BushCommand, Reminder, Time, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + BushCommand, + castDurationContent, + clientSendAndPermCheck, + dateDelta, + emojis, + format, + Reminder, + Time, + timestamp, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import { ApplicationCommandOptionType } from 'discord.js'; export default class RemindCommand extends BushCommand { @@ -22,7 +35,7 @@ export default class RemindCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -31,13 +44,13 @@ export default class RemindCommand extends BushCommand { message: CommandMessage | SlashMessage, args: { reminder: OptArgType<'contentWithDuration'> | string } ) { - const { duration, content } = await util.castDurationContent(args.reminder, message); + const { duration, content } = await castDurationContent(args.reminder, message); - if (!content.trim()) return await message.util.reply(`${util.emojis.error} Please enter a reason to be reminded about.`); - if (!duration) return await message.util.reply(`${util.emojis.error} Please enter a time to remind you in.`); + if (!content.trim()) return await message.util.reply(`${emojis.error} Please enter a reason to be reminded about.`); + if (!duration) return await message.util.reply(`${emojis.error} Please enter a time to remind you in.`); if (duration < Time.Second * 30) - return await message.util.reply(`${util.emojis.error} You cannot be reminded in less than 30 seconds.`); + return await message.util.reply(`${emojis.error} You cannot be reminded in less than 30 seconds.`); const expires = new Date(Date.now() + duration); @@ -49,10 +62,10 @@ export default class RemindCommand extends BushCommand { expires: expires }).catch(() => false); - if (!success) return await message.util.reply(`${util.emojis.error} Could not create a reminder.`); + if (!success) return await message.util.reply(`${emojis.error} Could not create a reminder.`); // This isn't technically accurate, but it prevents it from being .99 seconds - const delta = util.format.bold(util.dateDelta(new Date(Date.now() + duration))); - return await message.util.reply(`${util.emojis.success} I will remind you in ${delta} (${util.timestamp(expires, 'T')}).`); + const delta = format.bold(dateDelta(new Date(Date.now() + duration))); + return await message.util.reply(`${emojis.success} I will remind you in ${delta} (${timestamp(expires, 'T')}).`); } } diff --git a/src/commands/utilities/reminders.ts b/src/commands/utilities/reminders.ts index 79284ac..18243fe 100644 --- a/src/commands/utilities/reminders.ts +++ b/src/commands/utilities/reminders.ts @@ -1,4 +1,15 @@ -import { BushCommand, ButtonPaginator, Reminder, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + ButtonPaginator, + chunk, + clientSendAndPermCheck, + colors, + emojis, + Reminder, + timestamp, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { PermissionFlagsBits, type APIEmbed } from 'discord.js'; import { Op } from 'sequelize'; @@ -14,22 +25,22 @@ export default class RemindersCommand extends BushCommand { usage: ['reminder'], examples: ['reminders'], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks]), userPermissions: [] }); } public override async exec(message: CommandMessage | SlashMessage) { const reminders = await Reminder.findAll({ where: { user: message.author.id, expires: { [Op.gt]: new Date() } } }); - if (!reminders.length) return message.util.send(`${util.emojis.error} You don't have any reminders set.`); + if (!reminders.length) return message.util.send(`${emojis.error} You don't have any reminders set.`); - const formattedReminders = reminders.map((reminder) => `${util.timestamp(reminder.expires, 't')} - ${reminder.content}`); + const formattedReminders = reminders.map((reminder) => `${timestamp(reminder.expires, 't')} - ${reminder.content}`); - const chunked = util.chunk(formattedReminders, 15); + const chunked = chunk(formattedReminders, 15); const embeds: APIEmbed[] = chunked.map((chunk) => ({ title: `Reminders`, description: chunk.join('\n'), - color: util.colors.default + color: colors.default })); return await ButtonPaginator.send(message, embeds); } diff --git a/src/commands/utilities/steal.ts b/src/commands/utilities/steal.ts index 69d3054..83ec338 100644 --- a/src/commands/utilities/steal.ts +++ b/src/commands/utilities/steal.ts @@ -1,4 +1,13 @@ -import { BushCommand, OptArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + clientSendAndPermCheck, + emojis, + OptArgType, + regex, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { type ArgumentGeneratorReturn, type ArgumentType, type ArgumentTypeCaster } from 'discord-akairo'; import { ApplicationCommandOptionType, Attachment, PermissionFlagsBits } from 'discord.js'; @@ -36,7 +45,7 @@ export default class StealCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.ManageEmojisAndStickers]), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.ManageEmojisAndStickers]), userPermissions: [PermissionFlagsBits.ManageEmojisAndStickers] }); } @@ -47,7 +56,7 @@ export default class StealCommand extends BushCommand { const emoji = hasImage ? message.attachments.first()!.url : yield { - type: util.arg.union('discordEmoji', 'snowflake', 'url') as ArgumentType | ArgumentTypeCaster, + type: Arg.union('discordEmoji', 'snowflake', 'url') as ArgumentType | ArgumentTypeCaster, prompt: { start: lang.emojiStart, retry: lang.emojiRetry } }; @@ -65,20 +74,20 @@ export default class StealCommand extends BushCommand { ) { assert(message.inGuild()); - if (!args.emoji) return await message.util.reply(`${util.emojis.error} You must provide an emoji to steal.`); + if (!args.emoji) return await message.util.reply(`${emojis.error} You must provide an emoji to steal.`); const image = args.emoji instanceof URL ? args.emoji.href : typeof args.emoji === 'object' ? `https://cdn.discordapp.com/emojis/${args.emoji.id}` - : client.consts.regex.snowflake.test(args.emoji ?? '') + : regex.snowflake.test(args.emoji ?? '') ? `https://cdn.discordapp.com/emojis/${args!.emoji}` : (args.emoji ?? '').match(/https?:\/\//) ? args.emoji : undefined; - if (image === undefined) return await message.util.reply(`${util.emojis.error} You must provide an emoji to steal.`); + if (image === undefined) return await message.util.reply(`${emojis.error} You must provide an emoji to steal.`); const emojiName = args.name ?? args.emoji instanceof URL @@ -96,11 +105,9 @@ export default class StealCommand extends BushCommand { .catch((e: Error) => e); if (!(creationSuccess instanceof Error)) - return await message.util.reply(`${util.emojis.success} You successfully stole ${creationSuccess}.`); + return await message.util.reply(`${emojis.success} You successfully stole ${creationSuccess}.`); else { - return await message.util.reply( - `${util.emojis.error} The was an error stealing that emoji \`${creationSuccess.message}\`.` - ); + return await message.util.reply(`${emojis.error} The was an error stealing that emoji \`${creationSuccess.message}\`.`); } } @@ -129,11 +136,9 @@ export default class StealCommand extends BushCommand { .catch((e: Error) => e); if (!(creationSuccess instanceof Error)) - return await message.util.reply(`${util.emojis.success} You successfully stole ${creationSuccess}.`); + return await message.util.reply(`${emojis.success} You successfully stole ${creationSuccess}.`); else { - return await message.util.reply( - `${util.emojis.error} The was an error stealing that emoji \`${creationSuccess.message}\`.` - ); + return await message.util.reply(`${emojis.error} The was an error stealing that emoji \`${creationSuccess.message}\`.`); } } } diff --git a/src/commands/utilities/suicide.ts b/src/commands/utilities/suicide.ts index c4151e8..d2510cc 100644 --- a/src/commands/utilities/suicide.ts +++ b/src/commands/utilities/suicide.ts @@ -1,4 +1,4 @@ -import { AllowedMentions, BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { AllowedMentions, BushCommand, clientSendAndPermCheck, colors, type CommandMessage, type SlashMessage } from '#lib'; import { stripIndent } from '#tags'; import { EmbedBuilder } from 'discord.js'; @@ -11,7 +11,7 @@ export default class SuicideCommand extends BushCommand { usage: ['suicide'], examples: ['suicide'], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [], bypassChannelBlacklist: true }); @@ -21,7 +21,7 @@ export default class SuicideCommand extends BushCommand { // stolen from https://github.com/dexbiobot/Zeppelin const suicideEmbed = new EmbedBuilder() .setTitle('Mental Health Resources') - .setColor(util.colors.red) + .setColor(colors.red) .setAuthor({ name: 'Remember, You Matter <3', iconURL: diff --git a/src/commands/utilities/uuid.ts b/src/commands/utilities/uuid.ts index 1e70e91..44cfeda 100644 --- a/src/commands/utilities/uuid.ts +++ b/src/commands/utilities/uuid.ts @@ -1,4 +1,14 @@ -import { AllowedMentions, ArgType, BushCommand, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + ArgType, + BushCommand, + clientSendAndPermCheck, + emojis, + format, + mcUUID, + type CommandMessage, + type SlashMessage +} from '#lib'; import { ApplicationCommandOptionType } from 'discord.js'; export default class UuidCommand extends BushCommand { @@ -30,7 +40,7 @@ export default class UuidCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -41,17 +51,17 @@ export default class UuidCommand extends BushCommand { ) { if (typeof args.ign === 'string') args.ign = { match: /\w{1,16}/im.exec(args.ign)!, matches: [] }; - if (!args.ign.match) return await message.util.reply(`${util.emojis.error} Please enter a valid ign.`); + if (!args.ign.match) return await message.util.reply(`${emojis.error} Please enter a valid ign.`); const readableIGN = args.ign.match[0]; try { - const uuid = await util.mcUUID(readableIGN, args.dashed); + const uuid = await mcUUID(readableIGN, args.dashed); return await message.util.reply({ - content: `The uuid for ${util.format.input(readableIGN)} is ${util.format.input(uuid)}`, + content: `The uuid for ${format.input(readableIGN)} is ${format.input(uuid)}`, allowedMentions: AllowedMentions.none() }); } catch (e) { return await message.util.reply({ - content: `${util.emojis.error} Could not find an uuid for ${util.format.input(readableIGN)}.`, + content: `${emojis.error} Could not find an uuid for ${format.input(readableIGN)}.`, allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/utilities/viewRaw.ts b/src/commands/utilities/viewRaw.ts index 5c2c146..8114cef 100644 --- a/src/commands/utilities/viewRaw.ts +++ b/src/commands/utilities/viewRaw.ts @@ -1,4 +1,16 @@ -import { BushCommand, type ArgType, type CommandMessage, type OptArgType, type SlashMessage } from '#lib'; +import { + Arg, + BushCommand, + clientSendAndPermCheck, + codeblock, + colors, + emojis, + inspect, + type ArgType, + type CommandMessage, + type OptArgType, + type SlashMessage +} from '#lib'; import assert from 'assert'; import { ApplicationCommandOptionType, ChannelType, EmbedBuilder, Message, PermissionFlagsBits } from 'discord.js'; @@ -14,7 +26,7 @@ export default class ViewRawCommand extends BushCommand { { id: 'message', description: 'The message to view the raw content of.', - type: util.arg.union('message', 'messageLink'), + type: Arg.union('message', 'messageLink'), readableType: 'message|messageLink', prompt: 'What message would you like to view?', retry: '{error} Choose a valid message.', @@ -23,7 +35,7 @@ export default class ViewRawCommand extends BushCommand { { id: 'channel', description: 'The channel that the message is in.', - type: util.arg.union('textChannel', 'newsChannel', 'threadChannel', 'voiceChannel'), + type: Arg.union('textChannel', 'newsChannel', 'threadChannel', 'voiceChannel'), prompt: 'What channel is the message in?', retry: '{error} Choose a valid channel.', optional: true, @@ -59,7 +71,7 @@ export default class ViewRawCommand extends BushCommand { ], slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), + clientPermissions: (m) => clientSendAndPermCheck(m, [PermissionFlagsBits.EmbedLinks], true), userPermissions: [] }); } @@ -81,7 +93,7 @@ export default class ViewRawCommand extends BushCommand { args.message instanceof Message ? args.message : await args.channel!.messages.fetch(`${args.message}`).catch(() => null); if (!newMessage) return await message.util.reply( - `${util.emojis.error} There was an error fetching that message, make sure that is a valid id and if the message is not in this channel, please provide a channel.` + `${emojis.error} There was an error fetching that message, make sure that is a valid id and if the message is not in this channel, please provide a channel.` ); const Embed = await ViewRawCommand.getRawData(newMessage, { json: args.json, js: args.js }); @@ -94,14 +106,14 @@ export default class ViewRawCommand extends BushCommand { options.json || options.js ? options.json ? JSON.stringify(message.toJSON(), undefined, 2) - : util.inspect(message.toJSON()) || '[No Content]' + : inspect(message.toJSON()) || '[No Content]' : message.content || '[No Content]'; const lang = options.json ? 'json' : options.js ? 'js' : undefined; return new EmbedBuilder() .setFooter({ text: message.author.tag, iconURL: message.author.avatarURL() ?? undefined }) .setTimestamp(message.createdTimestamp) - .setColor(message.member?.roles?.color?.color ?? util.colors.default) + .setColor(message.member?.roles?.color?.color ?? colors.default) .setTitle('Raw Message Information') - .setDescription(await util.codeblock(content, 2048, lang)); + .setDescription(await codeblock(content, 2048, lang)); } } diff --git a/src/commands/utilities/whoHasRole.ts b/src/commands/utilities/whoHasRole.ts index ae96a65..851411a 100644 --- a/src/commands/utilities/whoHasRole.ts +++ b/src/commands/utilities/whoHasRole.ts @@ -1,6 +1,17 @@ -import { BushCommand, ButtonPaginator, OptArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + BushCommand, + ButtonPaginator, + chunk, + clientSendAndPermCheck, + colors, + emojis, + OptArgType, + oxford, + type CommandMessage, + type SlashMessage +} from '#lib'; import assert from 'assert'; -import { ApplicationCommandOptionType, Util, type CommandInteraction, type Role } from 'discord.js'; +import { ApplicationCommandOptionType, escapeMarkdown, type CommandInteraction, type Role } from 'discord.js'; export default class WhoHasRoleCommand extends BushCommand { public constructor() { @@ -24,7 +35,7 @@ export default class WhoHasRoleCommand extends BushCommand { ), slash: true, channel: 'guild', - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [], typing: true }); @@ -44,18 +55,18 @@ export default class WhoHasRoleCommand extends BushCommand { const members = message.guild.members.cache.filter((m) => roles.every((r) => m.roles.cache.has(r))); - const roleMembers = members.map((member) => `${member.user} (${Util.escapeMarkdown(member.user.tag)})`); - const chunkedRoleMembers = util.chunk(roleMembers, 30); + const roleMembers = members.map((member) => `${member.user} (${escapeMarkdown(member.user.tag)})`); + const chunkedRoleMembers = chunk(roleMembers, 30); const title = `Members with ${ roles.length < 4 - ? util.oxford( + ? oxford( rawRoles.map((r) => r.name), 'and' ) : `${rawRoles.length} Roles` } [\`${members.size.toLocaleString()}\`]`; - const color = util.colors.default; + const color = colors.default; const embedPages = chunkedRoleMembers.map((chunk) => ({ title, description: chunk.join('\n'), @@ -63,7 +74,7 @@ export default class WhoHasRoleCommand extends BushCommand { })); if (embedPages.length === 0) { - return await message.util.reply(`${util.emojis.error} No members found matching the given roles.`); + return await message.util.reply(`${emojis.error} No members found matching the given roles.`); } return await ButtonPaginator.send(message, embedPages, null, true); diff --git a/src/commands/utilities/wolframAlpha.ts b/src/commands/utilities/wolframAlpha.ts index 98cac69..b682c85 100644 --- a/src/commands/utilities/wolframAlpha.ts +++ b/src/commands/utilities/wolframAlpha.ts @@ -1,4 +1,15 @@ -import { AllowedMentions, BushCommand, type ArgType, type CommandMessage, type SlashMessage } from '#lib'; +import { + AllowedMentions, + BushCommand, + clientSendAndPermCheck, + colors, + emojis, + inspectCleanRedactCodeblock, + uploadImageToImgur, + type ArgType, + type CommandMessage, + type SlashMessage +} from '#lib'; import { initializeClass as WolframAlphaAPI } from '@notenoughupdates/wolfram-alpha-api'; import assert from 'assert'; import { ApplicationCommandOptionType, EmbedBuilder, type MessageOptions } from 'discord.js'; @@ -34,7 +45,7 @@ export default class WolframAlphaCommand extends BushCommand { } ], slash: true, - clientPermissions: (m) => util.clientSendAndPermCheck(m), + clientPermissions: (m) => clientSendAndPermCheck(m), userPermissions: [] }); } @@ -45,13 +56,13 @@ export default class WolframAlphaCommand extends BushCommand { ) { if (message.util.isSlashMessage(message)) await message.interaction.deferReply(); - args.image && void message.util.reply({ content: `${util.emojis.loading} Loading...`, embeds: [] }); + args.image && void message.util.reply({ content: `${emojis.loading} Loading...`, embeds: [] }); const waApi = WolframAlphaAPI(client.config.credentials.wolframAlphaAppId); const decodedEmbed = new EmbedBuilder().addFields([ { name: '📥 Input', - value: await util.inspectCleanRedactCodeblock(args.expression) + value: await inspectCleanRedactCodeblock(args.expression) } ]); const sendOptions: MessageOptions = { content: null, allowedMentions: AllowedMentions.none() }; @@ -59,21 +70,19 @@ export default class WolframAlphaCommand extends BushCommand { const calculated = await (args.image ? waApi.getSimple({ i: args.expression, timeout: 1, background: '2C2F33', foreground: 'white' }) : waApi.getShort(args.expression)); - decodedEmbed.setTitle(`${util.emojis.successFull} Successfully Queried Expression`).setColor(util.colors.success); + decodedEmbed.setTitle(`${emojis.successFull} Successfully Queried Expression`).setColor(colors.success); if (args.image) { - decodedEmbed.setImage(await util.uploadImageToImgur(calculated.split(',')[1])); + decodedEmbed.setImage(await uploadImageToImgur(calculated.split(',')[1])); decodedEmbed.addFields([{ name: '📤 Output', value: '' }]); } else { - decodedEmbed.addFields([{ name: '📤 Output', value: await util.inspectCleanRedactCodeblock(calculated.toString()) }]); + decodedEmbed.addFields([{ name: '📤 Output', value: await inspectCleanRedactCodeblock(calculated.toString()) }]); } } catch (error) { decodedEmbed - .setTitle(`${util.emojis.errorFull} Unable to Query Expression`) - .setColor(util.colors.error) - .addFields([ - { name: `📤 Error`, value: await util.inspectCleanRedactCodeblock(`${error.name}: ${error.message}`, 'js') } - ]); + .setTitle(`${emojis.errorFull} Unable to Query Expression`) + .setColor(colors.error) + .addFields([{ name: `📤 Error`, value: await inspectCleanRedactCodeblock(`${error.name}: ${error.message}`, 'js') }]); } sendOptions.embeds = [decodedEmbed]; |