diff options
author | IRONM00N <64110067+IRONM00N@users.noreply.github.com> | 2022-08-20 23:07:02 -0400 |
---|---|---|
committer | IRONM00N <64110067+IRONM00N@users.noreply.github.com> | 2022-08-20 23:07:02 -0400 |
commit | b81f9e8b73cb520ad5ae916c3e571ea55f4ca489 (patch) | |
tree | 25d7f42d66c3e3190022ece043c86082a9e85709 /src | |
parent | f2e5cfff7dc275bd93fac446a508b7d18ecd6c58 (diff) | |
download | tanzanite-b81f9e8b73cb520ad5ae916c3e571ea55f4ca489.tar.gz tanzanite-b81f9e8b73cb520ad5ae916c3e571ea55f4ca489.tar.bz2 tanzanite-b81f9e8b73cb520ad5ae916c3e571ea55f4ca489.zip |
fix ts composite shit, replace got with native fetch, update deps
Diffstat (limited to 'src')
36 files changed, 296 insertions, 612 deletions
@@ -1,11 +1,13 @@ +console.log('Tanzanite is Starting'); + import { init } from '../lib/utils/BushLogger.js'; // creates proxies on console.log and console.warn // also starts a REPL session init(); +import { config } from '#config'; import { dirname } from 'path'; import { fileURLToPath } from 'url'; -import { default as config } from '../config/options.js'; import { Sentry } from '../lib/common/Sentry.js'; import { BushClient } from '../lib/extensions/discord-akairo/BushClient.js'; @@ -16,7 +18,6 @@ const client = new BushClient(config); if (!isDry) await client.dbPreInit(); await client.init(); if (isDry) { - await client.destroy(); process.exit(0); } else { await client.start(); diff --git a/src/commands/admin/channelPermissions.ts b/src/commands/admin/channelPermissions.ts index 21abd04..0b09e54 100644 --- a/src/commands/admin/channelPermissions.ts +++ b/src/commands/admin/channelPermissions.ts @@ -1,5 +1,6 @@ import { Arg, + BushCommand, ButtonPaginator, clientSendAndPermCheck, emojis, @@ -10,7 +11,6 @@ import { } from '#lib'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; -import { BushCommand } from '../../../lib/extensions/discord-akairo/BushCommand.js'; export default class ChannelPermissionsCommand extends BushCommand { public constructor() { diff --git a/src/commands/admin/roleAll.ts b/src/commands/admin/roleAll.ts index a48bd6b..54afc2a 100644 --- a/src/commands/admin/roleAll.ts +++ b/src/commands/admin/roleAll.ts @@ -7,7 +7,6 @@ import { type CommandMessage, type SlashMessage } from '#lib'; - import assert from 'assert/strict'; import { ApplicationCommandOptionType, PermissionFlagsBits, type GuildMember } from 'discord.js'; diff --git a/src/commands/config/config.ts b/src/commands/config/config.ts index f6b8bfa..39a44d1 100644 --- a/src/commands/config/config.ts +++ b/src/commands/config/config.ts @@ -15,7 +15,6 @@ import { type SlashMessage } from '#lib'; import assert from 'assert/strict'; - import { type ArgumentGeneratorReturn, type SlashOption } from 'discord-akairo'; import { ActionRowBuilder, diff --git a/src/commands/config/disable.ts b/src/commands/config/disable.ts index 00dea76..f9abb4a 100644 --- a/src/commands/config/disable.ts +++ b/src/commands/config/disable.ts @@ -11,7 +11,7 @@ import { } from '#lib'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, AutocompleteInteraction, PermissionFlagsBits } from 'discord.js'; -import Fuse from 'fuse.js'; +import { default as Fuse } from 'fuse.js'; assert(Fuse); diff --git a/src/commands/dev/eval.ts b/src/commands/dev/eval.ts index 04db2eb..fdef3ac 100644 --- a/src/commands/dev/eval.ts +++ b/src/commands/dev/eval.ts @@ -45,7 +45,6 @@ import { ReactionCollector, SelectMenuComponent } from 'discord.js'; -import got from 'got'; import path from 'path'; import ts from 'typescript'; import { fileURLToPath } from 'url'; @@ -57,7 +56,7 @@ const { transpile } = ts, /* eslint-enable @typescript-eslint/no-unused-vars */ // prettier-ignore -assertAll(ActivePunishment, BushCommand, Global, Guild, Level, ModLog, Shared, StickyRole, Snowflake_, Canvas, exec, ActionRow, ButtonComponent, ButtonInteraction, Collection, Collector, CommandInteraction, ContextMenuCommandInteraction, DMChannel, Embed, Emoji, InteractionCollector, Message, Attachment, MessageCollector, OAuth2Scopes, PermissionFlagsBits, PermissionsBitField, ReactionCollector, SelectMenuComponent, path, ts, fileURLToPath, promisify, assert, got, transpile, 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, InteractionCollector, Message, Attachment, MessageCollector, OAuth2Scopes, PermissionFlagsBits, PermissionsBitField, ReactionCollector, SelectMenuComponent, path, ts, fileURLToPath, promisify, assert, transpile, sh, SnowflakeUtil, __dirname); export default class EvalCommand extends BushCommand { public constructor() { diff --git a/src/commands/dev/reload.ts b/src/commands/dev/reload.ts index 40d53eb..8125015 100644 --- a/src/commands/dev/reload.ts +++ b/src/commands/dev/reload.ts @@ -8,17 +8,6 @@ export default class ReloadCommand extends BushCommand { description: 'Reloads the bot', usage: ['reload'], examples: ['reload'], - // args: [ - // { - // id: 'fast', - // description: 'Whether or not to use esbuild for fast compiling.', - // match: 'flag', - // flag: ['--fast'], - // prompt: 'Would you like to use esbuild for fast compiling?', - // optional: true, - // slashType: ApplicationCommandOptionType.Boolean - // } - // ], ownerOnly: true, typing: true, slash: true, @@ -27,13 +16,13 @@ export default class ReloadCommand extends BushCommand { }); } - public override async exec(message: CommandMessage | SlashMessage /* args: { fast: ArgType<'flag'> } */) { + public override async exec(message: CommandMessage | SlashMessage) { 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 shell(`yarn build:${/* args.fast ? 'esbuild' : */ 'tsc'}`); + output = await shell(`yarn build`); await Promise.all([ this.client.commandHandler.reloadAll(), this.client.listenerHandler.reloadAll(), diff --git a/src/commands/dev/syncAutomod.ts b/src/commands/dev/syncAutomod.ts index c78e6c0..3dbd0be 100644 --- a/src/commands/dev/syncAutomod.ts +++ b/src/commands/dev/syncAutomod.ts @@ -1,5 +1,4 @@ import { BushCommand, clientSendAndPermCheck, emojis, Shared, type CommandMessage, type SlashMessage } from '#lib'; -import got from 'got'; import typescript from 'typescript'; import { NodeVM } from 'vm2'; @@ -22,10 +21,12 @@ export default class SyncAutomodCommand extends BushCommand { if (!message.author.isOwner() && message.author.id !== '497789163555389441') 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; - const badWords = (await got.get('https://raw.githubusercontent.com/NotEnoughUpdates/bush-bot/master/src/lib/badwords.ts')) - .body; + const badLinks = await fetch('https://raw.githubusercontent.com/NotEnoughUpdates/bush-bot/master/src/lib/badlinks.ts').then( + (p) => p.text() + ); + const badWords = await fetch('https://raw.githubusercontent.com/NotEnoughUpdates/bush-bot/master/src/lib/badwords.ts').then( + (p) => p.text() + ); const transpiledBadLinks = typescript.transpileModule(badLinks, {}).outputText; const transpiledBadWords = typescript.transpileModule(badWords, {}).outputText; diff --git a/src/commands/index.ts b/src/commands/index.ts index a9db0de..59801c7 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -62,7 +62,7 @@ export { default as ServerStatusCommand } from './moulberry-bush/serverStatus.js export { default as ActivityCommand } from './utilities/activity.js'; export { default as CalculatorCommand } from './utilities/calculator.js'; export { default as DecodeCommand } from './utilities/decode.js'; -export { default as HashCommand } from './utilities/hash.js'; +// export { default as HashCommand } from './utilities/hash.js'; export { default as PriceCommand } from './utilities/price.js'; export { default as RemindCommand } from './utilities/remind.js'; export { default as RemindersCommand } from './utilities/reminders.js'; diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 62f177e..df18403 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -20,7 +20,7 @@ import { EmbedBuilder, PermissionFlagsBits } from 'discord.js'; -import Fuse from 'fuse.js'; +import { default as Fuse } from 'fuse.js'; import packageDotJSON from '../../../package.json' assert { type: 'json' }; assert(Fuse); diff --git a/src/commands/leveling/level.ts b/src/commands/leveling/level.ts index eda43f2..219ae19 100644 --- a/src/commands/leveling/level.ts +++ b/src/commands/leveling/level.ts @@ -13,11 +13,7 @@ import { SimplifyNumber } from '@notenoughupdates/simplify-number'; import assert from 'assert/strict'; import canvas from 'canvas'; import { ApplicationCommandOptionType, AttachmentBuilder, Guild, PermissionFlagsBits, User } from 'discord.js'; -import got from 'got'; -import { dirname, join } from 'path'; -import { fileURLToPath } from 'url'; assert(canvas); -assert(got); assert(SimplifyNumber); export default class LevelCommand extends BushCommand { @@ -85,10 +81,12 @@ export default class LevelCommand extends BushCommand { const white = '#FFFFFF', gray = '#23272A', highlight = user.hexAccentColor ?? '#5865F2'; - // Load roboto font + + // ! Broken on node v18 - install the font instead + /* // Load roboto font canvas.registerFont(join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', 'assets', 'Roboto-Regular.ttf'), { family: 'Roboto' - }); + }); */ // Create image canvas const levelCard = canvas.createCanvas(800, 200), ctx = levelCard.getContext('2d'); @@ -97,9 +95,14 @@ export default class LevelCommand extends BushCommand { ctx.fillRect(0, 0, levelCard.width, levelCard.height); // Draw avatar const AVATAR_SIZE = 128; - const avatarBuffer = await got.get(user.displayAvatarURL({ extension: 'png', size: AVATAR_SIZE })).buffer(); const avatarImage = new canvas.Image(); - avatarImage.src = avatarBuffer; + avatarImage.src = user.displayAvatarURL({ extension: 'png', size: AVATAR_SIZE }); + + await new Promise((resolve, reject) => { + avatarImage.onload = () => resolve(undefined); + avatarImage.onerror = (e) => reject(e); + }); + const imageTopCoord = levelCard.height / 2 - AVATAR_SIZE / 2; ctx.drawImage(avatarImage, imageTopCoord, imageTopCoord, AVATAR_SIZE, AVATAR_SIZE); // Write tag of user @@ -123,13 +126,12 @@ export default class LevelCommand extends BushCommand { progressBar.draw(); // Draw level data text ctx.fillStyle = white; - ctx.fillText( - `Level: ${userLevel} XP: ${SimplifyNumber(currentLevelXpProgress)}/${SimplifyNumber( - xpForNextLevel - )} Rank: ${SimplifyNumber(rank.indexOf(rank.find((x) => x.user === user.id)!) + 1)}`, - AVATAR_SIZE + 70, - AVATAR_SIZE - 20 - ); + + const xpTxt = `${SimplifyNumber(currentLevelXpProgress)}/${SimplifyNumber(xpForNextLevel)}`; + + const rankTxt = SimplifyNumber(rank.indexOf(rank.find((x) => x.user === user.id)!) + 1); + + ctx.fillText(`Level: ${userLevel} XP: ${xpTxt} Rank: ${rankTxt}`, AVATAR_SIZE + 70, AVATAR_SIZE - 20); // Return image in buffer form return levelCard.toBuffer(); } diff --git a/src/commands/moderation/unmute.ts b/src/commands/moderation/unmute.ts index 620f499..f1e74ab 100644 --- a/src/commands/moderation/unmute.ts +++ b/src/commands/moderation/unmute.ts @@ -1,19 +1,16 @@ import { AllowedMentions, clientSendAndPermCheck, - emojis, - format, + formatUnmuteResponse, Moderation, - unmuteResponse, userGuildPermCheck, type ArgType, type CommandMessage, type OptArgType, - type SlashMessage, - type UnmuteResponse + type SlashMessage } from '#lib'; import assert from 'assert/strict'; -import { ApplicationCommandOptionType, PermissionFlagsBits, type GuildMember } from 'discord.js'; +import { ApplicationCommandOptionType, PermissionFlagsBits } from 'discord.js'; import { BushCommand } from '../../../lib/extensions/discord-akairo/BushCommand.js'; export default class UnmuteCommand extends BushCommand { @@ -83,35 +80,8 @@ export default class UnmuteCommand extends BushCommand { }); return await message.util.reply({ - content: UnmuteCommand.formatCode(member.client.utils.prefix(message), member, responseCode), + content: formatUnmuteResponse(member.client.utils.prefix(message), member, responseCode), allowedMentions: AllowedMentions.none() }); } - - public static formatCode(prefix: string, member: GuildMember, code: UnmuteResponse): string { - const error = emojis.error; - const victim = format.input(member.user.tag); - switch (code) { - 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\`.`; - 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\`.`; - 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\`.`; - case unmuteResponse.ACTION_ERROR: - return `${error} Could not unmute ${victim}, there was an error removing their mute role.`; - case unmuteResponse.MODLOG_ERROR: - return `${error} While muting ${victim}, there was an error creating a modlog entry, please report this to my developers.`; - 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 `${emojis.warn} unmuted ${victim} however I could not send them a dm.`; - case unmuteResponse.SUCCESS: - return `${emojis.success} Successfully unmuted ${victim}.`; - default: - return `${emojis.error} An error occurred: ${format.input(code)}}`; - } - } } diff --git a/src/commands/moulberry-bush/capePermissions.ts b/src/commands/moulberry-bush/capePermissions.ts index 3ad9602..793ac59 100644 --- a/src/commands/moulberry-bush/capePermissions.ts +++ b/src/commands/moulberry-bush/capePermissions.ts @@ -11,7 +11,6 @@ import { type SlashMessage } from '#lib'; import { ApplicationCommandOptionType, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; -import got from 'got'; export default class CapePermissionsCommand extends BushCommand { public constructor() { @@ -50,7 +49,7 @@ export default class CapePermissionsCommand extends BushCommand { } try { - capePerms = await got.get('http://moulberry.codes/permscapes.json').json(); + capePerms = await fetch('http://moulberry.codes/permscapes.json').then((p) => (p.ok ? p.json() : null)); } catch (error) { capePerms = null; } diff --git a/src/commands/moulberry-bush/capes.ts b/src/commands/moulberry-bush/capes.ts index 8693dba..6ffc540 100644 --- a/src/commands/moulberry-bush/capes.ts +++ b/src/commands/moulberry-bush/capes.ts @@ -14,11 +14,9 @@ import { } from '#lib'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, PermissionFlagsBits, type APIEmbed, type AutocompleteInteraction } from 'discord.js'; -import Fuse from 'fuse.js'; -import got from 'got'; +import { default as Fuse } from 'fuse.js'; assert(Fuse); -assert(got); export default class CapesCommand extends BushCommand { public constructor() { @@ -47,9 +45,9 @@ export default class CapesCommand extends BushCommand { } public override async exec(message: CommandMessage | SlashMessage, args: { cape: OptArgType<'string'> }) { - const { tree: neuFileTree }: GithubTreeApi = await got - .get('https://api.github.com/repos/NotEnoughUpdates/NotEnoughUpdates/git/trees/master?recursive=1') - .json(); + const { tree: neuFileTree }: GithubTreeApi = await fetch( + 'https://api.github.com/repos/NotEnoughUpdates/NotEnoughUpdates/git/trees/master?recursive=1' + ).then((p) => (p.ok ? p.json() : { tree: [] })); const rawCapes = neuFileTree .map((f) => ({ match: f.path.match(/src\/main\/resources\/assets\/notenoughupdates\/capes\/(?<name>\w+)_preview\.png/), diff --git a/src/commands/moulberry-bush/serverStatus.ts b/src/commands/moulberry-bush/serverStatus.ts index 1237b3f..cde3f04 100644 --- a/src/commands/moulberry-bush/serverStatus.ts +++ b/src/commands/moulberry-bush/serverStatus.ts @@ -1,9 +1,5 @@ import { BushCommand, clientSendAndPermCheck, colors, emojis, type CommandMessage } from '#lib'; -import assert from 'assert/strict'; import { EmbedBuilder, PermissionFlagsBits } from 'discord.js'; -import got from 'got'; - -assert(got); export default class ServerStatusCommand extends BushCommand { public constructor() { @@ -28,8 +24,8 @@ export default class ServerStatusCommand extends BushCommand { await message.util.reply({ embeds: [msgEmbed] }); let main; try { - await got.get('https://moulberry.codes/lowestbin.json').json(); - main = emojis.success; + const res = await fetch('https://moulberry.codes/lowestbin.json').then((p) => (p.ok ? p.json() : null)); + main = res ? emojis.success : emojis.error; } catch (e) { main = emojis.error; } diff --git a/src/commands/utilities/hash.ts b/src/commands/utilities/hash.ts index 6817f04..251d5e6 100644 --- a/src/commands/utilities/hash.ts +++ b/src/commands/utilities/hash.ts @@ -1,44 +1,44 @@ -import { BushCommand, clientSendAndPermCheck, type CommandMessage } from '#lib'; -import assert from 'assert/strict'; -import crypto from 'crypto'; -import { ApplicationCommandOptionType } from 'discord.js'; -import got from 'got'; +// import { BushCommand, clientSendAndPermCheck, type CommandMessage } from '#lib'; +// import assert from 'assert/strict'; +// import crypto from 'crypto'; +// import { ApplicationCommandOptionType } from 'discord.js'; +// import got from 'got'; -assert(crypto); -assert(got); +// assert(crypto); +// assert(got); -export default class HashCommand extends BushCommand { - public constructor() { - super('hash', { - aliases: ['hash'], - category: 'utilities', - description: 'Gets the file hash of the given discord link', - usage: ['hash <fileUrl>'], - examples: ['hash https://cdn.discordapp.com/emojis/782630946435366942.png?v=1'], //nice - args: [ - { - id: 'url', - description: 'The url of the discord link to find the hash of.', - type: 'url', - prompt: 'What url would you like to find the hash of?', - retry: '{error} Enter a valid url.', - slashType: ApplicationCommandOptionType.String - } - ], - clientPermissions: (m) => clientSendAndPermCheck(m), - userPermissions: [] - }); - } +// export default class HashCommand extends BushCommand { +// public constructor() { +// super('hash', { +// aliases: ['hash'], +// category: 'utilities', +// description: 'Gets the file hash of the given discord link', +// usage: ['hash <fileUrl>'], +// examples: ['hash https://cdn.discordapp.com/emojis/782630946435366942.png?v=1'], //nice +// args: [ +// { +// id: 'url', +// description: 'The url of the discord link to find the hash of.', +// type: 'url', +// prompt: 'What url would you like to find the hash of?', +// retry: '{error} Enter a valid url.', +// slashType: ApplicationCommandOptionType.String +// } +// ], +// clientPermissions: (m) => clientSendAndPermCheck(m), +// userPermissions: [] +// }); +// } - public override async exec(message: CommandMessage, { url }: { url: string }) { - try { - const req = await got.get(url); - const rawHash = crypto.createHash('md5'); - rawHash.update(req.rawBody.toString('binary')); - const hash = rawHash.digest('hex'); - await message.util.reply(`\`${hash}\``); - } catch { - await message.util.reply('Unable to calculate hash.'); - } - } -} +// public override async exec(message: CommandMessage, { url }: { url: string }) { +// try { +// const req = await got.get(url); +// const rawHash = crypto.createHash('md5'); +// rawHash.update(req.rawBody.toString('binary')); +// const hash = rawHash.digest('hex'); +// await message.util.reply(`\`${hash}\``); +// } catch { +// await message.util.reply('Unable to calculate hash.'); +// } +// } +// } diff --git a/src/commands/utilities/price.ts b/src/commands/utilities/price.ts index 8a3b5c6..bfe1f10 100644 --- a/src/commands/utilities/price.ts +++ b/src/commands/utilities/price.ts @@ -1,11 +1,9 @@ import { ArgType, BushCommand, clientSendAndPermCheck, colors, emojis, format, oxford, type CommandMessage } from '#lib'; import assert from 'assert/strict'; import { ApplicationCommandOptionType, AutocompleteInteraction, EmbedBuilder, PermissionFlagsBits } from 'discord.js'; -import Fuse from 'fuse.js'; -import got from 'got'; +import { default as Fuse } from 'fuse.js'; assert(Fuse); -assert(got); export default class PriceCommand extends BushCommand { public static cachedItemList: string[] = []; @@ -57,9 +55,8 @@ export default class PriceCommand extends BushCommand { const [bazaar, currentLowestBIN, averageLowestBIN, auctionAverages] = (await Promise.all( PriceCommand.urls.map(({ url, error }) => - got - .get(url) - .json() + fetch(url) + .then((p) => (p.ok ? p.json() : undefined)) .catch(() => (errors.push(error), undefined)) ) )) as [Bazaar?, LowestBIN?, LowestBIN?, AuctionAverages?]; diff --git a/src/context-menu-commands/user/modlog.ts b/src/context-menu-commands/user/modlog.ts index 91b1b62..c78396e 100644 --- a/src/context-menu-commands/user/modlog.ts +++ b/src/context-menu-commands/user/modlog.ts @@ -1,7 +1,7 @@ +import { ModlogCommand } from '#commands'; import { emojis, SlashMessage } from '#lib'; import { CommandUtil, ContextMenuCommand } from 'discord-akairo'; import { ApplicationCommandType, type ContextMenuCommandInteraction } from 'discord.js'; -import ModlogCommand from '../../commands/moderation/modlog.js'; export default class ModlogContextMenuCommand extends ContextMenuCommand { public constructor() { diff --git a/src/context-menu-commands/user/userInfo.ts b/src/context-menu-commands/user/userInfo.ts index 0d19cce..6d7f3b6 100644 --- a/src/context-menu-commands/user/userInfo.ts +++ b/src/context-menu-commands/user/userInfo.ts @@ -1,7 +1,7 @@ +import { UserInfoCommand } from '#commands'; import { format } from '#lib'; import { ContextMenuCommand } from 'discord-akairo'; import { ApplicationCommandType, type ContextMenuCommandInteraction, type Guild } from 'discord.js'; -import UserInfoCommand from '../../commands/info/userInfo.js'; export default class UserInfoContextMenuCommand extends ContextMenuCommand { public constructor() { diff --git a/src/listeners/commands/commandError.ts b/src/listeners/commands/commandError.ts index bfa857c..7e14bc3 100644 --- a/src/listeners/commands/commandError.ts +++ b/src/listeners/commands/commandError.ts @@ -1,8 +1,4 @@ -import { capitalize, colors, format, formatError, SlashMessage, type BushCommandHandlerEvents } from '#lib'; -import { type AkairoMessage, type Command } from 'discord-akairo'; -import { ChannelType, Client, EmbedBuilder, escapeInlineCode, GuildTextBasedChannel, type Message } from 'discord.js'; -import { BushListener } from '../../../lib/extensions/discord-akairo/BushListener.js'; -import { bold } from '../../../lib/utils/Format.js'; +import { BushListener, handleCommandError, type BushCommandHandlerEvents } from '#lib'; export default class CommandErrorListener extends BushListener { public constructor() { @@ -14,239 +10,6 @@ export default class CommandErrorListener extends BushListener { } public exec(...[error, message, command]: BushCommandHandlerEvents['error']) { - return CommandErrorListener.handleError(this.client, error, message, command); - } - - public static async handleError( - client: Client, - ...[error, message, _command]: BushCommandHandlerEvents['error'] | BushCommandHandlerEvents['slashError'] - ) { - try { - const isSlash = message.util?.isSlash; - const errorNum = Math.floor(Math.random() * 6969696969) + 69; // hehe funny number - const channel = - message.channel?.type === ChannelType.DM - ? message.channel.recipient?.tag - : (<GuildTextBasedChannel>message.channel)?.name; - const command = _command ?? message.util?.parsed?.command; - - client.sentry.captureException(error, { - level: 'error', - user: { id: message.author.id, username: message.author.tag }, - extra: { - 'command.name': command?.id, - 'message.id': message.id, - 'message.type': message.util ? (message.util.isSlash ? 'slash' : 'normal') : 'unknown', - 'message.parsed.content': message.util?.parsed?.content, - 'channel.id': - (message.channel?.type === ChannelType.DM ? message.channel.recipient?.id : message.channel?.id) ?? '¯\\_(ツ)_/¯', - 'channel.name': channel, - 'guild.id': message.guild?.id ?? '¯\\_(ツ)_/¯', - 'guild.name': message.guild?.name ?? '¯\\_(ツ)_/¯', - 'environment': client.config.environment - } - }); - - void client.console.error( - `${isSlash ? 'slashC' : 'c'}ommandError`, - `an error occurred with the <<${command}>> ${isSlash ? 'slash ' : ''}command in <<${channel}>> triggered by <<${ - message?.author?.tag - }>>:\n${formatError(error, true)})}`, - false - ); - - const _haste = CommandErrorListener.getErrorHaste(client, error); - const _stack = CommandErrorListener.getErrorStack(client, error); - const [haste, stack] = await Promise.all([_haste, _stack]); - const options = { message, error, isSlash, errorNum, command, channel, haste, stack }; - - const errorEmbed = CommandErrorListener._generateErrorEmbed({ - ...options, - type: 'command-log' - }); - - void client.logger.channelError({ embeds: errorEmbed }); - - if (message) { - if (!client.config.owners.includes(message.author.id)) { - const errorUserEmbed = CommandErrorListener._generateErrorEmbed({ - ...options, - type: 'command-user' - }); - void message.util?.send({ embeds: errorUserEmbed }).catch(() => null); - } else { - const errorDevEmbed = CommandErrorListener._generateErrorEmbed({ - ...options, - type: 'command-dev' - }); - - void message.util?.send({ embeds: errorDevEmbed }).catch(() => null); - } - } - } catch (e) { - throw new IFuckedUpError('An error occurred while handling a command error.', error, e); - } - } - - public static async generateErrorEmbed( - client: Client, - options: - | { - message: Message | AkairoMessage; - error: Error | any; - isSlash?: boolean; - type: 'command-log' | 'command-dev' | 'command-user'; - errorNum: number; - command?: Command; - channel?: string; - } - | { error: Error | any; type: 'uncaughtException' | 'unhandledRejection'; context?: string } - ): Promise<EmbedBuilder[]> { - const _haste = CommandErrorListener.getErrorHaste(client, options.error); - const _stack = CommandErrorListener.getErrorStack(client, options.error); - const [haste, stack] = await Promise.all([_haste, _stack]); - - return CommandErrorListener._generateErrorEmbed({ ...options, haste, stack }); - } - - private static _generateErrorEmbed( - options: - | { - message: Message | SlashMessage; - error: Error | any; - isSlash?: boolean; - type: 'command-log' | 'command-dev' | 'command-user'; - errorNum: number; - command?: Command; - channel?: string; - haste: string[]; - stack: string; - } - | { - error: Error | any; - type: 'uncaughtException' | 'unhandledRejection'; - context?: string; - haste: string[]; - stack: string; - } - ): EmbedBuilder[] { - const embeds = [new EmbedBuilder().setColor(colors.error)]; - if (options.type === 'command-user') { - embeds[0] - .setTitle('An Error Occurred') - .setDescription( - `Oh no! ${ - options.command - ? `While running the ${options.isSlash ? 'slash ' : ''}command ${format.input(options.command.id)}, a` - : 'A' - }n error occurred. Please give the developers code ${format.input(`${options.errorNum}`)}.` - ) - .setTimestamp(); - return embeds; - } - const description: string[] = []; - - if (options.type === 'command-log') { - description.push( - `**User:** ${options.message.author} (${options.message.author.tag})`, - `**Command:** ${options.command ?? 'N/A'}`, - `**Channel:** <#${options.message.channel?.id}> (${options.channel})`, - `**Message:** [link](${options.message.url})` - ); - if (options.message?.util?.parsed?.content) description.push(`**Command Content:** ${options.message.util.parsed.content}`); - } - - description.push(...options.haste); - - embeds.push(new EmbedBuilder().setColor(colors.error).setTimestamp().setDescription(options.stack.substring(0, 4000))); - if (description.length) embeds[0].setDescription(description.join('\n').substring(0, 4000)); - - if (options.type === 'command-dev' || options.type === 'command-log') - embeds[0].setTitle(`${options.isSlash ? 'Slash ' : ''}CommandError #${format.input(`${options.errorNum}`)}`); - else if (options.type === 'uncaughtException') - embeds[0].setTitle(`${options.context ? `[${bold(options.context)}] An Error Occurred` : 'Uncaught Exception'}`); - else if (options.type === 'unhandledRejection') - embeds[0].setTitle(`${options.context ? `[${bold(options.context)}] An Error Occurred` : 'Unhandled Promise Rejection'}`); - return embeds; - } - - public static async getErrorHaste(client: Client, error: Error | any): Promise<string[]> { - const inspectOptions = { - showHidden: false, - depth: 9, - colors: false, - customInspect: true, - showProxy: false, - maxArrayLength: Infinity, - maxStringLength: Infinity, - breakLength: 80, - compact: 3, - sorted: false, - getters: true - }; - - const ret: string[] = []; - const promises: Promise<{ - url?: string | undefined; - error?: 'content too long' | 'substr' | 'unable to post' | undefined; - }>[] = []; - const pair: { - [key: string]: { - url?: string | undefined; - error?: 'content too long' | 'substr' | 'unable to post' | undefined; - }; - } = {}; - - for (const element in error) { - if (['stack', 'name', 'message'].includes(element)) continue; - else if (typeof (error as any)[element] === 'object') { - promises.push(client.utils.inspectCleanRedactHaste((error as any)[element], inspectOptions)); - } - } - - const links = await Promise.all(promises); - - let index = 0; - for (const element in error) { - if (['stack', 'name', 'message'].includes(element)) continue; - else if (typeof (error as any)[element] === 'object') { - pair[element] = links[index]; - index++; - } - } - - for (const element in error) { - if (['stack', 'name', 'message'].includes(element)) continue; - else { - ret.push( - `**Error ${capitalize(element)}:** ${ - typeof error[element] === 'object' - ? `${ - pair[element].url - ? `[haste](${pair[element].url})${pair[element].error ? ` - ${pair[element].error}` : ''}` - : pair[element].error - }` - : `\`${escapeInlineCode(client.utils.inspectAndRedact((error as any)[element], inspectOptions))}\`` - }` - ); - } - } - return ret; - } - - public static async getErrorStack(client: Client, error: Error | any): Promise<string> { - return await client.utils.inspectCleanRedactCodeblock(error, 'js', { colors: false }, 4000); - } -} - -export class IFuckedUpError extends Error { - public declare original: Error | any; - public declare newError: Error | any; - - public constructor(message: string, original?: Error | any, newError?: Error | any) { - super(message); - this.name = 'IFuckedUpError'; - this.original = original; - this.newError = newError; + return handleCommandError(this.client, error, message, command); } } diff --git a/src/listeners/commands/slashCommandError.ts b/src/listeners/commands/slashCommandError.ts index 7c0d52c..aca7c5b 100644 --- a/src/listeners/commands/slashCommandError.ts +++ b/src/listeners/commands/slashCommandError.ts @@ -1,5 +1,4 @@ -import { BushListener, type BushCommandHandlerEvents } from '#lib'; -import CommandErrorListener from './commandError.js'; +import { BushListener, handleCommandError, type BushCommandHandlerEvents } from '#lib'; export default class SlashCommandErrorListener extends BushListener { public constructor() { @@ -11,6 +10,6 @@ export default class SlashCommandErrorListener extends BushListener { } public async exec(...[error, message, command]: BushCommandHandlerEvents['slashError']) { - return await CommandErrorListener.handleError(this.client, error, message, command); + return await handleCommandError(this.client, error, message, command); } } diff --git a/src/listeners/contextCommands/contextCommandError.ts b/src/listeners/contextCommands/contextCommandError.ts index 4b1ea52..6951ce3 100644 --- a/src/listeners/contextCommands/contextCommandError.ts +++ b/src/listeners/contextCommands/contextCommandError.ts @@ -1,7 +1,6 @@ -import { BushListener, colors, format, formatError } from '#lib'; +import { BushListener, colors, format, formatError, getErrorHaste, getErrorStack, IFuckedUpError } from '#lib'; import { type ContextMenuCommand, type ContextMenuCommandHandlerEvents } from 'discord-akairo'; import { ChannelType, Client, ContextMenuCommandInteraction, EmbedBuilder, GuildTextBasedChannel } from 'discord.js'; -import CommandErrorListener, { IFuckedUpError } from '../commands/commandError.js'; export default class ContextCommandErrorListener extends BushListener { public constructor() { @@ -49,8 +48,8 @@ export default class ContextCommandErrorListener extends BushListener { false ); - const _haste = CommandErrorListener.getErrorHaste(client, error); - const _stack = CommandErrorListener.getErrorStack(client, error); + const _haste = getErrorHaste(client, error); + const _stack = getErrorStack(client, error); const [haste, stack] = await Promise.all([_haste, _stack]); const options = { interaction, error, errorNum, command, channel, haste, stack }; diff --git a/src/listeners/member-custom/bushBan.ts b/src/listeners/member-custom/bushBan.ts index 525184c..2cde91d 100644 --- a/src/listeners/member-custom/bushBan.ts +++ b/src/listeners/member-custom/bushBan.ts @@ -24,7 +24,7 @@ export default class BushBanListener extends BushListener { { name: '**Action**', value: `${duration ? 'Temp Ban' : 'Perm Ban'}` }, { name: '**User**', value: `${user} (${user.tag})` }, { name: '**Moderator**', value: `${moderator} (${moderator.tag})` }, - { name: '**Reason**', value: `${reason ? reason : '[No Reason Provided]'}` } + { name: '**Reason**', value: `${reason ? reason.substring(0, 1024) : '[No Reason Provided]'}` } ); if (duration) logEmbed.addFields({ name: '**Duration**', value: humanizeDuration(duration) }); if (dmSuccess === false) logEmbed.addFields({ name: '**Additional Info**', value: 'Could not dm user.' }); diff --git a/src/listeners/message/blacklistedFile.ts b/src/listeners/message/blacklistedFile.ts index 3d66f38..f3e082c 100644 --- a/src/listeners/message/blacklistedFile.ts +++ b/src/listeners/message/blacklistedFile.ts @@ -1,154 +1,154 @@ -import { BushListener, type BushClientEvents } from '#lib'; -import * as crypto from 'crypto'; -import { ChannelType } from 'discord.js'; -import got from 'got'; +// import { BushListener, type BushClientEvents } from '#lib'; +// import * as crypto from 'crypto'; +// import { ChannelType } from 'discord.js'; +// import got from 'got'; -export default class BlacklistedFileListener extends BushListener { - #blacklistedFiles: { hash: string[]; name: string; description: string }[] = [ - { - hash: ['a0f5e30426234bc9d09306ffc9474422'], - name: 'Play twice audio', - description: 'weird audio files' - }, - { - hash: ['43e55abbcea67d9e6d7abfff944a8d0b'], - name: 'Flashy loud jumpscare', - description: 'flashy, loud gifs' - }, - { - hash: [ - '7a0831239e8c8368e96fb4cacd61b5f2', - '3bdb44bf3702f15d118f04fa63b927a9', - 'b6e45619a68c0e20749edb2412590b15', - 'bb8a27047518a8a7e420509af0e9e0ed', - 'f8076cd51e1ddab4ceded26a764af160', - '1757f0442b5e337bba0340f7b116e6f7', - 'f59185531f0dfa9bdd323b86f796c3bd', - '2825d3d82af65de210e638911e49b3a2', - '5256c3c18b367552e55e463a60af7760' - ], - name: 'Discord crash video/gif', - description: 'media that crashes discord' - }, - { - hash: ['1fd6b3f255946236fd55d3e4bef01c5f', '157d374ec41adeef9601fd87e23f4bf5'], - name: 'Repost lobster video', - description: 'images encouraging spam' - }, - { - hash: ['10ad124fc47cd9b7de2ec629bc945bf2'], - name: 'Jarvis message top user troll thingy', - description: 'gifs encouraging spam' - }, - { - hash: ['312cda77d3e1f5fa00f482aed3b36f6f'], - name: 'Discord token stealer', - description: 'discord token stealers' - }, - { - hash: ['f37f772246db9d690dee0f581682dfb7'], - name: 'Weird nsfw dog vid', - description: 'weird nsfw videos' - }, - { - hash: ['5a5bfdf02a0224d3468499d099ec4eee'], - name: 'Virus (or at least flags antiviruses)', - description: 'viruses' - } - ]; +// export default class BlacklistedFileListener extends BushListener { +// #blacklistedFiles: { hash: string[]; name: string; description: string }[] = [ +// { +// hash: ['a0f5e30426234bc9d09306ffc9474422'], +// name: 'Play twice audio', +// description: 'weird audio files' +// }, +// { +// hash: ['43e55abbcea67d9e6d7abfff944a8d0b'], +// name: 'Flashy loud jumpscare', +// description: 'flashy, loud gifs' +// }, +// { +// hash: [ +// '7a0831239e8c8368e96fb4cacd61b5f2', +// '3bdb44bf3702f15d118f04fa63b927a9', +// 'b6e45619a68c0e20749edb2412590b15', +// 'bb8a27047518a8a7e420509af0e9e0ed', +// 'f8076cd51e1ddab4ceded26a764af160', +// '1757f0442b5e337bba0340f7b116e6f7', +// 'f59185531f0dfa9bdd323b86f796c3bd', +// '2825d3d82af65de210e638911e49b3a2', +// '5256c3c18b367552e55e463a60af7760' +// ], +// name: 'Discord crash video/gif', +// description: 'media that crashes discord' +// }, +// { +// hash: ['1fd6b3f255946236fd55d3e4bef01c5f', '157d374ec41adeef9601fd87e23f4bf5'], +// name: 'Repost lobster video', +// description: 'images encouraging spam' +// }, +// { +// hash: ['10ad124fc47cd9b7de2ec629bc945bf2'], +// name: 'Jarvis message top user troll thingy', +// description: 'gifs encouraging spam' +// }, +// { +// hash: ['312cda77d3e1f5fa00f482aed3b36f6f'], +// name: 'Discord token stealer', +// description: 'discord token stealers' +// }, +// { +// hash: ['f37f772246db9d690dee0f581682dfb7'], +// name: 'Weird nsfw dog vid', +// description: 'weird nsfw videos' +// }, +// { +// hash: ['5a5bfdf02a0224d3468499d099ec4eee'], +// name: 'Virus (or at least flags antiviruses)', +// description: 'viruses' +// } +// ]; - public constructor() { - super('blacklistedFile', { - emitter: 'client', - event: 'messageCreate', - category: 'message' - }); - } +// public constructor() { +// super('blacklistedFile', { +// emitter: 'client', +// event: 'messageCreate', +// category: 'message' +// }); +// } - public async exec(...[message]: BushClientEvents['messageCreate']) { - if (!message.guild || !(await message.guild.hasFeature('blacklistedFile'))) return; - // const embedAttachments = message.embeds.filter((e) => ['image', 'video', 'gifv'].includes(e.type)); - const foundEmojis = [...message.content.matchAll(/<(?<animated>a?):\w+:(?<id>\d+)>/g)]; - if (message.attachments.size + /* embedAttachments.length + */ foundEmojis.length < 1) return; - const foundFiles = [] as { - name: string; - hash: string[]; - description: string; - }[]; - for (const attachment of message.attachments) { - try { - const req = await got.get(attachment[1].proxyURL); - const rawHash = crypto.createHash('md5'); - rawHash.update(req.rawBody.toString('binary')); - const hash = rawHash.digest('hex'); - const blacklistData = this.#blacklistedFiles.find((h) => h.hash.some((h) => h === hash)); - if (blacklistData !== undefined) { - foundFiles.push(blacklistData); - } - } catch { - continue; - } - } - /* for (const attachment of embedAttachments) { - try { - const req = await got.get(attachment.url!); - const rawHash = crypto.createHash('md5'); - rawHash.update(req.rawBody.toString('binary')); - const hash = rawHash.digest('hex'); - const blacklistData = this.#blacklistedFiles.find((h) => h.hash.some((h) => h === hash)); - if (blacklistData !== undefined) { - foundFiles.push(blacklistData); - } - } catch { - continue; - } - } */ - for (const attachment of foundEmojis) { - try { - const req = await got.get( - `https://cdn.discordapp.com/emojis/${attachment.groups?.id}.${attachment.groups?.animated === 'a' ? 'gif' : 'png'}` - ); - const rawHash = crypto.createHash('md5'); - rawHash.update(req.rawBody.toString('binary')); - const hash = rawHash.digest('hex'); - const blacklistData = this.#blacklistedFiles.find((h) => h.hash.some((h) => h === hash)); - if (blacklistData !== undefined) { - foundFiles.push(blacklistData); - } - } catch { - continue; - } - } - if (foundFiles.length > 0) { - try { - for (let i = 0; i < foundFiles.length; i++) { - if (foundFiles[i].name === 'Discord crash video' && !this.client.ownerID.includes(message.author.id)) { - await message.member?.roles.add('748912426581229690'); - } - } - await message.delete(); +// public async exec(...[message]: BushClientEvents['messageCreate']) { +// if (!message.guild || !(await message.guild.hasFeature('blacklistedFile'))) return; +// // const embedAttachments = message.embeds.filter((e) => ['image', 'video', 'gifv'].includes(e.type)); +// const foundEmojis = [...message.content.matchAll(/<(?<animated>a?):\w+:(?<id>\d+)>/g)]; +// if (message.attachments.size + /* embedAttachments.length + */ foundEmojis.length < 1) return; +// const foundFiles = [] as { +// name: string; +// hash: string[]; +// description: string; +// }[]; +// for (const attachment of message.attachments) { +// try { +// const req = await got.get(attachment[1].proxyURL); +// const rawHash = crypto.createHash('md5'); +// rawHash.update(req.rawBody.toString('binary')); +// const hash = rawHash.digest('hex'); +// const blacklistData = this.#blacklistedFiles.find((h) => h.hash.some((h) => h === hash)); +// if (blacklistData !== undefined) { +// foundFiles.push(blacklistData); +// } +// } catch { +// continue; +// } +// } +// /* for (const attachment of embedAttachments) { +// try { +// const req = await got.get(attachment.url!); +// const rawHash = crypto.createHash('md5'); +// rawHash.update(req.rawBody.toString('binary')); +// const hash = rawHash.digest('hex'); +// const blacklistData = this.#blacklistedFiles.find((h) => h.hash.some((h) => h === hash)); +// if (blacklistData !== undefined) { +// foundFiles.push(blacklistData); +// } +// } catch { +// continue; +// } +// } */ +// for (const attachment of foundEmojis) { +// try { +// const req = await got.get( +// `https://cdn.discordapp.com/emojis/${attachment.groups?.id}.${attachment.groups?.animated === 'a' ? 'gif' : 'png'}` +// ); +// const rawHash = crypto.createHash('md5'); +// rawHash.update(req.rawBody.toString('binary')); +// const hash = rawHash.digest('hex'); +// const blacklistData = this.#blacklistedFiles.find((h) => h.hash.some((h) => h === hash)); +// if (blacklistData !== undefined) { +// foundFiles.push(blacklistData); +// } +// } catch { +// continue; +// } +// } +// if (foundFiles.length > 0) { +// try { +// for (let i = 0; i < foundFiles.length; i++) { +// if (foundFiles[i].name === 'Discord crash video' && !this.client.ownerID.includes(message.author.id)) { +// await message.member?.roles.add('748912426581229690'); +// } +// } +// await message.delete(); - await message.util!.send( - `<@!${message.author.id}>, please do not send ${foundFiles.map((f) => f.description).join(' or ')}.` - ); - if (message.channel.type === ChannelType.DM) return; - void this.client.console.info( - 'blacklistedFile', - `Deleted <<${foundFiles.map((f) => f.description).join(' and ')}>> sent by <<${message.author.tag}>> in ${ - message.channel.name - }.` - ); - } catch (e) { - void message.util!.send( - `<@!${message.author.id}>, please do not send ${foundFiles.map((f) => f.description).join(' or ')}.` - ); - void this.client.console.warn( - 'blacklistedFile', - `Failed to delete <<${foundFiles.map((f) => f.description).join(' and ')}>> sent by <<${message.author.tag}>> in <<${ - message.channel.type === ChannelType.DM ? `${message.channel.recipient?.tag}'s DMs` : message.channel.name - }>>.` - ); - } - } - } -} +// await message.util!.send( +// `<@!${message.author.id}>, please do not send ${foundFiles.map((f) => f.description).join(' or ')}.` +// ); +// if (message.channel.type === ChannelType.DM) return; +// void this.client.console.info( +// 'blacklistedFile', +// `Deleted <<${foundFiles.map((f) => f.description).join(' and ')}>> sent by <<${message.author.tag}>> in ${ +// message.channel.name +// }.` +// ); +// } catch (e) { +// void message.util!.send( +// `<@!${message.author.id}>, please do not send ${foundFiles.map((f) => f.description).join(' or ')}.` +// ); +// void this.client.console.warn( +// 'blacklistedFile', +// `Failed to delete <<${foundFiles.map((f) => f.description).join(' and ')}>> sent by <<${message.author.tag}>> in <<${ +// message.channel.type === ChannelType.DM ? `${message.channel.recipient?.tag}'s DMs` : message.channel.name +// }>>.` +// ); +// } +// } +// } +// } diff --git a/src/listeners/other/promiseRejection.ts b/src/listeners/other/promiseRejection.ts index ab67ad4..4ff6c0e 100644 --- a/src/listeners/other/promiseRejection.ts +++ b/src/listeners/other/promiseRejection.ts @@ -1,5 +1,4 @@ -import { BushListener, formatError } from '#lib'; -import CommandErrorListener from '../commands/commandError.js'; +import { BushListener, formatError, generateErrorEmbed } from '#lib'; export default class PromiseRejectionListener extends BushListener { public constructor() { @@ -27,7 +26,7 @@ export default class PromiseRejectionListener extends BushListener { ); if (!error.message.includes('reason: getaddrinfo ENOTFOUND canary.discord.com')) void this.client.console.channelError({ - embeds: await CommandErrorListener.generateErrorEmbed(this.client, { type: 'unhandledRejection', error: error }) + embeds: await generateErrorEmbed(this.client, { type: 'unhandledRejection', error: error }) }); } } diff --git a/src/listeners/other/uncaughtException.ts b/src/listeners/other/uncaughtException.ts index e06a3b8..c976a22 100644 --- a/src/listeners/other/uncaughtException.ts +++ b/src/listeners/other/uncaughtException.ts @@ -1,5 +1,4 @@ -import { BushListener, formatError } from '#lib'; -import CommandErrorListener from '../commands/commandError.js'; +import { BushListener, formatError, generateErrorEmbed } from '#lib'; export default class UncaughtExceptionListener extends BushListener { public constructor() { @@ -21,7 +20,7 @@ export default class UncaughtExceptionListener extends BushListener { void this.client.console.error('uncaughtException', `An uncaught exception occurred:\n${formatError(error, true)}`, false); void this.client.console.channelError({ - embeds: await CommandErrorListener.generateErrorEmbed(this.client, { type: 'uncaughtException', error: error }) + embeds: await generateErrorEmbed(this.client, { type: 'uncaughtException', error: error }) }); } } diff --git a/src/listeners/other/warning.ts b/src/listeners/other/warning.ts index b427e4c..5cf9764 100644 --- a/src/listeners/other/warning.ts +++ b/src/listeners/other/warning.ts @@ -1,5 +1,4 @@ -import { BushListener, colors, formatError } from '#lib'; -import CommandErrorListener from '../commands/commandError.js'; +import { BushListener, colors, formatError, generateErrorEmbed } from '#lib'; export default class WarningListener extends BushListener { public constructor() { @@ -18,7 +17,7 @@ export default class WarningListener extends BushListener { void this.client.console.warn('warning', `A warning occurred:\n${formatError(error, true)}`, false); - const embeds = await CommandErrorListener.generateErrorEmbed(this.client, { type: 'unhandledRejection', error: error }); + const embeds = await generateErrorEmbed(this.client, { type: 'unhandledRejection', error: error }); embeds[0].setColor(colors.warn).setTitle('A Warning Occurred'); void this.client.console.channelError({ embeds }); diff --git a/src/tasks/cache/updateCache.ts b/src/tasks/cache/updateCache.ts index 595a872..190e2a4 100644 --- a/src/tasks/cache/updateCache.ts +++ b/src/tasks/cache/updateCache.ts @@ -1,8 +1,4 @@ -import { Global, Guild, Shared, type BushClient } from '#lib'; -import type { Client } from 'discord.js'; -import config from '../../../config/options.js'; -import { BushTask } from '../../../lib/extensions/discord-akairo/BushTask.js'; -import { Time } from '../../../lib/utils/BushConstants.js'; +import { BushTask, Time, updateEveryCache } from '#lib'; export default class UpdateCacheTask extends BushTask { public constructor() { @@ -13,48 +9,7 @@ export default class UpdateCacheTask extends BushTask { } public async exec() { - await Promise.all([ - UpdateCacheTask.#updateGlobalCache(this.client), - UpdateCacheTask.#updateSharedCache(this.client), - UpdateCacheTask.#updateGuildCache(this.client) - ]); + await updateEveryCache(this.client); void this.client.logger.verbose(`UpdateCache`, `Updated cache.`); } - - public static async init(client: BushClient) { - await Promise.all([ - UpdateCacheTask.#updateGlobalCache(client), - UpdateCacheTask.#updateSharedCache(client), - UpdateCacheTask.#updateGuildCache(client) - ]); - } - - static async #updateGlobalCache(client: Client) { - const environment = config.environment; - const row: { [x: string]: any } = ((await Global.findByPk(environment)) ?? (await Global.create({ environment }))).toJSON(); - - for (const option in row) { - if (Object.keys(client.cache.global).includes(option)) { - client.cache.global[option as keyof typeof client.cache.global] = row[option]; - } - } - } - - static async #updateSharedCache(client: Client) { - const row: { [x: string]: any } = ((await Shared.findByPk(0)) ?? (await Shared.create())).toJSON(); - - for (const option in row) { - if (Object.keys(client.cache.shared).includes(option)) { - client.cache.shared[option as keyof typeof client.cache.shared] = row[option]; - if (option === 'superUsers') client.superUserID = row[option]; - } - } - } - - static async #updateGuildCache(client: Client) { - const rows = await Guild.findAll(); - for (const row of rows) { - client.cache.guilds.set(row.id, row.toJSON() as Guild); - } - } } diff --git a/src/tasks/cache/updatePriceItemCache.ts b/src/tasks/cache/updatePriceItemCache.ts index 55115cc..bafbfaf 100644 --- a/src/tasks/cache/updatePriceItemCache.ts +++ b/src/tasks/cache/updatePriceItemCache.ts @@ -1,5 +1,4 @@ import { BushTask, Time } from '#lib'; -import got from 'got'; import PriceCommand, { AuctionAverages, Bazaar, LowestBIN } from '../../commands/utilities/price.js'; export default class UpdatePriceItemCache extends BushTask { @@ -13,9 +12,8 @@ export default class UpdatePriceItemCache extends BushTask { public async exec() { const [bazaar, currentLowestBIN, averageLowestBIN, auctionAverages] = (await Promise.all( PriceCommand.urls.map(({ url }) => - got - .get(url) - .json() + fetch(url) + .then((p) => (p.ok ? p.json() : undefined)) .catch(() => undefined) ) )) as [Bazaar?, LowestBIN?, LowestBIN?, AuctionAverages?]; diff --git a/src/tasks/feature/handleReminders.ts b/src/tasks/feature/handleReminders.ts index 1e44083..a9f5658 100644 --- a/src/tasks/feature/handleReminders.ts +++ b/src/tasks/feature/handleReminders.ts @@ -1,5 +1,5 @@ import { BushTask, dateDelta, format, Reminder, Time } from '#lib'; -const { Op } = (await import('sequelize')).default; +import { Op } from 'sequelize'; export default class HandlerRemindersTask extends BushTask { public constructor() { @@ -29,8 +29,7 @@ export default class HandlerRemindersTask extends BushTask { void this.client.users .send( entry.user, - `The reminder you set ${dateDelta(entry.created)} ago has expired: ${format.bold(entry.content)} -${entry.messageUrl}` + `The reminder you set ${dateDelta(entry.created)} ago has expired: ${format.bold(entry.content)}\n${entry.messageUrl}` ) .catch(() => false); void entry.update({ notified: true }); diff --git a/src/tasks/feature/removeExpiredPunishements.ts b/src/tasks/feature/removeExpiredPunishements.ts index c21454b..30b8eba 100644 --- a/src/tasks/feature/removeExpiredPunishements.ts +++ b/src/tasks/feature/removeExpiredPunishements.ts @@ -1,6 +1,6 @@ import { ActivePunishment, ActivePunishmentType, BushTask, Time } from '#lib'; import assert from 'assert/strict'; -const { Op } = (await import('sequelize')).default; +import { Op } from 'sequelize'; export default class RemoveExpiredPunishmentsTask extends BushTask { public constructor() { diff --git a/src/tasks/feature/updateStats.d.ts b/src/tasks/feature/updateStats.d.ts new file mode 100644 index 0000000..1274267 --- /dev/null +++ b/src/tasks/feature/updateStats.d.ts @@ -0,0 +1,10 @@ +import { BushTask } from '#lib'; +import { Client } from 'discord.js'; +export default class UpdateStatsTask extends BushTask { + constructor(); + exec(): Promise<void>; + static init(client: Client): Promise<{ + commandsUsed: bigint; + slashCommandsUsed: bigint; + }>; +} diff --git a/src/tasks/feature/updateStats.js b/src/tasks/feature/updateStats.js new file mode 100644 index 0000000..18a9a7c --- /dev/null +++ b/src/tasks/feature/updateStats.js @@ -0,0 +1,22 @@ +import { BushTask, Stat, Time } from '#lib'; +import { Client } from 'discord.js'; +export default class UpdateStatsTask extends BushTask { + constructor() { + super('updateStats', { + delay: 10 * 60000, + runOnStart: true + }); + } + async exec() { + const row = (await Stat.findByPk(this.client.config.environment)) ?? + (await Stat.create({ environment: this.client.config.environment })); + row.commandsUsed = this.client.stats.commandsUsed; + row.slashCommandsUsed = this.client.stats.slashCommandsUsed; + await row.save(); + } + static async init(client) { + const temp = (await Stat.findByPk(client.config.environment)) ?? (await Stat.create({ environment: client.config.environment })); + return { commandsUsed: temp.commandsUsed, slashCommandsUsed: temp.slashCommandsUsed }; + } +} +//# sourceMappingURL=updateStats.js.map
\ No newline at end of file diff --git a/src/tasks/feature/updateStats.js.map b/src/tasks/feature/updateStats.js.map new file mode 100644 index 0000000..01cd260 --- /dev/null +++ b/src/tasks/feature/updateStats.js.map @@ -0,0 +1 @@ +{"version":3,"file":"updateStats.js","sourceRoot":"","sources":["updateStats.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEpC,MAAM,CAAC,OAAO,OAAO,eAAgB,SAAQ,QAAQ;IACpD;QACC,KAAK,CAAC,aAAa,EAAE;YACpB,KAAK,EAAE,EAAE,QAAc;YACvB,UAAU,EAAE,IAAI;SAChB,CAAC,CAAC;IACJ,CAAC;IAEM,KAAK,CAAC,IAAI;QAChB,MAAM,GAAG,GACR,CAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YACrD,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;QACtE,GAAG,CAAC,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC;QAClD,GAAG,CAAC,iBAAiB,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC;QAC5D,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;IAClB,CAAC;IAEM,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,MAAc;QACtC,MAAM,IAAI,GACT,CAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;QACrH,OAAO,EAAE,YAAY,EAAE,IAAI,CAAC,YAAY,EAAE,iBAAiB,EAAE,IAAI,CAAC,iBAAiB,EAAE,CAAC;IACvF,CAAC;CACD"}
\ No newline at end of file diff --git a/src/tasks/feature/updateStats.ts b/src/tasks/feature/updateStats.ts index 0d0e661..77b7c30 100644 --- a/src/tasks/feature/updateStats.ts +++ b/src/tasks/feature/updateStats.ts @@ -1,5 +1,4 @@ import { BushTask, Stat, Time } from '#lib'; -import { Client } from 'discord.js'; export default class UpdateStatsTask extends BushTask { public constructor() { @@ -17,10 +16,4 @@ export default class UpdateStatsTask extends BushTask { row.slashCommandsUsed = this.client.stats.slashCommandsUsed; await row.save(); } - - public static async init(client: Client): Promise<{ commandsUsed: bigint; slashCommandsUsed: bigint }> { - const temp = - (await Stat.findByPk(client.config.environment)) ?? (await Stat.create({ environment: client.config.environment })); - return { commandsUsed: temp.commandsUsed, slashCommandsUsed: temp.slashCommandsUsed }; - } } diff --git a/src/tsconfig.json b/src/tsconfig.json index 6d2834a..705d261 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -1,9 +1,7 @@ { "extends": "../tsconfig.base.json", "compilerOptions": { - "outDir": "../../dist/src", - "composite": true + "outDir": "../dist/src" }, - "references": [{ "path": "../lib" }, { "path": "../config" }], - "include": ["src/**/*.ts"] + "references": [{ "path": "../lib" }, { "path": "../config" }, { "path": "../tsconfig.pkg.json" }] } |