diff options
author | IRONM00N <64110067+IRONM00N@users.noreply.github.com> | 2021-08-17 12:31:09 -0400 |
---|---|---|
committer | IRONM00N <64110067+IRONM00N@users.noreply.github.com> | 2021-08-17 12:31:09 -0400 |
commit | d40527d0a2d9f209905750258f71bedff1cdf089 (patch) | |
tree | e017fd844c2135bfc85228d00ef2617d24ce0a3f /src/commands | |
parent | d431ad00754f3f250103deedea495b9bcee73fc0 (diff) | |
download | tanzanite-d40527d0a2d9f209905750258f71bedff1cdf089.tar.gz tanzanite-d40527d0a2d9f209905750258f71bedff1cdf089.tar.bz2 tanzanite-d40527d0a2d9f209905750258f71bedff1cdf089.zip |
turned on ts strict option
Diffstat (limited to 'src/commands')
48 files changed, 262 insertions, 187 deletions
diff --git a/src/commands/admin/channelPermissions.ts b/src/commands/admin/channelPermissions.ts index a13f07a..83230f7 100644 --- a/src/commands/admin/channelPermissions.ts +++ b/src/commands/admin/channelPermissions.ts @@ -1,4 +1,4 @@ -import { GuildChannel, GuildMember, MessageEmbed, Role } from 'discord.js'; +import { GuildMember, MessageEmbed, Role } from 'discord.js'; import { BushCommand, BushMessage } from '../../lib'; export default class ChannelPermissionsCommand extends BushCommand { @@ -63,7 +63,7 @@ export default class ChannelPermissionsCommand extends BushCommand { } ): Promise<unknown> { const failedChannels = []; - for (const channel of message.guild.channels.cache.values()) { + for (const channel of message.guild!.channels.cache.values()) { try { if (channel.isThread()) return; if (channel.permissionsLocked) return; @@ -78,7 +78,7 @@ export default class ChannelPermissionsCommand extends BushCommand { failedChannels.push(channel); } } - const failure = failedChannels.map((e: GuildChannel) => `<#${e.id}>`).join(' '); + const failure = failedChannels.map((e) => `<#${e.id}>`).join(' '); if (failure.length > 2000) { const paginate: MessageEmbed[] = []; for (let i = 0; i < failure.length; i += 2000) { diff --git a/src/commands/config/autoPublishChannel.ts b/src/commands/config/autoPublishChannel.ts index 3381dc2..f058402 100644 --- a/src/commands/config/autoPublishChannel.ts +++ b/src/commands/config/autoPublishChannel.ts @@ -29,7 +29,7 @@ export default class AutoPublishChannelCommand extends BushCommand { name: 'channel', description: 'What channel would you like me to send welcome messages in?', type: 'CHANNEL', - required: false + required: true } ], channel: 'guild', @@ -39,13 +39,13 @@ export default class AutoPublishChannelCommand extends BushCommand { } public override async exec(message: BushMessage, { channel }: { channel: Channel }): Promise<unknown> { - const autoPublishChannels = await message.guild.getSetting('autoPublishChannels'); + const autoPublishChannels = await message.guild!.getSetting('autoPublishChannels'); const newValue = util.addOrRemoveFromArray( autoPublishChannels.includes(channel.id) ? 'remove' : 'add', autoPublishChannels, channel.id ); - await message.guild.setSetting('autoPublishChannels', newValue); + await message.guild!.setSetting('autoPublishChannels', newValue); return await message.util.reply({ content: `${util.emojis.success} Successfully ${ autoPublishChannels.includes(channel.id) ? 'disabled' : 'enabled' diff --git a/src/commands/config/blacklist.ts b/src/commands/config/blacklist.ts index 864081c..57c3015 100644 --- a/src/commands/config/blacklist.ts +++ b/src/commands/config/blacklist.ts @@ -75,9 +75,12 @@ export default class BlacklistCommand extends BushCommand { const targetID = target.id; if (global) { - if (action === 'toggle') { - const blacklistedUsers = (await Global.findByPk(client.config.environment)).blacklistedUsers; - const blacklistedChannels = (await Global.findByPk(client.config.environment)).blacklistedChannels; + if ((action as 'blacklist' | 'unblacklist' | 'toggle') === 'toggle') { + const globalDB = + (await Global.findByPk(client.config.environment)) ?? + (await Global.create({ environment: client.config.environment })); + const blacklistedUsers = globalDB.blacklistedUsers; + const blacklistedChannels = globalDB.blacklistedChannels; action = blacklistedUsers.includes(targetID) || blacklistedChannels.includes(targetID) ? 'unblacklist' : 'blacklist'; } const success = await util @@ -99,9 +102,11 @@ export default class BlacklistCommand extends BushCommand { }); // guild disable } else { + if (!message.guild) + return await message.util.reply(`${util.emojis.error} You have to be in a guild to disable commands.`); const blacklistedChannels = (await message.guild.getSetting('blacklistedChannels')) ?? []; const blacklistedUsers = (await message.guild.getSetting('blacklistedUsers')) ?? []; - if (action === 'toggle') { + if ((action as 'blacklist' | 'unblacklist' | 'toggle') === 'toggle') { action = blacklistedChannels.includes(targetID) ?? blacklistedUsers.includes(targetID) ? 'unblacklist' : 'blacklist'; } const newValue = util.addOrRemoveFromArray( diff --git a/src/commands/config/disable.ts b/src/commands/config/disable.ts index a9318a5..bc6ed47 100644 --- a/src/commands/config/disable.ts +++ b/src/commands/config/disable.ts @@ -69,8 +69,11 @@ export default class DisableCommand extends BushCommand { const commandID = (args.command as BushCommand).id; if (global) { - if (action === 'toggle') { - const disabledCommands = (await Global.findByPk(client.config.environment)).disabledCommands; + if ((action as 'disable' | 'enable' | 'toggle') === 'toggle') { + const disabledCommands = ( + (await Global.findByPk(client.config.environment)) ?? + (await Global.create({ environment: client.config.environment })) + ).disabledCommands; action = disabledCommands.includes(commandID) ? 'disable' : 'enable'; } const success = await util @@ -95,12 +98,12 @@ export default class DisableCommand extends BushCommand { // guild disable } else { - const disabledCommands = await message.guild.getSetting('disabledCommands'); - if (action === 'toggle') { + const disabledCommands = await message.guild!.getSetting('disabledCommands'); + if ((action as 'disable' | 'enable' | 'toggle') === 'toggle') { action = disabledCommands.includes(commandID) ? 'disable' : 'enable'; } const newValue = util.addOrRemoveFromArray(action === 'disable' ? 'remove' : 'add', disabledCommands, commandID); - const success = await message.guild.setSetting('disabledCommands', newValue).catch(() => false); + const success = await message.guild!.setSetting('disabledCommands', newValue).catch(() => false); if (!success) return await message.util.reply({ content: `${util.emojis.error} There was an error **${action.substr( diff --git a/src/commands/config/muteRole.ts b/src/commands/config/muteRole.ts index dee5322..c7a6e75 100644 --- a/src/commands/config/muteRole.ts +++ b/src/commands/config/muteRole.ts @@ -38,7 +38,7 @@ export default class MuteRoleCommand extends BushCommand { } override async exec(message: BushMessage | BushSlashMessage, args: { role: Role }): Promise<void> { - await message.guild.setSetting('muteRole', args.role.id); + await message.guild!.setSetting('muteRole', args.role.id); await message.util.send({ content: `${util.emojis.success} Changed the server's mute role to <@&${args.role.id}>.`, allowedMentions: AllowedMentions.none() diff --git a/src/commands/config/prefix.ts b/src/commands/config/prefix.ts index 9f80633..9d707e0 100644 --- a/src/commands/config/prefix.ts +++ b/src/commands/config/prefix.ts @@ -37,8 +37,8 @@ export default class PrefixCommand extends BushCommand { } override async exec(message: BushMessage | BushSlashMessage, args: { prefix?: string }): Promise<unknown> { - const oldPrefix = await message.guild.getSetting('prefix'); - await message.guild.setSetting('prefix', args.prefix ?? client.config.prefix); + const oldPrefix = await message.guild!.getSetting('prefix'); + await message.guild!.setSetting('prefix', args.prefix ?? client.config.prefix); if (args.prefix) { return await message.util.send({ content: `${util.emojis.success} changed the server's prefix ${oldPrefix ? `from \`${oldPrefix}\`` : ''} to \`${ diff --git a/src/commands/config/punishmentFooter.ts b/src/commands/config/punishmentFooter.ts index d8daf77..d07ce4f 100644 --- a/src/commands/config/punishmentFooter.ts +++ b/src/commands/config/punishmentFooter.ts @@ -39,7 +39,7 @@ export default class PunishmentFooterCommand extends BushCommand { } override async exec(message: BushMessage | BushSlashMessage, args: { ending: string }): Promise<unknown> { - await message.guild.setSetting('punishmentEnding', args.ending || null); + await message.guild!.setSetting('punishmentEnding', args.ending || ''); if (args.ending) return await message.util.send({ content: `${util.emojis.success} Changed the server's punishment footer to \n\`\`\`${Util.cleanCodeBlockContent( diff --git a/src/commands/config/welcomeChannel.ts b/src/commands/config/welcomeChannel.ts index a662802..fc56607 100644 --- a/src/commands/config/welcomeChannel.ts +++ b/src/commands/config/welcomeChannel.ts @@ -37,8 +37,8 @@ export default class WelcomeChannelCommand extends BushCommand { }); } public override async exec(message: BushMessage | BushSlashMessage, args: { channel: Channel }): Promise<unknown> { - const oldChannel = await message.guild.getSetting('welcomeChannel'); - await message.guild.setSetting('welcomeChannel', args.channel.id ?? undefined); + const oldChannel = await message.guild!.getSetting('welcomeChannel'); + await message.guild!.setSetting('welcomeChannel', args.channel.id ?? undefined); if (args.channel) { return await message.util.send( `${util.emojis.success} changed the server's welcome channel ${oldChannel ? `from <#${oldChannel}>` : ''} to <#${ diff --git a/src/commands/dev/eval.ts b/src/commands/dev/eval.ts index 5b44db2..10360cf 100644 --- a/src/commands/dev/eval.ts +++ b/src/commands/dev/eval.ts @@ -70,7 +70,7 @@ export default class EvalCommand extends BushCommand { } args.code = args.code.replace(/[“”]/g, '"').replace(/```*(?:js|ts)?/g, ''); - const code = { + const code: { ts: string | null; js: string; lang: 'ts' | 'js' } = { ts: args.typescript ? args.code : null, js: args.typescript ? transpile(args.code) : args.code, lang: args.typescript ? 'ts' : 'js' @@ -79,7 +79,7 @@ export default class EvalCommand extends BushCommand { const embed = new _MessageEmbed(); const badPhrases = ['delete', 'destroy']; - if (badPhrases.some((p) => code[code.lang].includes(p)) && !args.sudo) { + if (badPhrases.some((p) => code[code.lang]!.includes(p)) && !args.sudo) { return await message.util.send(`${util.emojis.error} This eval was blocked by smooth brain protection™.`); } @@ -119,7 +119,7 @@ export default class EvalCommand extends BushCommand { const inputJS = await util.inspectCleanRedactCodeblock(code.js, 'js'); const inputTS = code.lang === 'ts' ? await util.inspectCleanRedactCodeblock(code.ts, 'ts') : undefined; try { - const rawOutput = code[code.lang].replace(/ /g, '').includes('9+10' || '10+9') ? '21' : await eval(code.js); + const rawOutput = code[code.lang]!.replace(/ /g, '').includes('9+10' || '10+9') ? '21' : await eval(code.js); const output = await util.inspectCleanRedactCodeblock(rawOutput, 'js', { depth: args.sel_depth ?? 0, showHidden: args.hidden, @@ -148,7 +148,7 @@ export default class EvalCommand extends BushCommand { embed.addField('📤 Output', await util.inspectCleanRedactCodeblock(e?.stack || e, 'js')); } - embed.setTimestamp().setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true })); + embed.setTimestamp().setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true }) ?? undefined); if (!args.silent || message.util.isSlash) { await message.util.reply({ embeds: [embed] }); diff --git a/src/commands/dev/reload.ts b/src/commands/dev/reload.ts index 4f11a81..91cabfb 100644 --- a/src/commands/dev/reload.ts +++ b/src/commands/dev/reload.ts @@ -44,7 +44,7 @@ export default class ReloadCommand extends BushCommand { client.inhibitorHandler.reloadAll(); return message.util.send(`🔁 Successfully reloaded! (${new Date().getTime() - s.getTime()}ms)`); } catch (e) { - if (output) void client.logger.error('reloadCommand', output); + if (output!) void client.logger.error('reloadCommand', output); return message.util.send(`An error occurred while reloading:\n${await util.codeblock(e?.stack || e, 2048 - 34, 'js')}`); } } diff --git a/src/commands/dev/say.ts b/src/commands/dev/say.ts index f0a7cbf..1c797ea 100644 --- a/src/commands/dev/say.ts +++ b/src/commands/dev/say.ts @@ -42,6 +42,6 @@ export default class SayCommand extends BushCommand { }); } await message.interaction.reply({ content: 'Attempting to send message.', ephemeral: true }); - return message.channel.send({ content, allowedMentions: AllowedMentions.none() }); + return message.channel!.send({ content, allowedMentions: AllowedMentions.none() }); } } diff --git a/src/commands/dev/setLevel.ts b/src/commands/dev/setLevel.ts index 97527fa..e69b9df 100644 --- a/src/commands/dev/setLevel.ts +++ b/src/commands/dev/setLevel.ts @@ -44,7 +44,8 @@ export default class SetLevelCommand extends BushCommand { } ], ownerOnly: true, - slash: true + slash: true, + channel: 'guild' }); } @@ -58,11 +59,11 @@ export default class SetLevelCommand extends BushCommand { const [levelEntry] = await Level.findOrBuild({ where: { user: user.id, - guild: message.guild.id + guild: message.guild!.id }, defaults: { user: user.id, - guild: message.guild.id + guild: message.guild!.id } }); await levelEntry.update({ xp: Level.convertLevelToXp(level) }); diff --git a/src/commands/dev/sh.ts b/src/commands/dev/sh.ts index 7f048c0..025a308 100644 --- a/src/commands/dev/sh.ts +++ b/src/commands/dev/sh.ts @@ -5,7 +5,7 @@ import { MessageEmbed, Util } from 'discord.js'; import { promisify } from 'util'; const sh = promisify(exec); -const clean = (text) => { +const clean = (text: string | any) => { chalk.toString; if (typeof text === 'string') { return (text = Util.cleanCodeBlockContent(text)); @@ -43,7 +43,7 @@ export default class ShCommand extends BushCommand { const embed = new MessageEmbed() .setColor(util.colors.gray) - .setFooter(message.author.tag, message.author.avatarURL({ dynamic: true })) + .setFooter(message.author.tag, message.author.avatarURL({ dynamic: true }) ?? undefined) .setTimestamp() .setTitle('Shell Command') .addField('📥 Input', await util.codeblock(input, 1024, 'sh')) diff --git a/src/commands/dev/superUser.ts b/src/commands/dev/superUser.ts index 5178684..957e2b7 100644 --- a/src/commands/dev/superUser.ts +++ b/src/commands/dev/superUser.ts @@ -49,7 +49,7 @@ export default class SuperUserCommand extends BushCommand { `${util.emojis.error} I fucked up here is args ${await util.inspectCleanRedactCodeblock(args, 'ts')}` ); - const superUsers = (await Global.findByPk(client.config.environment)).superUsers; + const superUsers: string[] = (await Global.findByPk(client.config.environment))?.superUsers ?? []; let success; if (args.action === 'add') { if (superUsers.includes(args.user.id)) { diff --git a/src/commands/dev/test.ts b/src/commands/dev/test.ts index 60e93c4..151e4a1 100644 --- a/src/commands/dev/test.ts +++ b/src/commands/dev/test.ts @@ -56,9 +56,9 @@ export default class TestCommand extends BushCommand { const embed = new MessageEmbed() .addField('Field Name', 'Field Content') .setAuthor('Author', 'https://www.w3schools.com/w3css/img_snowtops.jpg', 'https://google.com/') - .setColor(message.member.displayColor) + .setColor(message.member?.displayColor ?? util.colors.default) .setDescription('Description') - .setFooter('Footer', message.author.avatarURL()) + .setFooter('Footer', message.author.avatarURL() ?? undefined) .setURL('https://duckduckgo.com/') .setTimestamp() .setImage('https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png') @@ -91,14 +91,15 @@ export default class TestCommand extends BushCommand { return await util.buttonPaginate(message, embeds); } else if (['lots of embeds'].includes(args?.feature?.toLowerCase())) { const description = 'This is a description.'; - const author = { name: 'This is a author', iconURL: message.author.avatarURL({ dynamic: true }) }; - const footer = { text: 'This is a footer', iconURL: message.author.avatarURL({ dynamic: true }) }; + const _avatar = message.author.avatarURL({ dynamic: true }) ?? undefined; + const author = { name: 'This is a author', iconURL: _avatar }; + const footer = { text: 'This is a footer', iconURL: _avatar }; const fields = []; for (let i = 0; i < 25; i++) { fields.push({ name: 'Field ' + i, value: 'Field Value ' + i }); } const c = util.colors; - const o = { description, author, footer, fields }; + const o = { description, author, footer, fields }!; const embeds = [ new MessageEmbed({ ...o, ...{ title: 'Embed Title 0', color: c.red } }).setTimestamp(), @@ -134,10 +135,11 @@ export default class TestCommand extends BushCommand { // }); // }) // ); + if (!message.guild) return await message.util.reply(`${util.emojis.error} This test can only be run in a guild.`); const guildCommands = await message.guild.commands.fetch(); // eslint-disable-next-line @typescript-eslint/no-misused-promises guildCommands.forEach(async (command) => await command.delete()); - const globalCommands = await client.application.commands.fetch(); + const globalCommands = await client.application!.commands.fetch(); // eslint-disable-next-line @typescript-eslint/no-misused-promises globalCommands.forEach(async (command) => await command.delete()); diff --git a/src/commands/fun/minesweeper.ts b/src/commands/fun/minesweeper.ts index 2bec1e9..57909a2 100644 --- a/src/commands/fun/minesweeper.ts +++ b/src/commands/fun/minesweeper.ts @@ -118,6 +118,6 @@ export default class MinesweeperCommand extends BushCommand { returnType: 'emoji' }); const matrix = minesweeper.start(); - return await message.util.reply(matrix.toString()); + return await message.util.reply(matrix?.toString() ?? `${util.emojis.error} Something went wrong.`); } } diff --git a/src/commands/info/avatar.ts b/src/commands/info/avatar.ts index 37d2256..7100afa 100644 --- a/src/commands/info/avatar.ts +++ b/src/commands/info/avatar.ts @@ -42,7 +42,9 @@ export default class AvatarCommand extends BushCommand { .setTimestamp() .setColor(util.colors.default) .setTitle(`${user.tag}'s Avatar`) - .setImage(user.avatarURL({ size: 2048, format: 'png', dynamic: true })); + .setImage( + user.avatarURL({ size: 2048, format: 'png', dynamic: true }) ?? 'https://cdn.discordapp.com/embed/avatars/0.png' + ); await message.util.reply({ embeds: [embed] }); } } diff --git a/src/commands/info/botInfo.ts b/src/commands/info/botInfo.ts index c89c356..37a63ce 100644 --- a/src/commands/info/botInfo.ts +++ b/src/commands/info/botInfo.ts @@ -24,7 +24,7 @@ export default class BotInfoCommand extends BushCommand { repoUrl = repoUrl.substring(0, repoUrl.length - 4); const embed = new MessageEmbed() .setTitle('Bot Info:') - .addField('**Uptime**', util.humanizeDuration(client.uptime), true) + .addField('**Uptime**', util.humanizeDuration(client.uptime!), true) .addField('**Servers**', client.guilds.cache.size.toLocaleString(), true) .addField('**Users**', client.users.cache.size.toLocaleString(), true) .addField('**Discord.js Version**', discordJSVersion, true) diff --git a/src/commands/info/color.ts b/src/commands/info/color.ts index 93dd439..350c23d 100644 --- a/src/commands/info/color.ts +++ b/src/commands/info/color.ts @@ -1,11 +1,11 @@ import { AllowedMentions, BushCommand, BushGuildMember, BushMessage, BushRole, BushSlashMessage } from '@lib'; import { Argument } from 'discord-akairo'; -import { MessageEmbed, Role } from 'discord.js'; +import { Message, MessageEmbed, Role } from 'discord.js'; import { Constructor } from 'tinycolor2'; // eslint-disable-next-line @typescript-eslint/no-var-requires const tinycolor: Constructor = require('tinycolor2'); // this is the only way I got it to work consistently -const isValidTinyColor = (_message: BushMessage, phase: string) => { +const isValidTinyColor = (_message: Message, phase: string) => { // if the phase is a number it converts it to hex incase it could be representing a color in decimal const newPhase = Number.isNaN(phase) ? phase : `#${Number(phase).toString(16)}`; return tinycolor(newPhase).isValid() ? newPhase : null; diff --git a/src/commands/info/guildInfo.ts b/src/commands/info/guildInfo.ts index 2cdf3d5..431b8bd 100644 --- a/src/commands/info/guildInfo.ts +++ b/src/commands/info/guildInfo.ts @@ -58,12 +58,16 @@ export default class GuildInfoCommand extends BushCommand { const guild: Guild | GuildPreview = (args?.guild as Guild | GuildPreview) || (message.guild as Guild); const emojis: string[] = []; const guildAbout: string[] = []; - const guildSecurity = []; + const guildStats: string[] = []; + const guildSecurity: string[] = []; const verifiedGuilds = Object.values(client.consts.mappings.guilds); if (verifiedGuilds.includes(guild.id)) emojis.push(client.consts.mappings.otherEmojis.BUSH_VERIFIED); if (!isPreview && guild instanceof Guild) { - if (guild.premiumTier) emojis.push(client.consts.mappings.otherEmojis['BOOST_' + guild.premiumTier]); + if (guild.premiumTier) + emojis.push( + client.consts.mappings.otherEmojis[('BOOST_' + guild.premiumTier) as keyof typeof client.consts.mappings.otherEmojis] + ); await guild.fetch(); const channelTypes = [ `${client.consts.mappings.otherEmojis.TEXT} ${guild.channels.cache @@ -91,7 +95,7 @@ export default class GuildInfoCommand extends BushCommand { .size.toLocaleString()}` ]; - const guildRegions = []; + const guildRegions: string[] = []; guild.channels.cache.forEach((channel) => { if (!channel.type.includes('VOICE')) return; else if (!guildRegions.includes((channel as BaseGuildVoiceChannel).rtcRegion ?? 'automatic')) { @@ -102,16 +106,16 @@ export default class GuildInfoCommand extends BushCommand { guildAbout.push( `**Owner:** ${guild.members.cache.get(guild.ownerId)?.user.tag}`, `**Created** ${guild.createdAt.toLocaleString()} (${util.dateDelta(guild.createdAt)})`, - `**Members:** ${guild.memberCount.toLocaleString() ?? 0}`, - `**Online:** ${guild.approximatePresenceCount?.toLocaleString() ?? 0}`, - `**Channels:** ${guild.channels.cache.size?.toLocaleString() ?? 0} (${channelTypes.join(', ')})`, - `**Emojis:** ${guild.emojis.cache.size?.toLocaleString() ?? 0}`, - `**Stickers:** ${guild.stickers.cache.size?.toLocaleString() ?? 0}`, - `**Regions:** ${guildRegions.map((region) => client.consts.mappings.regions[region] || region).join(', ')}` + `**Members:** ${guild.memberCount.toLocaleString() ?? 0} (${util.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 as keyof typeof client.consts.mappings.regions] || region) + .join(', ')}` ); if (guild.premiumSubscriptionCount) guildAbout.push( - `**Boosts:** Level ${guild.premiumTier == 'NONE' ? '0' : guild.premiumTier[5]} with ${ + `**Boosts:** Level ${guild.premiumTier == 'NONE' ? 0 : guild.premiumTier[5]} with ${ guild.premiumSubscriptionCount ?? 0 } boosts` ); @@ -123,6 +127,28 @@ export default class GuildInfoCommand extends BushCommand { ); } + if (guild.icon) guildAbout.push(`**Icon:** [link](${guild.iconURL({ dynamic: true, size: 4096, format: 'png' })})`); + if (guild.banner) guildAbout.push(`**Banner:** [link](${guild.bannerURL({ size: 4096, format: 'png' })})`); + if (guild.splash) guildAbout.push(`**Splash:** [link](${guild.splashURL({ size: 4096, format: 'png' })})`); + + guildStats.push( + `**Channels:** ${guild.channels.cache.size.toLocaleString()} / 500 (${channelTypes.join(', ')})`, + // subtract 1 for @everyone role + `**Roles:** ${((guild.roles.cache.size ?? 0) - 1).toLocaleString()} / 250`, + `**Emojis:** ${guild.emojis.cache.size?.toLocaleString() ?? 0} / ${ + guild.premiumTier === 'TIER_3' + ? 500 + : guild.premiumTier === 'TIER_2' + ? 300 + : guild.premiumTier === 'TIER_1' + ? 100 + : 50 + }`, + `**Stickers:** ${guild.stickers.cache.size?.toLocaleString() ?? 0} / ${ + guild.premiumTier === 'TIER_3' ? 60 : guild.premiumTier === 'TIER_2' ? 30 : guild.premiumTier === 'TIER_1' ? 15 : 0 + }` + ); + guildSecurity.push( `**Verification Level**: ${guild.verificationLevel.toLowerCase().replace(/_/g, ' ')}`, `**Explicit Content Filter:** ${guild.explicitContentFilter.toLowerCase().replace(/_/g, ' ')}`, @@ -135,14 +161,17 @@ export default class GuildInfoCommand extends BushCommand { ); } else { guildAbout.push( - `**Members:** ${guild.approximateMemberCount?.toLocaleString()}`, - `**Online:** ${guild.approximatePresenceCount?.toLocaleString()}`, + `**Members:** ${guild.approximateMemberCount?.toLocaleString() ?? 0} (${util.emojis.onlineCircle} ${ + guild.approximatePresenceCount?.toLocaleString() ?? 0 + }, ${util.emojis.offlineCircle} ${( + (guild.approximateMemberCount ?? 0) - (guild.approximatePresenceCount ?? 0) + ).toLocaleString()})`, `**Emojis:** ${(guild as GuildPreview).emojis.size?.toLocaleString() ?? 0}` // `**Stickers:** ${(guild as GuildPreview).stickers.size}` ); } - const guildFeatures = guild.features.sort((a, b) => { + const guildFeatures = guild.features.sort((a, b): number => { const aWeight = client.consts.mappings.features[a]?.weight; const bWeight = client.consts.mappings.features[b]?.weight; @@ -153,6 +182,7 @@ export default class GuildInfoCommand extends BushCommand { } else if (bWeight == undefined) { return -1; } + return 0; }); if (guildFeatures.length) { guildFeatures.forEach((feature) => { @@ -174,6 +204,7 @@ export default class GuildInfoCommand extends BushCommand { .setTitle(guild.name) .setColor(util.colors.default) .addField('» About', guildAbout.join('\n')); + if (guildStats) guildInfoEmbed.addField('» Stats', guildStats.join('\n')); const guildIcon = guild.iconURL({ size: 2048, format: 'png', dynamic: true }); if (guildIcon) { guildInfoEmbed.setThumbnail(guildIcon); diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 691051c..97811da 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -47,7 +47,7 @@ export default class HelpCommand extends BushCommand { message: BushMessage | BushSlashMessage, args: { command: BushCommand | string; showHidden?: boolean } ): Promise<unknown> { - const prefix = client.config.isDevelopment ? 'dev ' : message.util.parsed.prefix; + const prefix = client.config.isDevelopment ? 'dev ' : message.util.parsed?.prefix ?? client.config.prefix; const row = new MessageActionRow(); if (!client.config.isDevelopment && !client.guilds.cache.some((guild) => guild.ownerId === message.author.id)) { @@ -55,11 +55,13 @@ export default class HelpCommand extends BushCommand { new MessageButton({ style: 'LINK', label: 'Invite Me', - url: `https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=2147483647&scope=bot%20applications.commands` + url: `https://discord.com/api/oauth2/authorize?client_id=${ + client.user!.id + }&permissions=2147483647&scope=bot%20applications.commands` }) ); } - if (!client.guilds.cache.get(client.config.supportGuild.id).members.cache.has(message.author.id)) { + if (!client.guilds.cache.get(client.config.supportGuild.id)?.members.cache.has(message.author.id)) { row.addComponents( new MessageButton({ style: 'LINK', @@ -80,7 +82,7 @@ export default class HelpCommand extends BushCommand { const isSuperUser = client.isSuperUser(message.author); const command = args.command ? typeof args.command === 'string' - ? client.commandHandler.modules.get(args.command) || null + ? client.commandHandler.modules.get(args.command) ?? null : args.command : null; if (!isOwner) args.showHidden = false; @@ -98,7 +100,8 @@ export default class HelpCommand extends BushCommand { if (command.superUserOnly && !isSuperUser) { return false; } - return !(command.restrictedGuilds?.includes(message.guild.id) === false && !args.showHidden); + // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain + return !(command.restrictedGuilds?.includes(message.guild?.id!) === false && !args.showHidden); }); const categoryNice = category.id .replace(/(\b\w)/gi, (lc): string => lc.toUpperCase()) diff --git a/src/commands/info/icon.ts b/src/commands/info/icon.ts index 582494c..677fdaf 100644 --- a/src/commands/info/icon.ts +++ b/src/commands/info/icon.ts @@ -22,13 +22,13 @@ export default class IconCommand extends BushCommand { .setTimestamp() .setColor(util.colors.default) .setImage( - message.guild?.iconURL({ + message.guild!.iconURL({ size: 2048, dynamic: true, format: 'png' - }) + })! ) - .setTitle(message.guild.name); + .setTitle(message.guild!.name); await message.util.reply({ embeds: [embed] }); } } diff --git a/src/commands/info/invite.ts b/src/commands/info/invite.ts index 384c59e..615e767 100644 --- a/src/commands/info/invite.ts +++ b/src/commands/info/invite.ts @@ -24,7 +24,9 @@ export default class InviteCommand extends BushCommand { new MessageButton({ style: 'LINK', label: 'Invite Me', - url: `https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=2147483647&scope=bot%20applications.commands` + url: `https://discord.com/api/oauth2/authorize?client_id=${ + client.user!.id + }&permissions=2147483647&scope=bot%20applications.commands` }) ); return await message.util.reply({ content: 'You can invite me here:', components: [ButtonRow] }); diff --git a/src/commands/info/pronouns.ts b/src/commands/info/pronouns.ts index 6f2b074..c7eac7f 100644 --- a/src/commands/info/pronouns.ts +++ b/src/commands/info/pronouns.ts @@ -1,5 +1,5 @@ -import { BushCommand, BushSlashMessage } from '@lib'; -import { Message, MessageEmbed, User } from 'discord.js'; +import { BushCommand, BushMessage, BushSlashMessage } from '@lib'; +import { MessageEmbed, User } from 'discord.js'; import got, { HTTPError } from 'got'; export const pronounMapping = { @@ -60,8 +60,8 @@ export default class PronounsCommand extends BushCommand { slash: true }); } - override async exec(message: Message | BushSlashMessage, args: { user?: User }): Promise<unknown> { - const user = args.user || message.author; + override async exec(message: BushMessage | BushSlashMessage, args: { user?: User }): Promise<unknown> { + const user = args.user ?? message.author; const author = user.id === message.author.id; try { const apiRes: { pronouns: pronounsType } = await got diff --git a/src/commands/info/snowflakeInfo.ts b/src/commands/info/snowflakeInfo.ts index f293219..c4d71da 100644 --- a/src/commands/info/snowflakeInfo.ts +++ b/src/commands/info/snowflakeInfo.ts @@ -58,7 +58,7 @@ export default class SnowflakeInfoCommand extends BushCommand { // Channel if (client.channels.cache.has(snowflake)) { - const channel: Channel = client.channels.cache.get(snowflake); + const channel: Channel = client.channels.cache.get(snowflake)!; const channelInfo = [`**Type:** ${channel.type}`]; if (['dm', 'group'].includes(channel.type)) { const _channel = channel as DMChannel; @@ -89,38 +89,38 @@ export default class SnowflakeInfoCommand extends BushCommand { // Guild else if (client.guilds.cache.has(snowflake)) { - const guild: Guild = client.guilds.cache.get(snowflake); + const guild: Guild = client.guilds.cache.get(snowflake)!; const guildInfo = [ `**Name:** ${guild.name}`, - `**Owner:** ${client.users.cache.get(guild.ownerId)?.tag || '¯\\_(ツ)_/¯'} (${guild.ownerId})`, + `**Owner:** ${client.users.cache.get(guild.ownerId)?.tag ?? '¯\\_(ツ)_/¯'} (${guild.ownerId})`, `**Members:** ${guild.memberCount?.toLocaleString()}` ]; - snowflakeEmbed.setThumbnail(guild.iconURL({ size: 2048, dynamic: true })); + if (guild.icon) snowflakeEmbed.setThumbnail(guild.iconURL({ size: 2048, dynamic: true })!); snowflakeEmbed.addField('» Server Info', guildInfo.join('\n')); snowflakeEmbed.setTitle(`:snowflake: ${guild.name} \`[Server]\``); } // User else if (client.users.cache.has(snowflake)) { - const user: User = client.users.cache.get(snowflake); + const user: User = client.users.cache.get(snowflake)!; const userInfo = [`**Name:** <@${user.id}> (${user.tag})`]; - snowflakeEmbed.setThumbnail(user.avatarURL({ size: 2048, dynamic: true })); + if (user.avatar) snowflakeEmbed.setThumbnail(user.avatarURL({ size: 2048, dynamic: true })!); snowflakeEmbed.addField('» User Info', userInfo.join('\n')); snowflakeEmbed.setTitle(`:snowflake: ${user.tag} \`[User]\``); } // Emoji else if (client.emojis.cache.has(snowflake)) { - const emoji: Emoji = client.emojis.cache.get(snowflake); + const emoji: Emoji = client.emojis.cache.get(snowflake)!; const emojiInfo = [`**Name:** ${emoji.name}`, `**Animated:** ${emoji.animated}`]; - snowflakeEmbed.setThumbnail(emoji.url); + if (emoji.url) snowflakeEmbed.setThumbnail(emoji.url); snowflakeEmbed.addField('» Emoji Info', emojiInfo.join('\n')); snowflakeEmbed.setTitle(`:snowflake: ${emoji.name} \`[Emoji]\``); } // Role - else if (message.guild.roles.cache.has(snowflake)) { - const role: Role = message.guild.roles.cache.get(snowflake); + else if (message.guild && message.guild.roles.cache.has(snowflake)) { + const role: Role = message.guild.roles.cache.get(snowflake)!; const roleInfo = [ `**Name:** <@&${role.id}> (${role.name})`, `**Members:** ${role.members.size}`, diff --git a/src/commands/info/userInfo.ts b/src/commands/info/userInfo.ts index d9922d0..9ec5552 100644 --- a/src/commands/info/userInfo.ts +++ b/src/commands/info/userInfo.ts @@ -1,7 +1,6 @@ -import { BushCommand, BushMessage, BushSlashMessage } from '@lib'; -import { GuildMember, MessageEmbed } from 'discord.js'; +import { BushCommand, BushMessage, BushSlashMessage, BushUser } from '@lib'; +import { MessageEmbed } from 'discord.js'; -// TODO: Allow looking up a user not in the guild and not cached (if possible) // TODO: Re-Implement Status Emojis // TODO: Add bot information export default class UserInfoCommand extends BushCommand { @@ -17,7 +16,7 @@ export default class UserInfoCommand extends BushCommand { args: [ { id: 'user', - type: 'member', + customType: util.arg.union('user', 'bigint'), prompt: { start: 'What user would you like to find information about?', retry: '{error} Choose a valid user to find information about.', @@ -40,48 +39,57 @@ export default class UserInfoCommand extends BushCommand { }); } - public override async exec(message: BushMessage | BushSlashMessage, args: { user: GuildMember }): Promise<unknown> { - const user = args?.user || message.member; + public override async exec(message: BushMessage | BushSlashMessage, args: { user: BushUser | bigint }): Promise<unknown> { + const user = + args?.user === undefined || args?.user === null + ? message.author + : 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.`); + const member = message.guild ? message.guild.members.cache.get(user.id) : undefined; const emojis = []; const superUsers = client.cache.global.superUsers; const userEmbed: MessageEmbed = new MessageEmbed() - .setTitle(user.user.tag) - .setThumbnail(user.user.avatarURL({ size: 2048, format: 'png', dynamic: true })) + .setTitle(user.tag) + .setThumbnail( + user.avatarURL({ size: 2048, format: 'png', dynamic: true }) ?? 'https://cdn.discordapp.com/embed/avatars/0.png' + ) .setTimestamp(); // 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); - const flags = user.user.flags?.toArray(); + const flags = user.flags?.toArray(); if (flags) { flags.forEach((f) => { if (client.consts.mappings.userFlags[f]) { emojis.push(client.consts.mappings.userFlags[f]); - } else emojis.push(f); + } else emojis.push(`\`${f}\``); }); } // Since discord bald I just guess if someone has nitro if ( - Number(user.user.discriminator) < 10 || - client.consts.mappings.maybeNitroDiscrims.includes(user.user.discriminator) || - user.user.displayAvatarURL({ dynamic: true })?.endsWith('.gif') || - user.user.flags?.toArray().includes('PARTNERED_SERVER_OWNER') + Number(user.discriminator) < 10 || + client.consts.mappings.maybeNitroDiscrims.includes(user.discriminator) || + user.displayAvatarURL({ dynamic: true })?.endsWith('.gif') || + user.flags?.toArray().includes('PARTNERED_SERVER_OWNER') ) { emojis.push(client.consts.mappings.otherEmojis.NITRO); } - if (message.guild.ownerId == user.id) emojis.push(client.consts.mappings.otherEmojis.OWNER); - else if (user.permissions.has('ADMINISTRATOR')) emojis.push(client.consts.mappings.otherEmojis.ADMIN); - if (user.premiumSinceTimestamp) emojis.push(client.consts.mappings.otherEmojis.BOOSTER); + if (message.guild?.ownerId == user.id) emojis.push(client.consts.mappings.otherEmojis.OWNER); + else if (member?.permissions.has('ADMINISTRATOR')) emojis.push(client.consts.mappings.otherEmojis.ADMIN); + if (member?.premiumSinceTimestamp) emojis.push(client.consts.mappings.otherEmojis.BOOSTER); - const createdAt = user.user.createdAt.toLocaleString(), - createdAtDelta = util.dateDelta(user.user.createdAt), - joinedAt = user.joinedAt?.toLocaleString(), - joinedAtDelta = util.dateDelta(user.joinedAt, 2), - premiumSince = user.premiumSince?.toLocaleString(), - premiumSinceDelta = util.dateDelta(user.premiumSince, 2); + const createdAt = user.createdAt.toLocaleString(), + createdAtDelta = util.dateDelta(user.createdAt), + joinedAt = member?.joinedAt?.toLocaleString(), + joinedAtDelta = member && member.joinedAt ? util.dateDelta(member.joinedAt, 2) : undefined, + premiumSince = member?.premiumSince?.toLocaleString(), + premiumSinceDelta = member && member.premiumSince ? util.dateDelta(member.premiumSince, 2) : undefined; // General Info const generalInfo = [ @@ -95,27 +103,27 @@ export default class UserInfoCommand extends BushCommand { const serverUserInfo = []; if (joinedAt) serverUserInfo.push( - `**${message.guild.ownerId == user.id ? 'Created Server' : 'Joined'}: ** ${joinedAt} (${joinedAtDelta} ago)` + `**${message.guild!.ownerId == user.id ? 'Created Server' : 'Joined'}: ** ${joinedAt} (${joinedAtDelta} ago)` ); if (premiumSince) serverUserInfo.push(`**Boosting Since:** ${premiumSince} (${premiumSinceDelta} ago)`); - if (user.displayHexColor) serverUserInfo.push(`**Display Color:** ${user.displayHexColor}`); - if (user.id == '322862723090219008' && message.guild.id == client.consts.mappings.guilds.bush) + if (member?.displayHexColor) serverUserInfo.push(`**Display Color:** ${member.displayHexColor}`); + if (user.id == '322862723090219008' && message.guild?.id == client.consts.mappings.guilds.bush) serverUserInfo.push(`**General Deletions:** 1⅓`); if ( ['384620942577369088', '496409778822709251'].includes(user.id) && - message.guild.id == client.consts.mappings.guilds.bush + message.guild?.id == client.consts.mappings.guilds.bush ) serverUserInfo.push(`**General Deletions:** ⅓`); - if (user.nickname) serverUserInfo.push(`**Nickname** ${user.nickname}`); + if (member?.nickname) serverUserInfo.push(`**Nickname** ${member?.nickname}`); if (serverUserInfo.length) - userEmbed.addField('» Server Info', serverUserInfo.join('\n')).setColor(user.displayColor || util.colors.default); + userEmbed.addField('» Server Info', serverUserInfo.join('\n')).setColor(member?.displayColor ?? util.colors.default); // User Presence Info - if (user.presence?.status || user.presence?.clientStatus || user.presence?.activities) { + if (member?.presence?.status || member?.presence?.clientStatus || member?.presence?.activities) { let customStatus = ''; - const activitiesNames = []; - if (user.presence.activities) { - user.presence.activities.forEach((a) => { + const activitiesNames: string[] = []; + if (member.presence.activities) { + member.presence.activities.forEach((a) => { if (a.type == 'CUSTOM' && a.state) { const emoji = `${a.emoji ? `${a.emoji.toString()} ` : ''}`; customStatus = `${emoji}${a.state}`; @@ -124,9 +132,9 @@ export default class UserInfoCommand extends BushCommand { }); } let devices; - if (user.presence.clientStatus) devices = Object.keys(user.presence.clientStatus); + if (member?.presence.clientStatus) devices = Object.keys(member.presence.clientStatus); const presenceInfo = []; - if (user.presence.status) presenceInfo.push(`**Status:** ${user.presence.status}`); + 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', '')}`); if (activitiesNames.length) @@ -137,12 +145,14 @@ export default class UserInfoCommand extends BushCommand { // Important Perms const perms = []; - if (user.permissions.has('ADMINISTRATOR') || message.guild.ownerId == user.id) { + if (member?.permissions.has('ADMINISTRATOR') || message.guild?.ownerId == user.id) { perms.push('`Administrator`'); - } else { - user.permissions.toArray(true).forEach((permission) => { - if (client.consts.mappings.permissions[permission]?.important) { - perms.push(`\`${client.consts.mappings.permissions[permission].name}\``); + } else if (member?.permissions.toArray(true).length) { + member.permissions.toArray(true).forEach((permission) => { + if (client.consts.mappings.permissions[permission as keyof typeof client.consts.mappings.permissions]?.important) { + perms.push( + `\`${client.consts.mappings.permissions[permission as keyof typeof client.consts.mappings.permissions].name}\`` + ); } }); } diff --git a/src/commands/moderation/_lockdown.ts b/src/commands/moderation/_lockdown.ts index 32dbd5b..b7bf4b2 100644 --- a/src/commands/moderation/_lockdown.ts +++ b/src/commands/moderation/_lockdown.ts @@ -35,7 +35,7 @@ export default class LockdownCommand extends BushCommand { public override async exec(message: BushMessage | BushSlashMessage, { all }: { all: boolean }): Promise<unknown> { return await message.util.reply('no'); if (!all) { - if (!['GUILD_TEXT', 'GUILD_NEWS'].includes(message.channel.type)) + if (!['GUILD_TEXT', 'GUILD_NEWS'].includes(message.channel!.type)) return message.util.reply(`${util.emojis.error} You can only lock down text and announcement channels.`); // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/src/commands/moderation/ban.ts b/src/commands/moderation/ban.ts index bda0e2b..e32bf18 100644 --- a/src/commands/moderation/ban.ts +++ b/src/commands/moderation/ban.ts @@ -90,15 +90,15 @@ export default class BanCommand extends BushCommand { force }: { user: User; reason?: { duration: number; contentWithoutTime: string }; days?: number; force: boolean } ): Promise<unknown> { - const member = message.guild.members.cache.get(user.id) as BushGuildMember; + const member = message.guild!.members.cache.get(user.id) as BushGuildMember; const useForce = force && message.author.isOwner(); - const canModerateResponse = util.moderationPermissionCheck(message.member, member, 'ban', true, useForce); + const canModerateResponse = util.moderationPermissionCheck(message.member!, member, 'ban', true, useForce); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); } - if (!Number.isInteger(days) || days < 0 || days > 7) { + if (!Number.isInteger(days) || days! < 0 || days! > 7) { return message.util.reply(`${util.emojis.error} The delete days must be an integer between 0 and 7.`); } @@ -109,12 +109,12 @@ export default class BanCommand extends BushCommand { ? await Argument.cast('duration', client.commandHandler.resolver, message as BushMessage, reason) : reason.duration; } - const parsedReason = reason.contentWithoutTime; + const parsedReason = reason?.contentWithoutTime ?? ''; const responseCode = await member.bushBan({ reason: parsedReason, moderator: message.author, - duration: time, + duration: time! ?? 0, deleteDays: days ?? 0 }); diff --git a/src/commands/moderation/kick.ts b/src/commands/moderation/kick.ts index 2fc133e..8864320 100644 --- a/src/commands/moderation/kick.ts +++ b/src/commands/moderation/kick.ts @@ -59,12 +59,12 @@ export default class KickCommand extends BushCommand { message: BushMessage | BushSlashMessage, { user, reason, force }: { user: BushUser; reason?: string; force: boolean } ): Promise<unknown> { - const member = message.guild.members.cache.get(user.id) as BushGuildMember; + const member = message.guild!.members.cache.get(user.id) as BushGuildMember; if (!member) return await message.util.reply(`${util.emojis.error} You cannot kick members that are not in the server.`); const useForce = force && message.author.isOwner(); - const canModerateResponse = util.moderationPermissionCheck(message.member, member, 'kick', true, useForce); + const canModerateResponse = util.moderationPermissionCheck(message.member!, member, 'kick', true, useForce); if (canModerateResponse !== true) { return message.util.reply(canModerateResponse); diff --git a/src/commands/moderation/modlog.ts b/src/commands/moderation/modlog.ts index 84bb5b5..04264b8 100644 --- a/src/commands/moderation/modlog.ts +++ b/src/commands/moderation/modlog.ts @@ -42,6 +42,7 @@ export default class ModlogCommand extends BushCommand { `**Moderator**: <@!${log.moderator}> (${log.moderator})` ]; if (log.duration) modLog.push(`**Duration**: ${util.humanizeDuration(log.duration)}`); + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing modLog.push(`**Reason**: ${log.reason || 'No Reason Specified.'}`); if (log.evidence) modLog.push(`**Evidence:** ${log.evidence}`); return modLog.join(`\n`); @@ -55,7 +56,7 @@ export default class ModlogCommand extends BushCommand { if (foundUser) { const logs = await ModLog.findAll({ where: { - guild: message.guild.id, + guild: message.guild!.id, user: foundUser.id }, order: [['createdAt', 'ASC']] diff --git a/src/commands/moderation/mute.ts b/src/commands/moderation/mute.ts index 9f66558..e6c9065 100644 --- a/src/commands/moderation/mute.ts +++ b/src/commands/moderation/mute.ts @@ -61,11 +61,11 @@ export default class MuteCommand extends BushCommand { message: BushMessage | BushSlashMessage, { user, reason, force }: { user: BushUser; reason?: { duration: number; contentWithoutTime: string }; force: boolean } ): Promise<unknown> { - const member = message.guild.members.cache.get(user.id) as BushGuildMember; + const member = message.guild!.members.cache.get(user.id) as BushGuildMember; if (!member) return await message.util.reply(`${util.emojis.error} You cannot kick members that are not in the server.`); const useForce = force && message.author.isOwner(); - const canModerateResponse = util.moderationPermissionCheck(message.member, member, 'mute', true, useForce); + const canModerateResponse = util.moderationPermissionCheck(message.member!, member, 'mute', true, useForce); const victimBoldTag = `**${member.user.tag}**`; if (canModerateResponse !== true) { @@ -79,16 +79,16 @@ export default class MuteCommand extends BushCommand { ? await Argument.cast('duration', client.commandHandler.resolver, message as BushMessage, reason) : reason.duration; } - const parsedReason = reason.contentWithoutTime; + const parsedReason = reason?.contentWithoutTime ?? ''; const responseCode = await member.mute({ reason: parsedReason, moderator: message.author, - duration: time + duration: time! ?? 0 }); const responseMessage = async () => { - const prefix = await message.guild.getSetting('prefix'); + const prefix = await message.guild!.getSetting('prefix'); switch (responseCode) { case 'missing permissions': return `${util.emojis.error} Could not mute ${victimBoldTag} because I am missing the \`Manage Roles\` permission.`; diff --git a/src/commands/moderation/purge.ts b/src/commands/moderation/purge.ts index 4f1a5a6..b391ff6 100644 --- a/src/commands/moderation/purge.ts +++ b/src/commands/moderation/purge.ts @@ -1,3 +1,4 @@ +import { Message } from 'discord.js'; import { BushCommand, BushMessage } from '../../lib'; export default class PurgeCommand extends BushCommand { @@ -60,10 +61,10 @@ export default class PurgeCommand extends BushCommand { else { await message.util .send(`${util.emojis.success} Successfully purged **${purged.size}** messages.`) - .then(async (purgeMessage: BushMessage) => { + .then(async (purgeMessage) => { if (!message.util.isSlash) { await util.sleep(5); - await purgeMessage.delete().catch(() => {}); + await (purgeMessage as Message).delete().catch(() => {}); } }); } diff --git a/src/commands/moderation/removeReactionEmoji.ts b/src/commands/moderation/removeReactionEmoji.ts index 075b822..4dfd074 100644 --- a/src/commands/moderation/removeReactionEmoji.ts +++ b/src/commands/moderation/removeReactionEmoji.ts @@ -43,9 +43,9 @@ export default class RemoveReactionEmojiCommand extends BushCommand { const id = !['bigint', 'string'].includes(typeof emoji); const emojiID = !id ? `${emoji}` : (emoji as Emoji).id; const success = await messageToRemoveFrom.reactions.cache - .get(emojiID) - .remove() - .catch(() => {}); + ?.get(emojiID!) + ?.remove() + ?.catch(() => {}); if (success) { return await message.util.reply( `${util.emojis.success} Removed all reactions of \`${id ? emojiID : emoji}\` from the message with the id of \`${ diff --git a/src/commands/moderation/role.ts b/src/commands/moderation/role.ts index 0118f22..4575a11 100644 --- a/src/commands/moderation/role.ts +++ b/src/commands/moderation/role.ts @@ -94,26 +94,26 @@ export default class RoleCommand extends BushCommand { message: BushMessage | BushSlashMessage, { action, user, role, duration }: { action: 'add' | 'remove'; user: BushGuildMember; role: BushRole; duration: number } ): Promise<unknown> { - if (!message.member.permissions.has('MANAGE_ROLES')) { + if (!message.member!.permissions.has('MANAGE_ROLES')) { 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]; if (a.id == role.id) mappedRole = a; } - if (!mappedRole || !mappings.roleWhitelist[mappedRole.name]) { + if (!mappedRole! || !mappings.roleWhitelist[mappedRole.name as keyof typeof mappings.roleWhitelist]) { return await message.util.reply({ content: `${util.emojis.error} <@&${role.id}> is not whitelisted, and you do not have manage roles permission.`, allowedMentions: AllowedMentions.none() }); } - const allowedRoles = mappings.roleWhitelist[mappedRole.name].map((r) => { + const allowedRoles = mappings.roleWhitelist[mappedRole.name as keyof typeof mappings.roleWhitelist].map((r) => { for (let i = 0; i < mappings.roleMap.length; i++) { if (mappings.roleMap[i].name == r) return mappings.roleMap[i].id; } return; }); - if (!message.member.roles.cache.some((role) => allowedRoles.includes(role.id))) { + if (!message.member!.roles.cache.some((role) => allowedRoles.includes(role.id))) { return await message.util.reply({ content: `${util.emojis.error} <@&${role.id}> is whitelisted, but you do not have any of the roles required to manage it.`, allowedMentions: AllowedMentions.none() @@ -125,8 +125,8 @@ export default class RoleCommand extends BushCommand { const responseCode = action === 'add' - ? await user.addRole({ moderator: message.member, addToModlog: shouldLog, role, duration }) - : await user.removeRole({ moderator: message.member, addToModlog: shouldLog, role, duration }); + ? await user.addRole({ moderator: message.member!, addToModlog: shouldLog, role, duration }) + : await user.removeRole({ moderator: message.member!, addToModlog: shouldLog, role, duration }); const responseMessage = () => { switch (responseCode) { diff --git a/src/commands/moderation/slowmode.ts b/src/commands/moderation/slowmode.ts index ec9a9de..1d47616 100644 --- a/src/commands/moderation/slowmode.ts +++ b/src/commands/moderation/slowmode.ts @@ -58,9 +58,9 @@ export default class SlowModeCommand extends BushCommand { channel: TextChannel | ThreadChannel | BushTextChannel | BushNewsChannel | BushThreadChannel | NewsChannel; } ): Promise<unknown> { - if (message.channel.type === 'DM') + if (message.channel!.type === 'DM') return await message.util.reply(`${util.emojis.error} This command cannot be run in dms.`); - if (!channel) channel = message.channel; + if (!channel) channel = message.channel as any; if (!(channel instanceof TextChannel) && !(channel instanceof ThreadChannel)) return await message.util.reply(`${util.emojis.error} <#${channel.id}> is not a text or thread channel.`); if (length) { diff --git a/src/commands/moderation/unban.ts b/src/commands/moderation/unban.ts index 545d75c..f13e7f6 100644 --- a/src/commands/moderation/unban.ts +++ b/src/commands/moderation/unban.ts @@ -58,7 +58,7 @@ export default class UnbanCommand extends BushCommand { if (!(user instanceof User)) { user = util.resolveUser(user, client.users.cache) as BushUser; } - const responseCode = await message.guild.unban({ + const responseCode = await message.guild!.unban({ user, moderator: message.author, reason diff --git a/src/commands/moderation/unmute.ts b/src/commands/moderation/unmute.ts index 918c27f..7e93d31 100644 --- a/src/commands/moderation/unmute.ts +++ b/src/commands/moderation/unmute.ts @@ -56,8 +56,8 @@ export default class UnmuteCommand extends BushCommand { { user, reason }: { user: BushUser; reason?: string } ): Promise<unknown> { const error = util.emojis.error; - const member = message.guild.members.cache.get(user.id) as BushGuildMember; - const canModerateResponse = util.moderationPermissionCheck(message.member, member, 'unmute'); + const member = message.guild!.members.cache.get(user.id) as BushGuildMember; + const canModerateResponse = util.moderationPermissionCheck(message.member!, member, 'unmute'); const victimBoldTag = `**${member.user.tag}**`; if (canModerateResponse !== true) { @@ -70,7 +70,7 @@ export default class UnmuteCommand extends BushCommand { }); const responseMessage = async () => { - const prefix = await message.guild.getSetting('prefix'); + const prefix = await message.guild!.getSetting('prefix'); switch (responseCode) { case 'missing permissions': return `${error} Could not unmute ${victimBoldTag} because I am missing the \`Manage Roles\` permission.`; diff --git a/src/commands/moderation/warn.ts b/src/commands/moderation/warn.ts index 1aa14c3..33ac2a3 100644 --- a/src/commands/moderation/warn.ts +++ b/src/commands/moderation/warn.ts @@ -59,9 +59,9 @@ export default class WarnCommand extends BushCommand { message: BushMessage | BushSlashMessage, { user, reason, force }: { user: BushUser; reason: string; force: boolean } ): Promise<unknown> { - const member = message.guild.members.cache.get(user.id) as BushGuildMember; + const member = message.guild!.members.cache.get(user.id) as BushGuildMember; const useForce = force && message.author.isOwner(); - const canModerateResponse = util.moderationPermissionCheck(message.member, member, 'warn', true, useForce); + const canModerateResponse = util.moderationPermissionCheck(message.member!, member, 'warn', true, useForce); const victimBoldTag = `**${member.user.tag}**`; if (canModerateResponse !== true) { @@ -81,12 +81,12 @@ export default class WarnCommand extends BushCommand { case 'failed to dm': return message.util.reply( `${util.emojis.warn} **${member.user.tag}** has been warned for the ${util.ordinal( - caseNum + caseNum ?? 0 )} time, however I could not send them a dm.` ); case 'success': return message.util.reply( - `${util.emojis.success} Successfully warned **${member.user.tag}** for the ${util.ordinal(caseNum)} time.` + `${util.emojis.success} Successfully warned **${member.user.tag}** for the ${util.ordinal(caseNum ?? 0)} time.` ); } } diff --git a/src/commands/moulberry-bush/capePerms.ts b/src/commands/moulberry-bush/capePerms.ts index eb1ab89..2481e3e 100644 --- a/src/commands/moulberry-bush/capePerms.ts +++ b/src/commands/moulberry-bush/capePerms.ts @@ -48,7 +48,7 @@ export default class CapePermissionsCommand extends BushCommand { perms: string[]; } - let capeperms: Capeperms, uuid: string; + let capeperms: Capeperms | null, uuid: string; try { uuid = await util.findUUID(args.ign); } catch (e) { diff --git a/src/commands/moulberry-bush/giveawayPing.ts b/src/commands/moulberry-bush/giveawayPing.ts index 4abc6ab..4caaf0c 100644 --- a/src/commands/moulberry-bush/giveawayPing.ts +++ b/src/commands/moulberry-bush/giveawayPing.ts @@ -24,7 +24,7 @@ export default class GiveawayPingCommand extends BushCommand { } public override async exec(message: BushMessage): Promise<unknown> { - if (!message.member.permissions.has('MANAGE_GUILD')) + if (!message.member!.permissions.has('MANAGE_GUILD')) await message.util.reply(`${util.emojis.error} You are missing the \`manage server\` permission.`); await message.delete().catch(() => {}); diff --git a/src/commands/moulberry-bush/level.ts b/src/commands/moulberry-bush/level.ts index c202863..02d66be 100644 --- a/src/commands/moulberry-bush/level.ts +++ b/src/commands/moulberry-bush/level.ts @@ -36,7 +36,8 @@ export default class LevelCommand extends BushCommand { required: false } ], - slash: true + slash: true, + channel: 'guild' }); } @@ -143,6 +144,7 @@ export default class LevelCommand extends BushCommand { // 'lel.png' // ) // ); - await message.reply(await this.getResponse(user || message.author, message.guild)); + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + await message.reply(await this.getResponse(user || message.author, message.guild!)); } } diff --git a/src/commands/moulberry-bush/report.ts b/src/commands/moulberry-bush/report.ts index e91420b..878337b 100644 --- a/src/commands/moulberry-bush/report.ts +++ b/src/commands/moulberry-bush/report.ts @@ -59,7 +59,7 @@ export default class ReportCommand extends BushCommand { message: BushMessage, { member, evidence }: { member: GuildMember; evidence: string } ): Promise<unknown> { - if (message.guild.id != client.consts.mappings.guilds.bush) + if (message.guild!.id != client.consts.mappings.guilds.bush) return await message.util.reply(`${util.emojis.error} This command can only be run in Moulberry's bush.`); if (!member) return await message.util.reply(`${util.emojis.error} Choose someone to report`); if (member.user.id === '322862723090219008') @@ -76,14 +76,14 @@ export default class ReportCommand extends BushCommand { const reportEmbed = new MessageEmbed() .setFooter(`Reporter ID: ${message.author.id} Reported ID: ${member.user.id}`) .setTimestamp() - .setAuthor(`Report From: ${message.author.tag}`, message.author.avatarURL({ dynamic: true })) + .setAuthor(`Report From: ${message.author.tag}`, message.author.avatarURL({ dynamic: true }) ?? undefined) .setTitle('New Report') .setColor(util.colors.red) .setDescription(evidence) .addField( 'Reporter', `**Name:**${message.author.tag} <@${message.author.id}>\n**Joined:** ${moment( - message.member.joinedTimestamp + message.member!.joinedTimestamp ).fromNow()}\n**Created:** ${moment(message.author.createdTimestamp).fromNow()}\n**Sent From**: <#${ message.channel.id }> [Jump to context](${message.url})`, @@ -99,11 +99,11 @@ export default class ReportCommand extends BushCommand { //reusing code pog if (message.attachments.size > 0) { - const fileName = message.attachments.first().name.toLowerCase(); + const fileName = message.attachments.first()!.name!.toLowerCase(); if (fileName.endsWith('.png') || fileName.endsWith('.jpg') || fileName.endsWith('.gif') || fileName.endsWith('.webp')) { - reportEmbed.setImage(message.attachments.first().url); + reportEmbed.setImage(message.attachments.first()!.url); } else { - reportEmbed.addField('Attachment', message.attachments.first().url); + reportEmbed.addField('Attachment', message.attachments.first()!.url); } } const reportChannel = client.channels.cache.get('782972723654688848') as unknown as BushTextChannel; diff --git a/src/commands/moulberry-bush/rule.ts b/src/commands/moulberry-bush/rule.ts index eb767a8..bf44dad 100644 --- a/src/commands/moulberry-bush/rule.ts +++ b/src/commands/moulberry-bush/rule.ts @@ -106,10 +106,10 @@ export default class RuleCommand extends BushCommand { public override async exec(message: BushMessage, { rule, user }: { rule: undefined | number; user: User }): Promise<unknown> { const rulesEmbed = new MessageEmbed() .setColor('#ef3929') - .setFooter(`Triggered by ${message.author.tag}`, message.author.avatarURL({ dynamic: true })) + .setFooter(`Triggered by ${message.author.tag}`, message.author.avatarURL({ dynamic: true }) ?? undefined) .setTimestamp(); - if (rule > 12 || rule < 1) { + if (rule !== undefined && (rule > 12 || rule < 1)) { rule = undefined; } if (rule) { @@ -131,7 +131,7 @@ export default class RuleCommand extends BushCommand { // If the original message was a reply -> imitate it message.reference?.messageId && !message.util.isSlash ? await message.channel.messages.fetch(message.reference.messageId).then(async (message) => { - await message.util.reply({ embeds: [rulesEmbed], allowedMentions: AllowedMentions.users() }); + await message.util!.reply({ embeds: [rulesEmbed], allowedMentions: AllowedMentions.users() }); }) : await message.util.send({ embeds: [rulesEmbed], allowedMentions: AllowedMentions.users() }) ); diff --git a/src/commands/skyblock-reborn/chooseColor.ts b/src/commands/skyblock-reborn/chooseColor.ts index 4be2243..1d86899 100644 --- a/src/commands/skyblock-reborn/chooseColor.ts +++ b/src/commands/skyblock-reborn/chooseColor.ts @@ -122,7 +122,7 @@ export default class ChooseColorCommand extends BushCommand { message: BushMessage | BushSlashMessage, args: { color: Role | RoleResolvable } ): Promise<unknown> { - if (message.guild.id != client.consts.mappings.guilds.sbr) { + if (message.guild!.id != client.consts.mappings.guilds.sbr) { return await message.util.reply(`${util.emojis.error} This command can only be run in Skyblock: Reborn.`); } const allowedRoles: Snowflake[] = [ @@ -134,7 +134,7 @@ export default class ChooseColorCommand extends BushCommand { !( allowedRoles.some((role) => (message.member as BushGuildMember).roles.cache.has(role)) || (message.member as BushGuildMember).permissions.has('ADMINISTRATOR') || - message.guild.ownerId === message.author.id + message.guild!.ownerId === message.author.id ) ) { const allowed = util.oxford( diff --git a/src/commands/utilities/activity.ts b/src/commands/utilities/activity.ts index 0962fff..8bdfc21 100644 --- a/src/commands/utilities/activity.ts +++ b/src/commands/utilities/activity.ts @@ -1,4 +1,4 @@ -import { VoiceChannel } from 'discord.js'; +import { Message, VoiceChannel } from 'discord.js'; import { BushCommand, BushMessage, BushSlashMessage } from '../../lib'; const activityMap = { @@ -9,7 +9,7 @@ const activityMap = { 'Chess in the Park': '832012774040141894' }; -function map(phase) { +function map(phase: string) { if (['yt', 'youtube'].includes(phase)) return activityMap['YouTube Together']; else if (['chess', 'park'].includes(phase)) return activityMap['Chess in the Park']; else if (['poker'].includes(phase)) return activityMap['Poker Night']; @@ -19,7 +19,7 @@ function map(phase) { } // eslint-disable-next-line @typescript-eslint/no-unused-vars -const activityTypeCaster = (_message: BushMessage, phrase: string) => { +const activityTypeCaster = (_message: Message, phrase: string) => { if (!phrase) return null; const mappedPhrase = map(phrase); if (mappedPhrase) return mappedPhrase; diff --git a/src/commands/utilities/decode.ts b/src/commands/utilities/decode.ts index 9f56cfc..05e988a 100644 --- a/src/commands/utilities/decode.ts +++ b/src/commands/utilities/decode.ts @@ -95,17 +95,20 @@ export default class DecodeCommand extends BushCommand { message: BushMessage | AkairoMessage, { from, to, data }: { from: BufferEncoding; to: BufferEncoding; data: string } ): Promise<unknown> { + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing const encodeOrDecode = util.capitalizeFirstLetter(message?.util?.parsed?.alias || 'decoded'); const decodedEmbed = new MessageEmbed() .setTitle(`${encodeOrDecode} Information`) - .addField('📥 Input', await util.inspectCleanRedactCodeblock(data, null)); + .addField('📥 Input', await util.inspectCleanRedactCodeblock(data, undefined)); try { const decoded = Buffer.from(data, from).toString(to); - decodedEmbed.setColor(util.colors.success).addField('📤 Output', await util.inspectCleanRedactCodeblock(decoded, null)); + decodedEmbed + .setColor(util.colors.success) + .addField('📤 Output', await util.inspectCleanRedactCodeblock(decoded, undefined)); } catch (error) { decodedEmbed .setColor(util.colors.error) - .addField(`📤 Error ${encodeOrDecode.slice(1)}ing`, await util.inspectCleanRedactCodeblock(error.stack, null)); + .addField(`📤 Error ${encodeOrDecode.slice(1)}ing`, await util.inspectCleanRedactCodeblock(error.stack, undefined)); } return await message.util.reply({ embeds: [decodedEmbed], allowedMentions: AllowedMentions.none() }); } diff --git a/src/commands/utilities/price.ts b/src/commands/utilities/price.ts index a68c01d..921784f 100644 --- a/src/commands/utilities/price.ts +++ b/src/commands/utilities/price.ts @@ -112,6 +112,8 @@ export default class PriceCommand extends BushCommand { let parsedItem = item.toString().toUpperCase().replace(/ /g, '_').replace(/'S/g, ''); const priceEmbed = new MessageEmbed(); + if (bazaar?.success === false) errors.push('bazaar'); + if (errors?.length) { priceEmbed.setFooter(`Could not fetch data from ${util.oxford(errors, 'and', '')}`); } @@ -127,8 +129,8 @@ export default class PriceCommand extends BushCommand { // fuzzy search if (!strict) parsedItem = new Fuse(Array.from(itemNames))?.search(parsedItem)[0]?.item; - // iif bazaar item then it there should not be any ah data - if (bazaar['products'][parsedItem]) { + // if its a bazaar item then it there should not be any ah data + if (bazaar['products']?.[parsedItem]) { const bazaarPriceEmbed = new MessageEmbed() .setColor(errors?.length ? util.colors.warn : util.colors.success) .setTitle(`Bazaar Information for **${parsedItem}**`) @@ -168,8 +170,12 @@ export default class PriceCommand extends BushCommand { return await message.util.reply({ embeds: [priceEmbed] }); // helper functions - function addBazaarInformation(Information: string, digits: number, commas: boolean): string { - const price = bazaar?.products[parsedItem]?.quick_status?.[Information]; + function addBazaarInformation( + Information: keyof Bazaar['products'][string]['quick_status'], + digits: number, + commas: boolean + ): string { + const price = bazaar?.products?.[parsedItem]?.quick_status?.[Information]; const roundedPrice = Number(Number(price).toFixed(digits)); return commas ? roundedPrice?.toLocaleString() : roundedPrice?.toString(); } diff --git a/src/commands/utilities/viewraw.ts b/src/commands/utilities/viewraw.ts index e783dec..f6be382 100644 --- a/src/commands/utilities/viewraw.ts +++ b/src/commands/utilities/viewraw.ts @@ -70,18 +70,21 @@ export default class ViewRawCommand extends BushCommand { return await message.util.reply({ embeds: [messageEmbed] }); } - public static async getRawData(message: BushMessage, options: { json?: boolean; js: boolean }): Promise<unknown> { + public static async getRawData(message: BushMessage, options: { json?: boolean; js: boolean }): Promise<MessageEmbed> { const content = options.json || options.js ? options.json ? inspect(JSON.stringify(message.toJSON())) : inspect(message.toJSON()) || '[No Content]' : message.content || '[No Content]'; - return new MessageEmbed() - .setFooter(message.author.tag, message.author.avatarURL({ dynamic: true })) - .setTimestamp(message.createdTimestamp) - .setColor(message.member?.roles?.color?.color || util.colors.default) - .setTitle('Raw Message Information') - .setDescription(await util.codeblock(content, 2048, 'js')); + return ( + new MessageEmbed() + .setFooter(message.author.tag, message.author.avatarURL({ dynamic: true }) ?? undefined) + .setTimestamp(message.createdTimestamp) + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + .setColor(message.member?.roles?.color?.color || util.colors.default) + .setTitle('Raw Message Information') + .setDescription(await util.codeblock(content, 2048, 'js')) + ); } } |