From ef76e9c3ad4cbf72f02e8be621d378f7166270ef Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sat, 26 Aug 2023 21:50:14 +0200 Subject: [PATCH 01/24] fix: installed typescript --- package-lock.json | 31 +++++++++++++++++++++++-------- package.json | 6 ++++-- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/package-lock.json b/package-lock.json index a329286..9db1a51 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,8 +25,10 @@ "uuid": "^9.0.0" }, "devDependencies": { + "@types/node": "^20.5.6", "eslint": "^8.47.0", - "prettier-eslint": "^15.0.1" + "prettier-eslint": "^15.0.1", + "typescript": "^5.2.2" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -457,9 +459,9 @@ } }, "node_modules/@types/node": { - "version": "20.3.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.3.tgz", - "integrity": "sha512-wheIYdr4NYML61AjC8MKj/2jrR/kDQri/CIpVoZwldwhnIrD/j9jIU5bJ8yBKuB2VhpFV7Ab6G2XkBjv9r9Zzw==" + "version": "20.5.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.6.tgz", + "integrity": "sha512-Gi5wRGPbbyOTX+4Y2iULQ27oUPrefaB0PxGQJnfyWN3kvEDGM3mIB5M/gQLmitZf7A9FmLeaqxD3L1CXpm3VKQ==" }, "node_modules/@types/prettier": { "version": "2.7.3", @@ -3002,6 +3004,19 @@ "node": ">=10.0.0" } }, + "node_modules/prettier-eslint/node_modules/typescript": { + "version": "4.9.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", + "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, "node_modules/pretty-format": { "version": "23.6.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-23.6.0.tgz", @@ -3602,16 +3617,16 @@ } }, "node_modules/typescript": { - "version": "4.9.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", - "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", + "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { - "node": ">=4.2.0" + "node": ">=14.17" } }, "node_modules/undici": { diff --git a/package.json b/package.json index feb27e3..1df0c4b 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,9 @@ "uuid": "^9.0.0" }, "devDependencies": { + "@types/node": "^20.5.6", "eslint": "^8.47.0", - "prettier-eslint": "^15.0.1" + "prettier-eslint": "^15.0.1", + "typescript": "^5.2.2" } -} +} From 40bf9d926b2dc3ba8944669a848093766d854a6d Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sat, 26 Aug 2023 21:50:25 +0200 Subject: [PATCH 02/24] fix: created initial tsconfig.json --- tsconfig.json | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 tsconfig.json diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..460d0d2 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2020", // Specify ECMAScript target version + "module": "commonjs", // Specify module code generation + "outDir": "./dist", // Output directory for compiled files + "rootDir": "./src", // Root directory of source files + "strict": true, // Enable strict type-checking options + "esModuleInterop": true, // Enables ES module interop + "skipLibCheck": true, // Skip type checking of declaration files + "forceConsistentCasingInFileNames": true // Disallow inconsistently-cased references to the same file + }, + "include": ["src/**/*.ts"], // Source files to be compiled + "exclude": ["node_modules"] // Exclude node_modules from compilation +} From 92b1992b1ac6d4ce3cf15d14b6b78914536f7610 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sat, 26 Aug 2023 21:50:38 +0200 Subject: [PATCH 03/24] feat: rename .js files to .ts --- src/{bot.js => bot.ts} | 0 src/commands/info/{help.js => help.ts} | 0 src/commands/info/{status.js => status.ts} | 0 src/commands/player/{filters.js => filters.ts} | 0 src/commands/player/{leave.js => leave.ts} | 0 src/commands/player/{loop.js => loop.ts} | 0 src/commands/player/{lyrics.js => lyrics.ts} | 0 src/commands/player/{nowplaying.js => nowplaying.ts} | 0 src/commands/player/{pause.js => pause.ts} | 0 src/commands/player/{play.js => play.ts} | 0 src/commands/player/{queue.js => queue.ts} | 0 src/commands/player/{remove.js => remove.ts} | 0 src/commands/player/{seek.js => seek.ts} | 0 src/commands/player/{shuffle.js => shuffle.ts} | 0 src/commands/player/{skip.js => skip.ts} | 0 src/commands/player/{stop.js => stop.ts} | 0 src/commands/player/{volume.js => volume.ts} | 0 src/commands/system/{guilds.js => guilds.ts} | 0 src/commands/system/{reload.js => reload.ts} | 0 src/commands/system/{shards.js => shards.ts} | 0 src/commands/system/{systemstatus.js => systemstatus.ts} | 0 src/events/client/{debug.js => debug.ts} | 0 src/events/client/{disconnect.js => disconnect.ts} | 0 src/events/client/{error.js => error.ts} | 0 src/events/client/{guildCreate.js => guildCreate.ts} | 0 src/events/client/{guildDelete.js => guildDelete.ts} | 0 src/events/client/{ready.js => ready.ts} | 0 src/events/client/{reconnecting.js => reconnecting.ts} | 0 src/events/client/{warn.js => warn.ts} | 0 .../interactions/{interactionCreate.js => interactionCreate.ts} | 0 src/events/player/{generalDebug.js => generalDebug.ts} | 0 src/events/player/{generalError.js => generalError.ts} | 0 src/events/player/{playerDebug.js => playerDebug.ts} | 0 src/events/player/{playerError.js => playerError.ts} | 0 src/events/player/{playerSkip.js => playerSkip.ts} | 0 src/events/player/{playerStart.js => playerStart.ts} | 0 src/events/process/{uncaughtException.js => uncaughtException.ts} | 0 .../process/{unhandledRejection.js => unhandledRejection.ts} | 0 src/{index.js => index.ts} | 0 src/services/{logger.js => logger.ts} | 0 src/utils/{deploySlashCommands.js => deploySlashCommands.ts} | 0 src/utils/factory/{createClient.js => createClient.ts} | 0 src/utils/factory/{createPlayer.js => createPlayer.ts} | 0 src/utils/other/{cookieParser.js => cookieParser.ts} | 0 src/utils/other/{postBotStats.js => postBotStats.ts} | 0 src/utils/other/{startLoadTest.js => startLoadTest.ts} | 0 .../{registerClientCommands.js => registerClientCommands.ts} | 0 .../{registerEventListeners.js => registerEventListeners.ts} | 0 src/utils/system/{getUptimeFormatted.js => getUptimeFormatted.ts} | 0 .../validation/{permissionValidator.js => permissionValidator.ts} | 0 src/utils/validation/{queueValidator.js => queueValidator.ts} | 0 .../{searchQueryValidator.js => searchQueryValidator.ts} | 0 .../{systemCommandValidator.js => systemCommandValidator.ts} | 0 .../{voiceChannelValidator.js => voiceChannelValidator.ts} | 0 54 files changed, 0 insertions(+), 0 deletions(-) rename src/{bot.js => bot.ts} (100%) rename src/commands/info/{help.js => help.ts} (100%) rename src/commands/info/{status.js => status.ts} (100%) rename src/commands/player/{filters.js => filters.ts} (100%) rename src/commands/player/{leave.js => leave.ts} (100%) rename src/commands/player/{loop.js => loop.ts} (100%) rename src/commands/player/{lyrics.js => lyrics.ts} (100%) rename src/commands/player/{nowplaying.js => nowplaying.ts} (100%) rename src/commands/player/{pause.js => pause.ts} (100%) rename src/commands/player/{play.js => play.ts} (100%) rename src/commands/player/{queue.js => queue.ts} (100%) rename src/commands/player/{remove.js => remove.ts} (100%) rename src/commands/player/{seek.js => seek.ts} (100%) rename src/commands/player/{shuffle.js => shuffle.ts} (100%) rename src/commands/player/{skip.js => skip.ts} (100%) rename src/commands/player/{stop.js => stop.ts} (100%) rename src/commands/player/{volume.js => volume.ts} (100%) rename src/commands/system/{guilds.js => guilds.ts} (100%) rename src/commands/system/{reload.js => reload.ts} (100%) rename src/commands/system/{shards.js => shards.ts} (100%) rename src/commands/system/{systemstatus.js => systemstatus.ts} (100%) rename src/events/client/{debug.js => debug.ts} (100%) rename src/events/client/{disconnect.js => disconnect.ts} (100%) rename src/events/client/{error.js => error.ts} (100%) rename src/events/client/{guildCreate.js => guildCreate.ts} (100%) rename src/events/client/{guildDelete.js => guildDelete.ts} (100%) rename src/events/client/{ready.js => ready.ts} (100%) rename src/events/client/{reconnecting.js => reconnecting.ts} (100%) rename src/events/client/{warn.js => warn.ts} (100%) rename src/events/interactions/{interactionCreate.js => interactionCreate.ts} (100%) rename src/events/player/{generalDebug.js => generalDebug.ts} (100%) rename src/events/player/{generalError.js => generalError.ts} (100%) rename src/events/player/{playerDebug.js => playerDebug.ts} (100%) rename src/events/player/{playerError.js => playerError.ts} (100%) rename src/events/player/{playerSkip.js => playerSkip.ts} (100%) rename src/events/player/{playerStart.js => playerStart.ts} (100%) rename src/events/process/{uncaughtException.js => uncaughtException.ts} (100%) rename src/events/process/{unhandledRejection.js => unhandledRejection.ts} (100%) rename src/{index.js => index.ts} (100%) rename src/services/{logger.js => logger.ts} (100%) rename src/utils/{deploySlashCommands.js => deploySlashCommands.ts} (100%) rename src/utils/factory/{createClient.js => createClient.ts} (100%) rename src/utils/factory/{createPlayer.js => createPlayer.ts} (100%) rename src/utils/other/{cookieParser.js => cookieParser.ts} (100%) rename src/utils/other/{postBotStats.js => postBotStats.ts} (100%) rename src/utils/other/{startLoadTest.js => startLoadTest.ts} (100%) rename src/utils/{registerClientCommands.js => registerClientCommands.ts} (100%) rename src/utils/{registerEventListeners.js => registerEventListeners.ts} (100%) rename src/utils/system/{getUptimeFormatted.js => getUptimeFormatted.ts} (100%) rename src/utils/validation/{permissionValidator.js => permissionValidator.ts} (100%) rename src/utils/validation/{queueValidator.js => queueValidator.ts} (100%) rename src/utils/validation/{searchQueryValidator.js => searchQueryValidator.ts} (100%) rename src/utils/validation/{systemCommandValidator.js => systemCommandValidator.ts} (100%) rename src/utils/validation/{voiceChannelValidator.js => voiceChannelValidator.ts} (100%) diff --git a/src/bot.js b/src/bot.ts similarity index 100% rename from src/bot.js rename to src/bot.ts diff --git a/src/commands/info/help.js b/src/commands/info/help.ts similarity index 100% rename from src/commands/info/help.js rename to src/commands/info/help.ts diff --git a/src/commands/info/status.js b/src/commands/info/status.ts similarity index 100% rename from src/commands/info/status.js rename to src/commands/info/status.ts diff --git a/src/commands/player/filters.js b/src/commands/player/filters.ts similarity index 100% rename from src/commands/player/filters.js rename to src/commands/player/filters.ts diff --git a/src/commands/player/leave.js b/src/commands/player/leave.ts similarity index 100% rename from src/commands/player/leave.js rename to src/commands/player/leave.ts diff --git a/src/commands/player/loop.js b/src/commands/player/loop.ts similarity index 100% rename from src/commands/player/loop.js rename to src/commands/player/loop.ts diff --git a/src/commands/player/lyrics.js b/src/commands/player/lyrics.ts similarity index 100% rename from src/commands/player/lyrics.js rename to src/commands/player/lyrics.ts diff --git a/src/commands/player/nowplaying.js b/src/commands/player/nowplaying.ts similarity index 100% rename from src/commands/player/nowplaying.js rename to src/commands/player/nowplaying.ts diff --git a/src/commands/player/pause.js b/src/commands/player/pause.ts similarity index 100% rename from src/commands/player/pause.js rename to src/commands/player/pause.ts diff --git a/src/commands/player/play.js b/src/commands/player/play.ts similarity index 100% rename from src/commands/player/play.js rename to src/commands/player/play.ts diff --git a/src/commands/player/queue.js b/src/commands/player/queue.ts similarity index 100% rename from src/commands/player/queue.js rename to src/commands/player/queue.ts diff --git a/src/commands/player/remove.js b/src/commands/player/remove.ts similarity index 100% rename from src/commands/player/remove.js rename to src/commands/player/remove.ts diff --git a/src/commands/player/seek.js b/src/commands/player/seek.ts similarity index 100% rename from src/commands/player/seek.js rename to src/commands/player/seek.ts diff --git a/src/commands/player/shuffle.js b/src/commands/player/shuffle.ts similarity index 100% rename from src/commands/player/shuffle.js rename to src/commands/player/shuffle.ts diff --git a/src/commands/player/skip.js b/src/commands/player/skip.ts similarity index 100% rename from src/commands/player/skip.js rename to src/commands/player/skip.ts diff --git a/src/commands/player/stop.js b/src/commands/player/stop.ts similarity index 100% rename from src/commands/player/stop.js rename to src/commands/player/stop.ts diff --git a/src/commands/player/volume.js b/src/commands/player/volume.ts similarity index 100% rename from src/commands/player/volume.js rename to src/commands/player/volume.ts diff --git a/src/commands/system/guilds.js b/src/commands/system/guilds.ts similarity index 100% rename from src/commands/system/guilds.js rename to src/commands/system/guilds.ts diff --git a/src/commands/system/reload.js b/src/commands/system/reload.ts similarity index 100% rename from src/commands/system/reload.js rename to src/commands/system/reload.ts diff --git a/src/commands/system/shards.js b/src/commands/system/shards.ts similarity index 100% rename from src/commands/system/shards.js rename to src/commands/system/shards.ts diff --git a/src/commands/system/systemstatus.js b/src/commands/system/systemstatus.ts similarity index 100% rename from src/commands/system/systemstatus.js rename to src/commands/system/systemstatus.ts diff --git a/src/events/client/debug.js b/src/events/client/debug.ts similarity index 100% rename from src/events/client/debug.js rename to src/events/client/debug.ts diff --git a/src/events/client/disconnect.js b/src/events/client/disconnect.ts similarity index 100% rename from src/events/client/disconnect.js rename to src/events/client/disconnect.ts diff --git a/src/events/client/error.js b/src/events/client/error.ts similarity index 100% rename from src/events/client/error.js rename to src/events/client/error.ts diff --git a/src/events/client/guildCreate.js b/src/events/client/guildCreate.ts similarity index 100% rename from src/events/client/guildCreate.js rename to src/events/client/guildCreate.ts diff --git a/src/events/client/guildDelete.js b/src/events/client/guildDelete.ts similarity index 100% rename from src/events/client/guildDelete.js rename to src/events/client/guildDelete.ts diff --git a/src/events/client/ready.js b/src/events/client/ready.ts similarity index 100% rename from src/events/client/ready.js rename to src/events/client/ready.ts diff --git a/src/events/client/reconnecting.js b/src/events/client/reconnecting.ts similarity index 100% rename from src/events/client/reconnecting.js rename to src/events/client/reconnecting.ts diff --git a/src/events/client/warn.js b/src/events/client/warn.ts similarity index 100% rename from src/events/client/warn.js rename to src/events/client/warn.ts diff --git a/src/events/interactions/interactionCreate.js b/src/events/interactions/interactionCreate.ts similarity index 100% rename from src/events/interactions/interactionCreate.js rename to src/events/interactions/interactionCreate.ts diff --git a/src/events/player/generalDebug.js b/src/events/player/generalDebug.ts similarity index 100% rename from src/events/player/generalDebug.js rename to src/events/player/generalDebug.ts diff --git a/src/events/player/generalError.js b/src/events/player/generalError.ts similarity index 100% rename from src/events/player/generalError.js rename to src/events/player/generalError.ts diff --git a/src/events/player/playerDebug.js b/src/events/player/playerDebug.ts similarity index 100% rename from src/events/player/playerDebug.js rename to src/events/player/playerDebug.ts diff --git a/src/events/player/playerError.js b/src/events/player/playerError.ts similarity index 100% rename from src/events/player/playerError.js rename to src/events/player/playerError.ts diff --git a/src/events/player/playerSkip.js b/src/events/player/playerSkip.ts similarity index 100% rename from src/events/player/playerSkip.js rename to src/events/player/playerSkip.ts diff --git a/src/events/player/playerStart.js b/src/events/player/playerStart.ts similarity index 100% rename from src/events/player/playerStart.js rename to src/events/player/playerStart.ts diff --git a/src/events/process/uncaughtException.js b/src/events/process/uncaughtException.ts similarity index 100% rename from src/events/process/uncaughtException.js rename to src/events/process/uncaughtException.ts diff --git a/src/events/process/unhandledRejection.js b/src/events/process/unhandledRejection.ts similarity index 100% rename from src/events/process/unhandledRejection.js rename to src/events/process/unhandledRejection.ts diff --git a/src/index.js b/src/index.ts similarity index 100% rename from src/index.js rename to src/index.ts diff --git a/src/services/logger.js b/src/services/logger.ts similarity index 100% rename from src/services/logger.js rename to src/services/logger.ts diff --git a/src/utils/deploySlashCommands.js b/src/utils/deploySlashCommands.ts similarity index 100% rename from src/utils/deploySlashCommands.js rename to src/utils/deploySlashCommands.ts diff --git a/src/utils/factory/createClient.js b/src/utils/factory/createClient.ts similarity index 100% rename from src/utils/factory/createClient.js rename to src/utils/factory/createClient.ts diff --git a/src/utils/factory/createPlayer.js b/src/utils/factory/createPlayer.ts similarity index 100% rename from src/utils/factory/createPlayer.js rename to src/utils/factory/createPlayer.ts diff --git a/src/utils/other/cookieParser.js b/src/utils/other/cookieParser.ts similarity index 100% rename from src/utils/other/cookieParser.js rename to src/utils/other/cookieParser.ts diff --git a/src/utils/other/postBotStats.js b/src/utils/other/postBotStats.ts similarity index 100% rename from src/utils/other/postBotStats.js rename to src/utils/other/postBotStats.ts diff --git a/src/utils/other/startLoadTest.js b/src/utils/other/startLoadTest.ts similarity index 100% rename from src/utils/other/startLoadTest.js rename to src/utils/other/startLoadTest.ts diff --git a/src/utils/registerClientCommands.js b/src/utils/registerClientCommands.ts similarity index 100% rename from src/utils/registerClientCommands.js rename to src/utils/registerClientCommands.ts diff --git a/src/utils/registerEventListeners.js b/src/utils/registerEventListeners.ts similarity index 100% rename from src/utils/registerEventListeners.js rename to src/utils/registerEventListeners.ts diff --git a/src/utils/system/getUptimeFormatted.js b/src/utils/system/getUptimeFormatted.ts similarity index 100% rename from src/utils/system/getUptimeFormatted.js rename to src/utils/system/getUptimeFormatted.ts diff --git a/src/utils/validation/permissionValidator.js b/src/utils/validation/permissionValidator.ts similarity index 100% rename from src/utils/validation/permissionValidator.js rename to src/utils/validation/permissionValidator.ts diff --git a/src/utils/validation/queueValidator.js b/src/utils/validation/queueValidator.ts similarity index 100% rename from src/utils/validation/queueValidator.js rename to src/utils/validation/queueValidator.ts diff --git a/src/utils/validation/searchQueryValidator.js b/src/utils/validation/searchQueryValidator.ts similarity index 100% rename from src/utils/validation/searchQueryValidator.js rename to src/utils/validation/searchQueryValidator.ts diff --git a/src/utils/validation/systemCommandValidator.js b/src/utils/validation/systemCommandValidator.ts similarity index 100% rename from src/utils/validation/systemCommandValidator.js rename to src/utils/validation/systemCommandValidator.ts diff --git a/src/utils/validation/voiceChannelValidator.js b/src/utils/validation/voiceChannelValidator.ts similarity index 100% rename from src/utils/validation/voiceChannelValidator.js rename to src/utils/validation/voiceChannelValidator.ts From c3891f9c2dfb6469e1f72d6f95093d9269166d05 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sat, 26 Aug 2023 22:19:04 +0200 Subject: [PATCH 04/24] feat: update paths to typescript /dist --- .gitignore | 1 + package.json | 10 +++++----- src/index.ts | 2 +- src/utils/deploySlashCommands.ts | 4 ++-- src/utils/registerClientCommands.ts | 4 ++-- src/utils/registerEventListeners.ts | 4 ++-- 6 files changed, 13 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index cec1399..3061e0c 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ /logs/app-*.log /cookies.json /cookies.txt +/dist diff --git a/package.json b/package.json index 1df0c4b..0de33b5 100644 --- a/package.json +++ b/package.json @@ -19,11 +19,11 @@ "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", - "start": "node ./src/index.js", - "start-pretty": "node ./src/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId", - "start-pretty-no-ignore": "node ./src/index.js | pino-pretty", - "deploy": "node ./src/utils/deploySlashCommands.js", - "deploy-pretty": "node ./src/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId", + "start": "node ./dist/index.js", + "start-pretty": "node ./dist/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId", + "start-pretty-no-ignore": "node ./dist/index.js | pino-pretty", + "deploy": "node ./dist/utils/deploySlashCommands.js", + "deploy-pretty": "node ./dist/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId", "eslint": "eslint ./" }, "dependencies": { diff --git a/src/index.ts b/src/index.ts index 5d7575c..7acbd6c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,7 +3,7 @@ const shardingOptions = require('config').get('shardingOptions'); const { ShardingManager, ShardEvents } = require('discord.js'); const { v4: uuidv4 } = require('uuid'); -const manager = new ShardingManager('./src/bot.js', { +const manager = new ShardingManager('./dist/bot.js', { token: process.env.DISCORD_BOT_TOKEN, ...shardingOptions }); diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index 0f34a89..bd4bd32 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -17,10 +17,10 @@ const logger = require('../services/logger').child({ const slashCommands = []; const systemCommands = []; -const commandFolders = fs.readdirSync(path.resolve('./src/commands')); +const commandFolders = fs.readdirSync(path.resolve('./dist/commands')); for (const folder of commandFolders) { const commandFiles = fs - .readdirSync(path.resolve(`./src/commands/${folder}`)) + .readdirSync(path.resolve(`./dist/commands/${folder}`)) .filter((file) => file.endsWith('.js')); for (const file of commandFiles) { diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index d5c3c77..ab0b2ca 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -14,11 +14,11 @@ exports.registerClientCommands = ({ client, executionId }) => { logger.debug('Registering client commands...'); client.commands = new Collection(); - const commandFolders = fs.readdirSync(path.resolve('./src/commands')); + const commandFolders = fs.readdirSync(path.resolve('./dist/commands')); for (const folder of commandFolders) { logger.trace(`Registering client commands for folder '${folder}'...`); const commandFiles = fs - .readdirSync(path.resolve(`./src/commands/${folder}`)) + .readdirSync(path.resolve(`./dist/commands/${folder}`)) .filter((file) => file.endsWith('.js')); for (const file of commandFiles) { diff --git a/src/utils/registerEventListeners.ts b/src/utils/registerEventListeners.ts index 004b86c..ba1f94f 100644 --- a/src/utils/registerEventListeners.ts +++ b/src/utils/registerEventListeners.ts @@ -15,12 +15,12 @@ exports.registerEventListeners = ({ client, player, executionId }) => { logger.debug('Registering event listeners...'); - const eventFolders = fs.readdirSync(path.resolve('./src/events')); + const eventFolders = fs.readdirSync(path.resolve('./dist/events')); for (const folder of eventFolders) { logger.trace(`Registering event listener for folder '${folder}'...`); const eventFiles = fs - .readdirSync(path.resolve(`./src/events/${folder}`)) + .readdirSync(path.resolve(`./dist/events/${folder}`)) .filter((file) => file.endsWith('.js')); for (const file of eventFiles) { From 9125e4a5dada8f9073cdcbd64944aad37a8e41a3 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sat, 26 Aug 2023 22:26:40 +0200 Subject: [PATCH 05/24] fix: update module import statements from require to import --- src/commands/info/help.ts | 2 +- src/commands/info/status.ts | 4 ++-- src/commands/player/filters.ts | 2 +- src/commands/player/leave.ts | 2 +- src/commands/player/loop.ts | 2 +- src/commands/player/lyrics.ts | 2 +- src/commands/player/nowplaying.ts | 2 +- src/commands/player/pause.ts | 2 +- src/commands/player/play.ts | 3 +-- src/commands/player/queue.ts | 2 +- src/commands/player/remove.ts | 2 +- src/commands/player/seek.ts | 2 +- src/commands/player/shuffle.ts | 2 +- src/commands/player/skip.ts | 2 +- src/commands/player/stop.ts | 2 +- src/commands/player/volume.ts | 2 +- src/commands/system/guilds.ts | 2 +- src/commands/system/reload.ts | 2 +- src/commands/system/shards.ts | 2 +- src/commands/system/systemstatus.ts | 4 ++-- src/events/client/disconnect.ts | 2 +- src/events/client/ready.ts | 2 +- src/events/client/reconnecting.ts | 2 +- src/events/interactions/interactionCreate.ts | 2 +- src/events/player/generalError.ts | 2 +- src/events/player/playerError.ts | 2 +- src/events/player/playerSkip.ts | 2 +- src/index.ts | 4 +++- src/services/logger.ts | 4 ++-- src/utils/deploySlashCommands.ts | 6 +++--- src/utils/factory/createClient.ts | 2 +- src/utils/other/cookieParser.ts | 4 ++-- src/utils/other/postBotStats.ts | 2 +- src/utils/other/startLoadTest.ts | 2 +- src/utils/registerClientCommands.ts | 4 ++-- src/utils/registerEventListeners.ts | 6 +++--- src/utils/validation/permissionValidator.ts | 2 +- src/utils/validation/queueValidator.ts | 2 +- src/utils/validation/systemCommandValidator.ts | 2 +- src/utils/validation/voiceChannelValidator.ts | 2 +- 40 files changed, 51 insertions(+), 50 deletions(-) diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 7f8d158..ec325b6 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); diff --git a/src/commands/info/status.ts b/src/commands/info/status.ts index fc63e13..b71f2ac 100644 --- a/src/commands/info/status.ts +++ b/src/commands/info/status.ts @@ -1,8 +1,8 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { getUptimeFormatted } = require('../../utils/system/getUptimeFormatted'); const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const osu = require('node-os-utils'); +import osu from 'node-os-utils'; const { version } = require('../../../package.json'); module.exports = { diff --git a/src/commands/player/filters.ts b/src/commands/player/filters.ts index 90eab1a..d10f280 100644 --- a/src/commands/player/filters.ts +++ b/src/commands/player/filters.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const ffmpegFilterOptions = config.get('ffmpegFilterOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); diff --git a/src/commands/player/leave.ts b/src/commands/player/leave.ts index 7452f85..d88f31e 100644 --- a/src/commands/player/leave.ts +++ b/src/commands/player/leave.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); diff --git a/src/commands/player/loop.ts b/src/commands/player/loop.ts index 2c13958..022ca62 100644 --- a/src/commands/player/loop.ts +++ b/src/commands/player/loop.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); diff --git a/src/commands/player/lyrics.ts b/src/commands/player/lyrics.ts index 7f54c76..6b9817a 100644 --- a/src/commands/player/lyrics.ts +++ b/src/commands/player/lyrics.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); diff --git a/src/commands/player/nowplaying.ts b/src/commands/player/nowplaying.ts index 3222fbd..342b8a9 100644 --- a/src/commands/player/nowplaying.ts +++ b/src/commands/player/nowplaying.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const playerOptions = config.get('playerOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); diff --git a/src/commands/player/pause.ts b/src/commands/player/pause.ts index 8c286ef..f1f8de9 100644 --- a/src/commands/player/pause.ts +++ b/src/commands/player/pause.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); diff --git a/src/commands/player/play.ts b/src/commands/player/play.ts index fa6dd5d..0962adb 100644 --- a/src/commands/player/play.ts +++ b/src/commands/player/play.ts @@ -1,5 +1,4 @@ -//const logger = require('../../services/logger'); -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const playerOptions = config.get('playerOptions'); diff --git a/src/commands/player/queue.ts b/src/commands/player/queue.ts index a37171b..512a32b 100644 --- a/src/commands/player/queue.ts +++ b/src/commands/player/queue.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const playerOptions = config.get('playerOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); diff --git a/src/commands/player/remove.ts b/src/commands/player/remove.ts index d4c73e6..5744879 100644 --- a/src/commands/player/remove.ts +++ b/src/commands/player/remove.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { queueDoesNotExist } = require('../../utils/validation/queueValidator'); diff --git a/src/commands/player/seek.ts b/src/commands/player/seek.ts index 598d0d3..fa63310 100644 --- a/src/commands/player/seek.ts +++ b/src/commands/player/seek.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); diff --git a/src/commands/player/shuffle.ts b/src/commands/player/shuffle.ts index 2ae9eee..f64660c 100644 --- a/src/commands/player/shuffle.ts +++ b/src/commands/player/shuffle.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { queueDoesNotExist, queueIsEmpty } = require('../../utils/validation/queueValidator'); diff --git a/src/commands/player/skip.ts b/src/commands/player/skip.ts index eda7d57..cdfd7e0 100644 --- a/src/commands/player/skip.ts +++ b/src/commands/player/skip.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); diff --git a/src/commands/player/stop.ts b/src/commands/player/stop.ts index 5f03fdc..bf3c7c2 100644 --- a/src/commands/player/stop.ts +++ b/src/commands/player/stop.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); diff --git a/src/commands/player/volume.ts b/src/commands/player/volume.ts index f44fe87..b5052c5 100644 --- a/src/commands/player/volume.ts +++ b/src/commands/player/volume.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); const { queueDoesNotExist } = require('../../utils/validation/queueValidator'); diff --git a/src/commands/system/guilds.ts b/src/commands/system/guilds.ts index bb6b727..8c3620c 100644 --- a/src/commands/system/guilds.ts +++ b/src/commands/system/guilds.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notValidGuildId } = require('../../utils/validation/systemCommandValidator'); const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); diff --git a/src/commands/system/reload.ts b/src/commands/system/reload.ts index 4e960ed..d1cf18a 100644 --- a/src/commands/system/reload.ts +++ b/src/commands/system/reload.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notValidGuildId } = require('../../utils/validation/systemCommandValidator'); const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); diff --git a/src/commands/system/shards.ts b/src/commands/system/shards.ts index d01d4b8..040a72a 100644 --- a/src/commands/system/shards.ts +++ b/src/commands/system/shards.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notValidGuildId } = require('../../utils/validation/systemCommandValidator'); const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); diff --git a/src/commands/system/systemstatus.ts b/src/commands/system/systemstatus.ts index 806b265..6be0d75 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/commands/system/systemstatus.ts @@ -1,9 +1,9 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { notValidGuildId } = require('../../utils/validation/systemCommandValidator'); const { getUptimeFormatted } = require('../../utils/system/getUptimeFormatted'); const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const osu = require('node-os-utils'); +import osu from 'node-os-utils'; const { version, dependencies } = require('../../../package.json'); module.exports = { diff --git a/src/events/client/disconnect.ts b/src/events/client/disconnect.ts index 63e77bd..6985f09 100644 --- a/src/events/client/disconnect.ts +++ b/src/events/client/disconnect.ts @@ -1,5 +1,5 @@ const { v4: uuidv4 } = require('uuid'); -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const systemOptions = config.get('systemOptions'); const { EmbedBuilder } = require('discord.js'); diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 286ab06..32ef784 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const systemOptions = config.get('systemOptions'); const presenceStatusOptions = config.get('presenceStatusOptions'); diff --git a/src/events/client/reconnecting.ts b/src/events/client/reconnecting.ts index 5f849fb..b86e347 100644 --- a/src/events/client/reconnecting.ts +++ b/src/events/client/reconnecting.ts @@ -1,5 +1,5 @@ const { v4: uuidv4 } = require('uuid'); -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const systemOptions = config.get('systemOptions'); const { EmbedBuilder } = require('discord.js'); diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index 4a6c294..17d1f84 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const { cannotSendMessageInChannel } = require('../../utils/validation/permissionValidator'); diff --git a/src/events/player/generalError.ts b/src/events/player/generalError.ts index a011d97..be28714 100644 --- a/src/events/player/generalError.ts +++ b/src/events/player/generalError.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const systemOptions = config.get('systemOptions'); diff --git a/src/events/player/playerError.ts b/src/events/player/playerError.ts index c64fb2b..b407280 100644 --- a/src/events/player/playerError.ts +++ b/src/events/player/playerError.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const systemOptions = config.get('systemOptions'); diff --git a/src/events/player/playerSkip.ts b/src/events/player/playerSkip.ts index 4a9f4d7..81d06c6 100644 --- a/src/events/player/playerSkip.ts +++ b/src/events/player/playerSkip.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const systemOptions = config.get('systemOptions'); diff --git a/src/index.ts b/src/index.ts index 7acbd6c..d17b177 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,7 @@ require('dotenv').config(); -const shardingOptions = require('config').get('shardingOptions'); +import config from 'config'; +const shardingOptions = config.get('shardingOptions'); + const { ShardingManager, ShardEvents } = require('discord.js'); const { v4: uuidv4 } = require('uuid'); diff --git a/src/services/logger.ts b/src/services/logger.ts index c6a0202..de66f84 100644 --- a/src/services/logger.ts +++ b/src/services/logger.ts @@ -1,5 +1,5 @@ -const pino = require('pino'); -const config = require('config'); +import pino from 'pino'; +import config from 'config'; // Retrieve logger options from config const loggerOptions = config.get('loggerOptions'); diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index bd4bd32..4315d99 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -1,8 +1,8 @@ require('dotenv').config(); -const fs = require('node:fs'); -const path = require('node:path'); +import fs from 'node:fs'; +import path from 'node:path'; const { REST, Routes } = require('discord.js'); -const config = require('config'); +import config from 'config'; const { v4: uuidv4 } = require('uuid'); const systemOptions = config.get('systemOptions'); diff --git a/src/utils/factory/createClient.ts b/src/utils/factory/createClient.ts index ddcdf70..198c758 100644 --- a/src/utils/factory/createClient.ts +++ b/src/utils/factory/createClient.ts @@ -1,4 +1,4 @@ -const Discord = require('discord.js'); +import Discord from 'discord.js'; exports.createClient = async ({ executionId }) => { const logger = require('../../services/logger').child({ diff --git a/src/utils/other/cookieParser.ts b/src/utils/other/cookieParser.ts index 9be015c..db0e0ae 100644 --- a/src/utils/other/cookieParser.ts +++ b/src/utils/other/cookieParser.ts @@ -1,5 +1,5 @@ -const path = require('node:path'); -const fs = require('node:fs'); +import path from 'node:path'; +import fs from 'node:fs'; const cookies = require(path.resolve('./cookies.json')); try { diff --git a/src/utils/other/postBotStats.ts b/src/utils/other/postBotStats.ts index d7737e7..8cb9aea 100644 --- a/src/utils/other/postBotStats.ts +++ b/src/utils/other/postBotStats.ts @@ -1,4 +1,4 @@ -const https = require('node:https'); +import https from 'node:https'; exports.postBotStats = async ({ client, executionId }) => { const logger = require('../../services/logger').child({ diff --git a/src/utils/other/startLoadTest.ts b/src/utils/other/startLoadTest.ts index 80a6352..985aa5a 100644 --- a/src/utils/other/startLoadTest.ts +++ b/src/utils/other/startLoadTest.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const loadTestOptions = config.get('loadTestOptions'); exports.startLoadTest = async ({ client, executionId }) => { diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index ab0b2ca..ea45d37 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -1,5 +1,5 @@ -const fs = require('node:fs'); -const path = require('node:path'); +import fs from 'node:fs'; +import path from 'node:path'; const { Collection } = require('discord.js'); exports.registerClientCommands = ({ client, executionId }) => { diff --git a/src/utils/registerEventListeners.ts b/src/utils/registerEventListeners.ts index ba1f94f..3507ca1 100644 --- a/src/utils/registerEventListeners.ts +++ b/src/utils/registerEventListeners.ts @@ -1,6 +1,6 @@ -const fs = require('node:fs'); -const path = require('node:path'); -const config = require('config'); +import fs from 'node:fs'; +import path from 'node:path'; +import config from 'config'; const loggerOptions = config.get('loggerOptions'); diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index b7cb761..9b9044c 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { EmbedBuilder } = require('discord.js'); diff --git a/src/utils/validation/queueValidator.ts b/src/utils/validation/queueValidator.ts index 2792438..6579fda 100644 --- a/src/utils/validation/queueValidator.ts +++ b/src/utils/validation/queueValidator.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { EmbedBuilder } = require('discord.js'); diff --git a/src/utils/validation/systemCommandValidator.ts b/src/utils/validation/systemCommandValidator.ts index 28f18be..0ff7c78 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/utils/validation/systemCommandValidator.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const systemOptions = config.get('systemOptions'); const { EmbedBuilder } = require('discord.js'); diff --git a/src/utils/validation/voiceChannelValidator.ts b/src/utils/validation/voiceChannelValidator.ts index d17445a..da90230 100644 --- a/src/utils/validation/voiceChannelValidator.ts +++ b/src/utils/validation/voiceChannelValidator.ts @@ -1,4 +1,4 @@ -const config = require('config'); +import config from 'config'; const embedOptions = config.get('embedOptions'); const { EmbedBuilder } = require('discord.js'); From 1a7f800ba2d354b717bc1dc9e58a66dc18bc18ae Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sat, 26 Aug 2023 23:01:12 +0200 Subject: [PATCH 06/24] fix: update eslint to respect typescript and run eslint fix --- .eslintrc.json | 22 +- package-lock.json | 323 +++++++++++++++++++++---- package.json | 5 + src/commands/info/help.ts | 6 +- src/commands/info/status.ts | 6 +- src/commands/player/filters.ts | 4 +- src/commands/player/play.ts | 2 +- src/commands/player/queue.ts | 4 +- src/commands/player/seek.ts | 2 +- src/commands/system/guilds.ts | 2 +- src/commands/system/reload.ts | 4 +- src/commands/system/shards.ts | 4 +- src/commands/system/systemstatus.ts | 6 +- src/utils/other/postBotStats.ts | 10 +- src/utils/system/getUptimeFormatted.ts | 2 +- 15 files changed, 325 insertions(+), 77 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 853c74b..58dcb68 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,12 +1,17 @@ { + "ignorePatterns": ["config/**/*.js"], "env": { "node": true, "es2021": true }, - "extends": "eslint:recommended", + "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"], + "parser": "@typescript-eslint/parser", "parserOptions": { - "ecmaVersion": "latest" + "ecmaVersion": "latest", + "sourceType": "module", + "project": "./tsconfig.json" }, + "plugins": ["@typescript-eslint"], "rules": { "indent": ["error", 4, { "SwitchCase": 1 }], "max-len": [ @@ -21,14 +26,9 @@ } ], "linebreak-style": ["error", "windows"], - "quotes": ["error", "single"], + "quotes": ["error", "single", { "avoidEscape": true }], "semi": ["error", "always"], - "camelcase": [ - "error", - { - "properties": "always" - } - ], + "camelcase": "error", "array-bracket-spacing": ["error", "never"], "object-curly-spacing": ["error", "always"], "jsx-quotes": ["error", "prefer-single"], @@ -47,6 +47,8 @@ } ], "curly": ["error", "all"], - "no-console": ["error"] + "no-console": ["error"], + "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], + "@typescript-eslint/explicit-module-boundary-types": "off" } } diff --git a/package-lock.json b/package-lock.json index 9db1a51..f2d867b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,7 +25,12 @@ "uuid": "^9.0.0" }, "devDependencies": { + "@types/config": "^3.3.0", "@types/node": "^20.5.6", + "@types/node-os-utils": "^1.3.1", + "@types/pino": "^7.0.5", + "@types/uuid": "^9.0.2", + "@typescript-eslint/eslint-plugin": "^6.4.1", "eslint": "^8.47.0", "prettier-eslint": "^15.0.1", "typescript": "^5.2.2" @@ -423,6 +428,12 @@ "@types/responselike": "^1.0.0" } }, + "node_modules/@types/config": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/@types/config/-/config-3.3.0.tgz", + "integrity": "sha512-9kZSbl3/X3TVNowLCu5HFQdQmD+4287Om55avknEYkuo6R2dDrsp/EXEHUFvfYeG7m1eJ0WYGj+cbcUIhARJAQ==", + "dev": true + }, "node_modules/@types/eslint": { "version": "8.44.0", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.44.0.tgz", @@ -463,6 +474,22 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.6.tgz", "integrity": "sha512-Gi5wRGPbbyOTX+4Y2iULQ27oUPrefaB0PxGQJnfyWN3kvEDGM3mIB5M/gQLmitZf7A9FmLeaqxD3L1CXpm3VKQ==" }, + "node_modules/@types/node-os-utils": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@types/node-os-utils/-/node-os-utils-1.3.1.tgz", + "integrity": "sha512-gokG1AaQo78X3f1KXOPAfwbhERX95XL0nhosOhwFck0hZ3BG52Mfch3oj3gAhXuUsou3lwi+ewZWjDo0wshKwQ==", + "dev": true + }, + "node_modules/@types/pino": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@types/pino/-/pino-7.0.5.tgz", + "integrity": "sha512-wKoab31pknvILkxAF8ss+v9iNyhw5Iu/0jLtRkUD74cNfOOLJNnqfFKAv0r7wVaTQxRZtWrMpGfShwwBjOcgcg==", + "deprecated": "This is a stub types definition. pino provides its own type definitions, so you do not need this installed.", + "dev": true, + "dependencies": { + "pino": "*" + } + }, "node_modules/@types/prettier": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.3.tgz", @@ -477,6 +504,18 @@ "@types/node": "*" } }, + "node_modules/@types/semver": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.0.tgz", + "integrity": "sha512-G8hZ6XJiHnuhQKR7ZmysCeJWE08o8T0AXtk5darsCaTVsYZhhgUrq53jizaR2FvsoeCwJhlmwTjkXBY5Pn/ZHw==", + "dev": true + }, + "node_modules/@types/uuid": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.2.tgz", + "integrity": "sha512-kNnC1GFBLuhImSnV7w4njQkUiJi0ZXUycu1rUaouPqiKlXkh77JKgdRnTAp1x5eBwcIwbtI+3otwzuIDEuDoxQ==", + "dev": true + }, "node_modules/@types/ws": { "version": "8.5.5", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz", @@ -485,26 +524,63 @@ "@types/node": "*" } }, - "node_modules/@typescript-eslint/parser": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", - "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.4.1.tgz", + "integrity": "sha512-3F5PtBzUW0dYlq77Lcqo13fv+58KDwUib3BddilE8ajPJT+faGgxmI9Sw+I8ZS22BYwoir9ZhNXcLi+S+I2bkw==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "5.62.0", - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/typescript-estree": "5.62.0", - "debug": "^4.3.4" + "@eslint-community/regexpp": "^4.5.1", + "@typescript-eslint/scope-manager": "6.4.1", + "@typescript-eslint/type-utils": "6.4.1", + "@typescript-eslint/utils": "6.4.1", + "@typescript-eslint/visitor-keys": "6.4.1", + "debug": "^4.3.4", + "graphemer": "^1.4.0", + "ignore": "^5.2.4", + "natural-compare": "^1.4.0", + "semver": "^7.5.4", + "ts-api-utils": "^1.0.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + "@typescript-eslint/parser": "^6.0.0 || ^6.0.0-alpha", + "eslint": "^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.4.1.tgz", + "integrity": "sha512-610G6KHymg9V7EqOaNBMtD1GgpAmGROsmfHJPXNLCU9bfIuLrkdOygltK784F6Crboyd5tBFayPB7Sf0McrQwg==", + "dev": true, + "peer": true, + "dependencies": { + "@typescript-eslint/scope-manager": "6.4.1", + "@typescript-eslint/types": "6.4.1", + "@typescript-eslint/typescript-estree": "6.4.1", + "@typescript-eslint/visitor-keys": "6.4.1", + "debug": "^4.3.4" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { "typescript": { @@ -513,29 +589,56 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", - "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.4.1.tgz", + "integrity": "sha512-p/OavqOQfm4/Hdrr7kvacOSFjwQ2rrDVJRPxt/o0TOWdFnjJptnjnZ+sYDR7fi4OimvIuKp+2LCkc+rt9fIW+A==", "dev": true, "dependencies": { - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/visitor-keys": "5.62.0" + "@typescript-eslint/types": "6.4.1", + "@typescript-eslint/visitor-keys": "6.4.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@typescript-eslint/type-utils": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.4.1.tgz", + "integrity": "sha512-7ON8M8NXh73SGZ5XvIqWHjgX2f+vvaOarNliGhjrJnv1vdjG0LVIz+ToYfPirOoBi56jxAKLfsLm40+RvxVVXA==", + "dev": true, + "dependencies": { + "@typescript-eslint/typescript-estree": "6.4.1", + "@typescript-eslint/utils": "6.4.1", + "debug": "^4.3.4", + "ts-api-utils": "^1.0.1" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, "node_modules/@typescript-eslint/types": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", - "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.4.1.tgz", + "integrity": "sha512-zAAopbNuYu++ijY1GV2ylCsQsi3B8QvfPHVqhGdDcbx/NK5lkqMnCGU53amAjccSpk+LfeONxwzUhDzArSfZJg==", "dev": true, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", @@ -543,21 +646,21 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", - "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.4.1.tgz", + "integrity": "sha512-xF6Y7SatVE/OyV93h1xGgfOkHr2iXuo8ip0gbfzaKeGGuKiAnzS+HtVhSPx8Www243bwlW8IF7X0/B62SzFftg==", "dev": true, "dependencies": { - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/visitor-keys": "5.62.0", + "@typescript-eslint/types": "6.4.1", + "@typescript-eslint/visitor-keys": "6.4.1", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", - "semver": "^7.3.7", - "tsutils": "^3.21.0" + "semver": "^7.5.4", + "ts-api-utils": "^1.0.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", @@ -569,17 +672,42 @@ } } }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", - "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", + "node_modules/@typescript-eslint/utils": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.4.1.tgz", + "integrity": "sha512-F/6r2RieNeorU0zhqZNv89s9bDZSovv3bZQpUNOmmQK1L80/cV4KEu95YUJWi75u5PhboFoKUJBnZ4FQcoqhDw==", "dev": true, "dependencies": { - "@typescript-eslint/types": "5.62.0", - "eslint-visitor-keys": "^3.3.0" + "@eslint-community/eslint-utils": "^4.4.0", + "@types/json-schema": "^7.0.12", + "@types/semver": "^7.5.0", + "@typescript-eslint/scope-manager": "6.4.1", + "@typescript-eslint/types": "6.4.1", + "@typescript-eslint/typescript-estree": "6.4.1", + "semver": "^7.5.4" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^16.0.0 || >=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^7.0.0 || ^8.0.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.4.1.tgz", + "integrity": "sha512-y/TyRJsbZPkJIZQXrHfdnxVnxyKegnpEvnRGNam7s3TRR2ykGefEWOhaef00/UUN3IZxizS7BTO3svd3lCOJRQ==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "6.4.1", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^16.0.0 || >=18.0.0" }, "funding": { "type": "opencollective", @@ -1478,9 +1606,9 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" }, "node_modules/fast-glob": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.0.tgz", - "integrity": "sha512-ChDuvbOypPuNjO8yIDf36x7BlZX1smcUMTTcyoIjycexOxd6DFsKsg21qVBzEmr3G7fUKIRy2/psii+CIUt7FA==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", + "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", "dev": true, "dependencies": { "@nodelib/fs.stat": "^2.0.2", @@ -3004,6 +3132,107 @@ "node": ">=10.0.0" } }, + "node_modules/prettier-eslint/node_modules/@typescript-eslint/parser": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", + "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", + "dev": true, + "dependencies": { + "@typescript-eslint/scope-manager": "5.62.0", + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/typescript-estree": "5.62.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/prettier-eslint/node_modules/@typescript-eslint/scope-manager": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", + "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/prettier-eslint/node_modules/@typescript-eslint/types": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", + "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/prettier-eslint/node_modules/@typescript-eslint/typescript-estree": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", + "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "@typescript-eslint/visitor-keys": "5.62.0", + "debug": "^4.3.4", + "globby": "^11.1.0", + "is-glob": "^4.0.3", + "semver": "^7.3.7", + "tsutils": "^3.21.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/prettier-eslint/node_modules/@typescript-eslint/visitor-keys": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", + "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "5.62.0", + "eslint-visitor-keys": "^3.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, "node_modules/prettier-eslint/node_modules/typescript": { "version": "4.9.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", @@ -3311,9 +3540,9 @@ "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" }, "node_modules/semver": { - "version": "7.5.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", - "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "devOptional": true, "dependencies": { "lru-cache": "^6.0.0" @@ -3561,6 +3790,18 @@ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" }, + "node_modules/ts-api-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.0.2.tgz", + "integrity": "sha512-Cbu4nIqnEdd+THNEsBdkolnOXhg0I8XteoHaEKgvsxpsbWda4IsUut2c187HxywQCvveojow0Dgw/amxtSKVkQ==", + "dev": true, + "engines": { + "node": ">=16.13.0" + }, + "peerDependencies": { + "typescript": ">=4.2.0" + } + }, "node_modules/ts-mixer": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.3.tgz", diff --git a/package.json b/package.json index 0de33b5..4be52be 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,12 @@ "uuid": "^9.0.0" }, "devDependencies": { + "@types/config": "^3.3.0", "@types/node": "^20.5.6", + "@types/node-os-utils": "^1.3.1", + "@types/pino": "^7.0.5", + "@types/uuid": "^9.0.2", + "@typescript-eslint/eslint-plugin": "^6.4.1", "eslint": "^8.47.0", "prettier-eslint": "^15.0.1", "typescript": "^5.2.2" diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index ec325b6..7e3541c 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -28,9 +28,9 @@ module.exports = { return true; }) .map((command) => { - let params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : ''; - let beta = command.isBeta ? `${embedOptions.icons.beta} ` : ''; - let newCommand = command.isNew ? `${embedOptions.icons.new} ` : ''; + const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : ''; + const beta = command.isBeta ? `${embedOptions.icons.beta} ` : ''; + const newCommand = command.isNew ? `${embedOptions.icons.new} ` : ''; return `- **\`/${command.data.name}\`** ${params}- ${beta}${newCommand}${command.data.description}`; }); diff --git a/src/commands/info/status.ts b/src/commands/info/status.ts index b71f2ac..8b322d7 100644 --- a/src/commands/info/status.ts +++ b/src/commands/info/status.ts @@ -39,9 +39,9 @@ module.exports = { return player.generateStatistics(); }) .then((results) => { - let queueCountList = []; - let trackCountList = []; - let listenerCountList = []; + const queueCountList = []; + const trackCountList = []; + const listenerCountList = []; results.map((result) => { queueCountList.push(result.queues.length); if (result.queues.length > 0) { diff --git a/src/commands/player/filters.ts b/src/commands/player/filters.ts index d10f280..c26c7d3 100644 --- a/src/commands/player/filters.ts +++ b/src/commands/player/filters.ts @@ -49,7 +49,7 @@ module.exports = { return; } - let filterOptions = []; + const filterOptions = []; ffmpegFilterOptions.availableFilters.forEach((filter) => { let isEnabled = false; @@ -169,7 +169,7 @@ module.exports = { embedOptions.icons.success } Filters toggled**\nNow using these filters:\n${confirmation.values .map((enabledFilter) => { - let filter = ffmpegFilterOptions.availableFilters.find( + const filter = ffmpegFilterOptions.availableFilters.find( (filter) => enabledFilter == filter.value ); diff --git a/src/commands/player/play.ts b/src/commands/player/play.ts index 0962adb..537bc31 100644 --- a/src/commands/player/play.ts +++ b/src/commands/player/play.ts @@ -136,7 +136,7 @@ module.exports = { } queue = useQueue(interaction.guild.id); - let queueSize = queue?.size ?? 0; + const queueSize = queue?.size ?? 0; if ((searchResult.playlist && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) { logger.debug(`Playlist found but would exceed max queue size. Query: '${query}'.`); diff --git a/src/commands/player/queue.ts b/src/commands/player/queue.ts index 512a32b..3d673cd 100644 --- a/src/commands/player/queue.ts +++ b/src/commands/player/queue.ts @@ -116,7 +116,7 @@ module.exports = { .join('\n'); } - let currentTrack = queue.currentTrack; + const currentTrack = queue.currentTrack; const loopModesFormatted = new Map([ [0, 'disabled'], @@ -127,7 +127,7 @@ module.exports = { const loopModeUserString = loopModesFormatted.get(queue.repeatMode); - let repeatModeString = `${ + const repeatModeString = `${ queue.repeatMode === 0 ? '' : `**${ diff --git a/src/commands/player/seek.ts b/src/commands/player/seek.ts index fa63310..597cfa6 100644 --- a/src/commands/player/seek.ts +++ b/src/commands/player/seek.ts @@ -85,7 +85,7 @@ module.exports = { const durationString = durationArray.join(':'); - let validElements = durationArray.every((value) => { + const validElements = durationArray.every((value) => { return value.length === 2; }); diff --git a/src/commands/system/guilds.ts b/src/commands/system/guilds.ts index 8c3620c..fe5d840 100644 --- a/src/commands/system/guilds.ts +++ b/src/commands/system/guilds.ts @@ -44,7 +44,7 @@ module.exports = { logger.debug(`Successfully fetched ${totalGuildCount} guilds.`); - let guildListFormatted = shardGuilds + const guildListFormatted = shardGuilds .map((guild) => { return { name: guild.name, diff --git a/src/commands/system/reload.ts b/src/commands/system/reload.ts index d1cf18a..67fb9bb 100644 --- a/src/commands/system/reload.ts +++ b/src/commands/system/reload.ts @@ -56,11 +56,11 @@ module.exports = { } const commands = client.commands.map((command) => { - let params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : ''; + const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : ''; return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`; }); - let embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands.join('\n'); + const embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands.join('\n'); logger.debug('Responding with success embed.'); return await interaction.editReply({ diff --git a/src/commands/system/shards.ts b/src/commands/system/shards.ts index 040a72a..06bb1d9 100644 --- a/src/commands/system/shards.ts +++ b/src/commands/system/shards.ts @@ -50,9 +50,9 @@ module.exports = { await client.shard .broadcastEval((shardClient) => { /* eslint-disable no-undef */ - let playerStats = player.generateStatistics(); + const playerStats = player.generateStatistics(); const nodeProcessMemUsageInMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2); - let shardInfo = { + const shardInfo = { shardId: shardClient.shard.ids[0], memUsage: nodeProcessMemUsageInMb, guildCount: shardClient.guilds.cache.size, diff --git a/src/commands/system/systemstatus.ts b/src/commands/system/systemstatus.ts index 6be0d75..7d6f35a 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/commands/system/systemstatus.ts @@ -60,9 +60,9 @@ module.exports = { return player.generateStatistics(); }) .then((results) => { - let queueCountList = []; - let trackCountList = []; - let listenerCountList = []; + const queueCountList = []; + const trackCountList = []; + const listenerCountList = []; results.map((result) => { queueCountList.push(result.queues.length); if (result.queues.length > 0) { diff --git a/src/utils/other/postBotStats.ts b/src/utils/other/postBotStats.ts index 8cb9aea..8e5bfde 100644 --- a/src/utils/other/postBotStats.ts +++ b/src/utils/other/postBotStats.ts @@ -16,8 +16,8 @@ exports.postBotStats = async ({ client, executionId }) => { let guildCount = 0; let memberCount = 0; - let shardCount = client.shard.count; - let shardId = client.shard.ids[0]; + const shardCount = client.shard.count; + const shardId = client.shard.ids[0]; logger.debug('Gathering data about guild and member count from shards...'); await client.shard @@ -119,14 +119,14 @@ exports.postBotStats = async ({ client, executionId }) => { logger.info(`Starting to post bot stats with guild count ${guildCount} and member count ${memberCount}...`); - let statusCodes = []; + const statusCodes = []; sites.map((site) => { if (site.disabled) { return; } - let options = { + const options = { protocol: 'https:', hostname: site.hostname, port: 443, @@ -138,7 +138,7 @@ exports.postBotStats = async ({ client, executionId }) => { } }; - let request = https.request(options, (res) => { + const request = https.request(options, (res) => { res.statusCode === 200 ? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`) : logger.warn(`Request to ${site.hostname}: statusCode: ${res.statusCode}`); diff --git a/src/utils/system/getUptimeFormatted.ts b/src/utils/system/getUptimeFormatted.ts index bbe73e7..d66958e 100644 --- a/src/utils/system/getUptimeFormatted.ts +++ b/src/utils/system/getUptimeFormatted.ts @@ -10,7 +10,7 @@ exports.getUptimeFormatted = async ({ executionId }) => { let uptimeFormattedString = ''; const uptimeInSeconds = process.uptime(); - let uptimeDate = new Date(0); + const uptimeDate = new Date(0); uptimeDate.setSeconds(uptimeInSeconds.toFixed(0)); uptimeFormattedString = `${ uptimeDate.getUTCDate() - 1 From 0d9f4bd404413db34cf06a1464453fe069464ff2 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 00:39:03 +0200 Subject: [PATCH 07/24] fix: Fixed most imports and some typescript changes --- .eslintrc.json | 3 +- package.json | 2 +- src/bot.ts | 22 +-- src/commands/info/help.ts | 8 +- src/commands/info/status.ts | 13 +- src/commands/player/filters.ts | 16 ++- src/commands/player/leave.ts | 12 +- src/commands/player/loop.ts | 14 +- src/commands/player/lyrics.ts | 20 +-- src/commands/player/nowplaying.ts | 14 +- src/commands/player/pause.ts | 14 +- src/commands/player/play.ts | 24 ++-- src/commands/player/queue.ts | 12 +- src/commands/player/remove.ts | 14 +- src/commands/player/seek.ts | 14 +- src/commands/player/shuffle.ts | 14 +- src/commands/player/skip.ts | 14 +- src/commands/player/stop.ts | 12 +- src/commands/player/volume.ts | 14 +- src/commands/system/guilds.ts | 10 +- src/commands/system/reload.ts | 10 +- src/commands/system/shards.ts | 10 +- src/commands/system/systemstatus.ts | 16 ++- src/events/client/debug.ts | 8 +- src/events/client/disconnect.ts | 11 +- src/events/client/error.ts | 8 +- src/events/client/guildCreate.ts | 8 +- src/events/client/guildDelete.ts | 8 +- src/events/client/ready.ts | 15 +- src/events/client/reconnecting.ts | 11 +- src/events/client/warn.ts | 8 +- src/events/interactions/interactionCreate.ts | 14 +- src/events/player/generalDebug.ts | 6 +- src/events/player/generalError.ts | 11 +- src/events/player/playerDebug.ts | 6 +- src/events/player/playerError.ts | 11 +- src/events/player/playerSkip.ts | 11 +- src/events/player/playerStart.ts | 6 +- src/events/process/uncaughtException.ts | 6 +- src/events/process/unhandledRejection.ts | 6 +- src/index.ts | 16 ++- src/services/logger.ts | 2 +- src/types/clientTypes.ts | 7 + src/types/configTypes.ts | 130 ++++++++++++++++++ src/types/playerTypes.ts | 6 + src/utils/deploySlashCommands.ts | 12 +- src/utils/factory/createClient.ts | 12 +- src/utils/factory/createPlayer.ts | 11 +- src/utils/other/cookieParser.ts | 1 + src/utils/other/postBotStats.ts | 5 +- src/utils/other/startLoadTest.ts | 5 +- src/utils/registerClientCommands.ts | 8 +- src/utils/registerEventListeners.ts | 7 +- src/utils/system/getUptimeFormatted.ts | 6 +- src/utils/validation/permissionValidator.ts | 14 +- src/utils/validation/queueValidator.ts | 18 +-- src/utils/validation/searchQueryValidator.ts | 6 +- .../validation/systemCommandValidator.ts | 15 +- src/utils/validation/voiceChannelValidator.ts | 14 +- tsconfig.json | 2 +- 60 files changed, 488 insertions(+), 265 deletions(-) create mode 100644 src/types/clientTypes.ts create mode 100644 src/types/configTypes.ts create mode 100644 src/types/playerTypes.ts diff --git a/.eslintrc.json b/.eslintrc.json index 58dcb68..81b96b1 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -49,6 +49,7 @@ "curly": ["error", "all"], "no-console": ["error"], "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], - "@typescript-eslint/explicit-module-boundary-types": "off" + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/ban-ts-comment": "off" } } diff --git a/package.json b/package.json index 4be52be..511b4ee 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "start-pretty-no-ignore": "node ./dist/index.js | pino-pretty", "deploy": "node ./dist/utils/deploySlashCommands.js", "deploy-pretty": "node ./dist/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId", - "eslint": "eslint ./" + "eslint": "eslint ./src" }, "dependencies": { "@discord-player/extractor": "^4.4.2-dev.1", diff --git a/src/bot.ts b/src/bot.ts index 45af23e..acaf0f9 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -1,13 +1,15 @@ -require('dotenv').config(); -const { registerEventListeners } = require('./utils/registerEventListeners.js'); -const { registerClientCommands } = require('./utils/registerClientCommands.js'); -const { createClient } = require('./utils/factory/createClient.js'); -const { createPlayer } = require('./utils/factory/createPlayer.js'); -const { v4: uuidv4 } = require('uuid'); +import 'dotenv/config'; +import { registerEventListeners } from './utils/registerEventListeners'; +import { registerClientCommands } from './utils/registerClientCommands'; +import { createClient } from './utils/factory/createClient'; +import { createPlayer } from './utils/factory/createPlayer'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from './services/logger'; +import { ExtendedClient } from './types/clientTypes'; +import { Client } from 'discord.js'; const executionId = uuidv4(); - -const logger = require('./services/logger').child({ +const logger = loggerModule.child({ source: 'bot.js', module: 'shardingClient', name: 'shardingClient', @@ -16,14 +18,14 @@ const logger = require('./services/logger').child({ }); (async () => { - const client = await createClient({ executionId }); + const client: ExtendedClient = await createClient({ executionId }); const player = await createPlayer({ client, executionId }); client.on('allShardsReady', async () => { client.registerClientCommands = registerClientCommands; registerEventListeners({ client, player, executionId }); registerClientCommands({ client, executionId }); - client.emit('ready', client); + client.emit('ready', client as Client); }); client.login(process.env.DISCORD_BOT_TOKEN); diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 7e3541c..327c1a4 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -1,7 +1,9 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); +import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { data: new SlashCommandBuilder() @@ -10,7 +12,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, client, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'help.js', module: 'slashCommand', name: '/help', diff --git a/src/commands/info/status.ts b/src/commands/info/status.ts index 8b322d7..b269fa8 100644 --- a/src/commands/info/status.ts +++ b/src/commands/info/status.ts @@ -1,9 +1,12 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { getUptimeFormatted } = require('../../utils/system/getUptimeFormatted'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import osu from 'node-os-utils'; -const { version } = require('../../../package.json'); +// @ts-ignore +import { version } from '../../../package.json'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -14,7 +17,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, client, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'status.js', module: 'slashCommand', name: '/status', diff --git a/src/commands/player/filters.ts b/src/commands/player/filters.ts index c26c7d3..9047e09 100644 --- a/src/commands/player/filters.ts +++ b/src/commands/player/filters.ts @@ -1,17 +1,19 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const ffmpegFilterOptions = config.get('ffmpegFilterOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); -const { +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, ButtonBuilder -} = require('discord.js'); -const { useQueue } = require('discord-player'); +} from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -22,7 +24,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'filters.js', module: 'slashCommand', name: '/filters', diff --git a/src/commands/player/leave.ts b/src/commands/player/leave.ts index d88f31e..cf88094 100644 --- a/src/commands/player/leave.ts +++ b/src/commands/player/leave.ts @@ -1,8 +1,10 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -13,7 +15,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'leave.js', module: 'slashCommand', name: '/leave', diff --git a/src/commands/player/loop.ts b/src/commands/player/loop.ts index 022ca62..4dce11f 100644 --- a/src/commands/player/loop.ts +++ b/src/commands/player/loop.ts @@ -1,10 +1,12 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist } from '../../utils/validation/queueValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -27,7 +29,7 @@ module.exports = { ) ), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'loop.js', module: 'slashCommand', name: '/loop', diff --git a/src/commands/player/lyrics.ts b/src/commands/player/lyrics.ts index 6b9817a..0f2130a 100644 --- a/src/commands/player/lyrics.ts +++ b/src/commands/player/lyrics.ts @@ -1,14 +1,16 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useMainPlayer, useQueue, QueryType } = require('discord-player'); -const { lyricsExtractor } = require('@discord-player/extractor'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useMainPlayer, useQueue, QueryType } from 'discord-player'; +import { lyricsExtractor } from '@discord-player/extractor'; +import loggerModule from '../../services/logger'; const recentQueries = new Map(); -const loggerTempplate = require('../../services/logger').child({ +const loggerTemplate = loggerModule.child({ source: 'lyrics.js', module: 'slashCommand', name: '/lyrics' @@ -32,7 +34,7 @@ module.exports = { .setAutocomplete(true) ), autocomplete: async ({ interaction, executionId }) => { - const logger = loggerTempplate.child({ + const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild.shardId, guildId: interaction.guild.id @@ -92,7 +94,7 @@ module.exports = { return interaction.respond(response); }, execute: async ({ interaction, executionId }) => { - const logger = loggerTempplate.child({ + const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild.shardId, guildId: interaction.guild.id diff --git a/src/commands/player/nowplaying.ts b/src/commands/player/nowplaying.ts index 342b8a9..d73beee 100644 --- a/src/commands/player/nowplaying.ts +++ b/src/commands/player/nowplaying.ts @@ -1,10 +1,12 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions = config.get('playerOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -15,7 +17,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'nowplaying.js', module: 'slashCommand', name: '/nowplaying', diff --git a/src/commands/player/pause.ts b/src/commands/player/pause.ts index f1f8de9..bd704d1 100644 --- a/src/commands/player/pause.ts +++ b/src/commands/player/pause.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -14,7 +16,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'pause.js', module: 'slashCommand', name: '/pause', diff --git a/src/commands/player/play.ts b/src/commands/player/play.ts index 537bc31..47d08f9 100644 --- a/src/commands/player/play.ts +++ b/src/commands/player/play.ts @@ -1,16 +1,18 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const playerOptions = config.get('playerOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { cannotJoinVoiceOrTalk } = require('../../utils/validation/permissionValidator'); -const { transformQuery } = require('../../utils/validation/searchQueryValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useMainPlayer, useQueue } = require('discord-player'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { cannotJoinVoiceOrTalk } from '../../utils/validation/permissionValidator'; +import { transformQuery } from '../../utils/validation/searchQueryValidator'; +import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useMainPlayer, useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; +import { EmbedOptions } from '../../types/configTypes'; const recentQueries = new Map(); -const loggerTempplate = require('../../services/logger').child({ +const loggerTemplate = loggerModule.child({ source: 'play.js', module: 'slashCommand', name: '/play' @@ -34,7 +36,7 @@ module.exports = { .setAutocomplete(true) ), autocomplete: async ({ interaction, executionId }) => { - const logger = loggerTempplate.child({ + const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild.shardId, guildId: interaction.guild.id @@ -86,7 +88,7 @@ module.exports = { return interaction.respond(response); }, execute: async ({ interaction, executionId }) => { - const logger = loggerTempplate.child({ + const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild.shardId, guildId: interaction.guild.id @@ -213,7 +215,7 @@ module.exports = { if ( (error.type === 'TypeError' && - (error.message.includes('Cannot read properties of null (reading \'createStream\')') || + (error.message.includes("Cannot read properties of null (reading 'createStream')") || error.message.includes('Failed to fetch resources for ytdl streaming'))) || error.message.includes('Could not extract stream for this track') ) { @@ -248,7 +250,7 @@ module.exports = { }); } - if (error.message === 'Cannot read properties of null (reading \'createStream\')') { + if (error.message === "Cannot read properties of null (reading 'createStream')") { // Can happen if /play then /leave before track starts playing logger.warn(error, 'Found track but failed to play back audio. Voice connection might be unavailable.'); diff --git a/src/commands/player/queue.ts b/src/commands/player/queue.ts index 3d673cd..83da830 100644 --- a/src/commands/player/queue.ts +++ b/src/commands/player/queue.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const playerOptions = config.get('playerOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -15,7 +17,7 @@ module.exports = { .setNSFW(false) .addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'queue.js', module: 'slashCommand', name: '/queue', diff --git a/src/commands/player/remove.ts b/src/commands/player/remove.ts index 5744879..05e9116 100644 --- a/src/commands/player/remove.ts +++ b/src/commands/player/remove.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist } from '../../utils/validation/queueValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -21,7 +23,7 @@ module.exports = { .setRequired(true) ), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'remove.js', module: 'slashCommand', name: '/remove', diff --git a/src/commands/player/seek.ts b/src/commands/player/seek.ts index 597cfa6..ba06c88 100644 --- a/src/commands/player/seek.ts +++ b/src/commands/player/seek.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -20,7 +22,7 @@ module.exports = { .setRequired(true) ), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'seek.js', module: 'slashCommand', name: '/seek', diff --git a/src/commands/player/shuffle.ts b/src/commands/player/shuffle.ts index f64660c..3ab5f23 100644 --- a/src/commands/player/shuffle.ts +++ b/src/commands/player/shuffle.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist, queueIsEmpty } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist, queueIsEmpty } from '../../utils/validation/queueValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -14,7 +16,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'shuffle.js', module: 'slashCommand', name: '/shuffle', diff --git a/src/commands/player/skip.ts b/src/commands/player/skip.ts index cdfd7e0..8cc8e71 100644 --- a/src/commands/player/skip.ts +++ b/src/commands/player/skip.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -17,7 +19,7 @@ module.exports = { option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1) ), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'skip.js', module: 'slashCommand', name: '/skip', diff --git a/src/commands/player/stop.ts b/src/commands/player/stop.ts index bf3c7c2..3efed8f 100644 --- a/src/commands/player/stop.ts +++ b/src/commands/player/stop.ts @@ -1,8 +1,10 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -13,7 +15,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'stop.js', module: 'slashCommand', name: '/stop', diff --git a/src/commands/player/volume.ts b/src/commands/player/volume.ts index b5052c5..2701c13 100644 --- a/src/commands/player/volume.ts +++ b/src/commands/player/volume.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator'); -const { queueDoesNotExist } = require('../../utils/validation/queueValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); -const { useQueue } = require('discord-player'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +import { queueDoesNotExist } from '../../utils/validation/queueValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { useQueue } from 'discord-player'; +import loggerModule from '../../services/logger'; module.exports = { isNew: false, @@ -21,7 +23,7 @@ module.exports = { .setMaxValue(100) ), execute: async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'volume.js', module: 'slashCommand', name: '/volume', diff --git a/src/commands/system/guilds.ts b/src/commands/system/guilds.ts index fe5d840..09b36aa 100644 --- a/src/commands/system/guilds.ts +++ b/src/commands/system/guilds.ts @@ -1,7 +1,9 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notValidGuildId } = require('../../utils/validation/systemCommandValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { isSystemCommand: true, @@ -13,7 +15,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, client, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'guilds.js', module: 'slashCommand', name: '/guilds', diff --git a/src/commands/system/reload.ts b/src/commands/system/reload.ts index 67fb9bb..3ece3e7 100644 --- a/src/commands/system/reload.ts +++ b/src/commands/system/reload.ts @@ -1,7 +1,9 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notValidGuildId } = require('../../utils/validation/systemCommandValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { isSystemCommand: true, @@ -13,7 +15,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, client, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'reload.js', module: 'slashCommand', name: '/reload', diff --git a/src/commands/system/shards.ts b/src/commands/system/shards.ts index 06bb1d9..67d3822 100644 --- a/src/commands/system/shards.ts +++ b/src/commands/system/shards.ts @@ -1,7 +1,9 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notValidGuildId } = require('../../utils/validation/systemCommandValidator'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { isSystemCommand: true, @@ -30,7 +32,7 @@ module.exports = { .addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)), execute: async ({ interaction, client, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'shards.js', module: 'slashCommand', name: '/shards', diff --git a/src/commands/system/systemstatus.ts b/src/commands/system/systemstatus.ts index 7d6f35a..81b7af5 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/commands/system/systemstatus.ts @@ -1,10 +1,14 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { notValidGuildId } = require('../../utils/validation/systemCommandValidator'); -const { getUptimeFormatted } = require('../../utils/system/getUptimeFormatted'); -const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); +import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; +import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import osu from 'node-os-utils'; -const { version, dependencies } = require('../../../package.json'); +// @ts-ignore +import { version, dependencies } from '../../../package.json'; +import loggerModule from '../../services/logger'; + +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isSystemCommand: true, @@ -16,7 +20,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false), execute: async ({ interaction, client, executionId }) => { - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'systemstatus.js', module: 'slashCommand', name: '/systemstatus', diff --git a/src/events/client/debug.ts b/src/events/client/debug.ts index a75932b..34a80d9 100644 --- a/src/events/client/debug.ts +++ b/src/events/client/debug.ts @@ -1,5 +1,6 @@ -const { v4: uuidv4 } = require('uuid'); -const { Events } = require('discord.js'); +import { v4 as uuidv4 } from 'uuid'; +import { Events } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { name: Events.Debug, @@ -7,8 +8,7 @@ module.exports = { once: false, execute: async (message) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'debug.js', module: 'event', name: 'clientDebug', diff --git a/src/events/client/disconnect.ts b/src/events/client/disconnect.ts index 6985f09..ffb9e4b 100644 --- a/src/events/client/disconnect.ts +++ b/src/events/client/disconnect.ts @@ -1,8 +1,10 @@ -const { v4: uuidv4 } = require('uuid'); +import { v4 as uuidv4 } from 'uuid'; import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const systemOptions = config.get('systemOptions'); -const { EmbedBuilder } = require('discord.js'); +import { EmbedBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { name: 'disconnect', @@ -10,8 +12,7 @@ module.exports = { once: false, execute: async (client) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'disconnect.js', module: 'event', name: 'clientDisconnect', diff --git a/src/events/client/error.ts b/src/events/client/error.ts index c3ed742..cf1bfc1 100644 --- a/src/events/client/error.ts +++ b/src/events/client/error.ts @@ -1,5 +1,6 @@ -const { v4: uuidv4 } = require('uuid'); -const { Events } = require('discord.js'); +import { v4 as uuidv4 } from 'uuid'; +import { Events } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { name: Events.Error, @@ -7,8 +8,7 @@ module.exports = { once: false, execute: async (error) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'error.js', module: 'event', name: 'clientError', diff --git a/src/events/client/guildCreate.ts b/src/events/client/guildCreate.ts index 695747b..4e3c9c3 100644 --- a/src/events/client/guildCreate.ts +++ b/src/events/client/guildCreate.ts @@ -1,5 +1,6 @@ -const { Events } = require('discord.js'); -const { v4: uuidv4 } = require('uuid'); +import { Events } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: Events.GuildCreate, @@ -7,8 +8,7 @@ module.exports = { once: false, execute: async (guild) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'guildCreate.js', module: 'event', name: 'guildCreate', diff --git a/src/events/client/guildDelete.ts b/src/events/client/guildDelete.ts index a378fb4..faf6b9a 100644 --- a/src/events/client/guildDelete.ts +++ b/src/events/client/guildDelete.ts @@ -1,5 +1,6 @@ -const { Events } = require('discord.js'); -const { v4: uuidv4 } = require('uuid'); +import { Events } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: Events.GuildDelete, @@ -7,8 +8,7 @@ module.exports = { once: false, execute: async (guild) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'guildDelete.js', module: 'event', name: 'guildDelete', diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 32ef784..a2c5998 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -1,12 +1,14 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const systemOptions = config.get('systemOptions'); const presenceStatusOptions = config.get('presenceStatusOptions'); const loadTestOptions = config.get('loadTestOptions'); -const { postBotStats } = require('../../utils/other/postBotStats.js'); -const { startLoadTest } = require('../../utils/other/startLoadTest'); -const { Events, EmbedBuilder } = require('discord.js'); -const { v4: uuidv4 } = require('uuid'); +import { postBotStats } from '../../utils/other/postBotStats'; +import { startLoadTest } from '../../utils/other/startLoadTest'; +import { Events, EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: Events.ClientReady, @@ -14,8 +16,7 @@ module.exports = { once: false, execute: async (client) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'ready.js', module: 'event', name: 'clientReady', diff --git a/src/events/client/reconnecting.ts b/src/events/client/reconnecting.ts index b86e347..1ec9797 100644 --- a/src/events/client/reconnecting.ts +++ b/src/events/client/reconnecting.ts @@ -1,8 +1,10 @@ -const { v4: uuidv4 } = require('uuid'); +import { v4 as uuidv4 } from 'uuid'; import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const systemOptions = config.get('systemOptions'); -const { EmbedBuilder } = require('discord.js'); +import { EmbedBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { name: 'reconnecting', @@ -10,8 +12,7 @@ module.exports = { once: false, execute: async (client) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'reconnecting.js', module: 'event', name: 'clientReconnecting', diff --git a/src/events/client/warn.ts b/src/events/client/warn.ts index 191e1fa..0390cb6 100644 --- a/src/events/client/warn.ts +++ b/src/events/client/warn.ts @@ -1,5 +1,6 @@ -const { v4: uuidv4 } = require('uuid'); -const { Events } = require('discord.js'); +import { v4 as uuidv4 } from 'uuid'; +import { Events } from 'discord.js'; +import loggerModule from '../../services/logger'; module.exports = { name: Events.Warn, @@ -7,8 +8,7 @@ module.exports = { once: false, execute: async (warning) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'warn.js', module: 'event', name: 'clientWarn', diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index 17d1f84..cb282bb 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,18 +1,18 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); -const { cannotSendMessageInChannel } = require('../../utils/validation/permissionValidator'); -const { Events, EmbedBuilder } = require('discord.js'); - -const { v4: uuidv4 } = require('uuid'); +import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator'; +import { Events, EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: Events.InteractionCreate, isDebug: false, execute: async (interaction, { client }) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'interactionCreate.js', module: 'event', name: 'interactionCreate', diff --git a/src/events/player/generalDebug.ts b/src/events/player/generalDebug.ts index 0b279ae..6108593 100644 --- a/src/events/player/generalDebug.ts +++ b/src/events/player/generalDebug.ts @@ -1,4 +1,5 @@ -const { v4: uuidv4 } = require('uuid'); +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: 'debug', @@ -6,8 +7,7 @@ module.exports = { isPlayerEvent: false, execute: async (message) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'generalDebug.js', module: 'event', name: 'playerGeneralDebug', diff --git a/src/events/player/generalError.ts b/src/events/player/generalError.ts index be28714..b9f247a 100644 --- a/src/events/player/generalError.ts +++ b/src/events/player/generalError.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const systemOptions = config.get('systemOptions'); -const { EmbedBuilder } = require('discord.js'); -const { v4: uuidv4 } = require('uuid'); +import { EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; // Emitted when the player queue encounters error (general error with queue) module.exports = { @@ -12,8 +14,7 @@ module.exports = { isPlayerEvent: true, execute: async (queue, error) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'generalError.js', module: 'event', name: 'playerGeneralError', diff --git a/src/events/player/playerDebug.ts b/src/events/player/playerDebug.ts index d56acb5..8ee6a38 100644 --- a/src/events/player/playerDebug.ts +++ b/src/events/player/playerDebug.ts @@ -1,4 +1,5 @@ -const { v4: uuidv4 } = require('uuid'); +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: 'error', @@ -6,8 +7,7 @@ module.exports = { isPlayerEvent: true, execute: async (message) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'playerDebug.js', module: 'event', name: 'playerDebug', diff --git a/src/events/player/playerError.ts b/src/events/player/playerError.ts index b407280..75a9c86 100644 --- a/src/events/player/playerError.ts +++ b/src/events/player/playerError.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const systemOptions = config.get('systemOptions'); -const { EmbedBuilder } = require('discord.js'); -const { v4: uuidv4 } = require('uuid'); +import { EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; // Emitted when the player encounters an error while streaming audio track module.exports = { @@ -12,8 +14,7 @@ module.exports = { isPlayerEvent: true, execute: async (queue, error) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'playerError.js', module: 'event', name: 'playerError', diff --git a/src/events/player/playerSkip.ts b/src/events/player/playerSkip.ts index 81d06c6..6baed0c 100644 --- a/src/events/player/playerSkip.ts +++ b/src/events/player/playerSkip.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions = config.get('botOptions'); const systemOptions = config.get('systemOptions'); -const { EmbedBuilder } = require('discord.js'); -const { v4: uuidv4 } = require('uuid'); +import { EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; // Emitted when the audio player fails to load the stream for a track module.exports = { @@ -12,8 +14,7 @@ module.exports = { isPlayerEvent: true, execute: async (queue, track) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'playerSkip.js', module: 'event', name: 'playerSkip', diff --git a/src/events/player/playerStart.ts b/src/events/player/playerStart.ts index 86a2882..06f24ca 100644 --- a/src/events/player/playerStart.ts +++ b/src/events/player/playerStart.ts @@ -1,4 +1,5 @@ -const { v4: uuidv4 } = require('uuid'); +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: 'playerStart', @@ -6,8 +7,7 @@ module.exports = { isPlayerEvent: true, execute: async (queue, track) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'playerStart.js', module: 'event', name: 'playerStart', diff --git a/src/events/process/uncaughtException.ts b/src/events/process/uncaughtException.ts index 36af29f..0041f59 100644 --- a/src/events/process/uncaughtException.ts +++ b/src/events/process/uncaughtException.ts @@ -1,12 +1,12 @@ -const { v4: uuidv4 } = require('uuid'); +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: 'uncaughtException', isDebug: false, execute: async (error) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'uncaughtException.js', module: 'event', name: 'uncaughtException', diff --git a/src/events/process/unhandledRejection.ts b/src/events/process/unhandledRejection.ts index 096ce62..a33a34a 100644 --- a/src/events/process/unhandledRejection.ts +++ b/src/events/process/unhandledRejection.ts @@ -1,12 +1,12 @@ -const { v4: uuidv4 } = require('uuid'); +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../../services/logger'; module.exports = { name: 'unhandledRejection', isDebug: false, execute: async (error) => { const executionId = uuidv4(); - - const logger = require('../../services/logger').child({ + const logger = loggerModule.child({ source: 'unhandledRejection.js', module: 'event', name: 'unhandledRejection', diff --git a/src/index.ts b/src/index.ts index d17b177..661ed07 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,11 @@ -require('dotenv').config(); +import 'dotenv/config'; import config from 'config'; -const shardingOptions = config.get('shardingOptions'); +import { Client, Shard } from 'discord.js'; +import { ShardingManager, ShardEvents } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from './services/logger'; -const { ShardingManager, ShardEvents } = require('discord.js'); -const { v4: uuidv4 } = require('uuid'); +const shardingOptions: object = config.get('shardingOptions'); const manager = new ShardingManager('./dist/bot.js', { token: process.env.DISCORD_BOT_TOKEN, @@ -12,10 +14,10 @@ const manager = new ShardingManager('./dist/bot.js', { const readyShards = new Set(); -manager.on('shardCreate', (shard) => { +manager.on('shardCreate', (shard: Shard) => { const executionId = uuidv4(); - const logger = require('./services/logger').child({ + const logger = loggerModule.child({ source: 'index.js', module: 'shardingManager', name: 'shardingManager', @@ -29,7 +31,7 @@ manager.on('shardCreate', (shard) => { shard.on(ShardEvents.Ready, () => { readyShards.add(shard.id); if (readyShards.size === manager.totalShards) { - manager.broadcastEval((client) => client.emit('allShardsReady')); + manager.broadcastEval((client: Client) => client.emit('allShardsReady')); logger.info('All shards ready, bot is now online.'); } }); diff --git a/src/services/logger.ts b/src/services/logger.ts index de66f84..5bdf4a5 100644 --- a/src/services/logger.ts +++ b/src/services/logger.ts @@ -76,5 +76,5 @@ const logLevelConfig = { }; const logger = pino(logLevelConfig, transport); - +export default logger; module.exports = logger; diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts new file mode 100644 index 0000000..fcc2613 --- /dev/null +++ b/src/types/clientTypes.ts @@ -0,0 +1,7 @@ +import { Client } from 'discord.js'; + +type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; + +export interface ExtendedClient extends Client { + registerClientCommands?: RegisterClientCommandsFunction; +} diff --git a/src/types/configTypes.ts b/src/types/configTypes.ts new file mode 100644 index 0000000..ce346bd --- /dev/null +++ b/src/types/configTypes.ts @@ -0,0 +1,130 @@ +import { ActivityType, PresenceUpdateStatus, ColorResolvable } from 'discord.js'; +export interface BotOptions { + name: string; + botInviteUrl: string; + serverInviteUrl: string; +} + +export interface ShardingOptions { + totalShards: string; + shardList: string; + mode: string; + respawn: boolean; +} + +export interface LoggerOptions { + minimumLogLevel: string; + minimumLogLevelConsole: string; + discordPlayerDebug: boolean; +} + +export interface SystemOptions { + systemGuildIds: string[]; + systemMessageChannelId: string; + systemUserId: string; +} + +export interface PresenceStatusOptions { + status: PresenceUpdateStatus; + activities: { + name: string; + type: ActivityType; + }[]; +} + +export interface EmbedOptions { + info: { + fallbackThumbnailUrl: string; + }; + colors: { + success: ColorResolvable; + warning: ColorResolvable; + error: ColorResolvable; + info: ColorResolvable; + note: ColorResolvable; + }; + icons: { + logo: string; + beta: string; + new: string; + rule: string; + support: string; + bot: string; + server: string; + discord: string; + audioPlaying: string; + audioStartedPlaying: string; + success: string; + error: string; + warning: string; + disable: string; + enable: string; + disabled: string; + enabled: string; + nextTrack: string; + previousTrack: string; + pauseResumeTrack: string; + shuffleQueue: string; + loop: string; + loopAction: string; + autoplay: string; + autoplayAction: string; + looping: string; + autoplaying: string; + skipped: string; + back: string; + pauseResumed: string; + shuffled: string; + volume: string; + volumeIsMuted: string; + volumeChanged: string; + volumeMuted: string; + queue: string; + sourceArbitrary: string; + sourceAppleMusic: string; + sourceYouTube: string; + sourceSoundCloud: string; + sourceSpotify: string; + liveTrack: string; + }; +} + +export interface PlayerOptions { + leaveOnEmpty: boolean; + leaveOnEmptyCooldown: number; + leaveOnEnd: boolean; + leaveonEndCooldown: number; + leaveOnStop: boolean; + leaveOnStopCooldown: number; + defaultVolume: number; + maxQueueSize: number; + maxHistorySize: number; + bufferingTimeout: number; + connectionTimeout: number; + progressBar: { + length: number; + timecodes: boolean; + separator: string; + indicator: string; + leftChar: string; + rightChar: string; + }; +} + +export interface FFmpegFilterOption { + label: string; + value: string; + description: string; + emoji: string; +} + +export interface FFmpegFilterOptions { + threadAmount: string; + availableFilters: FFmpegFilterOption[]; +} + +export interface LoadTestOptions { + enabled: boolean; + trackUrl: string; + channelIdsToJoin: string[]; +} diff --git a/src/types/playerTypes.ts b/src/types/playerTypes.ts new file mode 100644 index 0000000..446e646 --- /dev/null +++ b/src/types/playerTypes.ts @@ -0,0 +1,6 @@ +import { Client } from 'discord.js'; + +export interface CreatePlayerParams { + client: Client; + executionId: string; +} diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index 4315d99..b58681e 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -1,14 +1,15 @@ -require('dotenv').config(); +import 'dotenv/config'; import fs from 'node:fs'; import path from 'node:path'; -const { REST, Routes } = require('discord.js'); +import { REST, Routes } from 'discord.js'; import config from 'config'; -const { v4: uuidv4 } = require('uuid'); +import { v4 as uuidv4 } from 'uuid'; +import loggerModule from '../services/logger'; const systemOptions = config.get('systemOptions'); const executionId = uuidv4(); -const logger = require('../services/logger').child({ +const logger = loggerModule.child({ source: 'deploySlashCommands.js', module: 'deploy', name: 'deploySlashCommands', @@ -24,6 +25,7 @@ for (const folder of commandFolders) { .filter((file) => file.endsWith('.js')); for (const file of commandFiles) { + /* eslint-disable @typescript-eslint/no-var-requires */ const command = require(`../commands/${folder}/${file}`); command.isSystemCommand ? systemCommands.push(command.data.toJSON()) @@ -72,7 +74,7 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN) } catch (error) { logger.error( error, - 'Failed to refresh system slash commands. Make sure the bot is in the system guilds specified in \'systemOptions\'.' + "Failed to refresh system slash commands. Make sure the bot is in the system guilds specified in 'systemOptions'." ); } })(); diff --git a/src/utils/factory/createClient.ts b/src/utils/factory/createClient.ts index 198c758..29596a5 100644 --- a/src/utils/factory/createClient.ts +++ b/src/utils/factory/createClient.ts @@ -1,7 +1,9 @@ import Discord from 'discord.js'; +import loggerModule from '../../services/logger'; +import { Client } from 'discord.js'; -exports.createClient = async ({ executionId }) => { - const logger = require('../../services/logger').child({ +export const createClient = async ({ executionId }: { executionId: string }) => { + const logger = loggerModule.child({ source: 'createClient.js', module: 'utilFactory', name: 'createClient', @@ -12,7 +14,7 @@ exports.createClient = async ({ executionId }) => { try { logger.debug('Creating discord.js client...'); - const client = new Discord.Client({ + const client: Client = new Discord.Client({ intents: [Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildVoiceStates], makeCache: Discord.Options.cacheWithLimits({ ...Discord.Options.DefaultMakeCacheSettings, @@ -22,7 +24,7 @@ exports.createClient = async ({ executionId }) => { ReactionManager: 0, GuildMemberManager: { maxSize: 50, - keepOverLimit: (member) => member.id === client.user.id + keepOverLimit: (member) => member.id === client.user?.id } }), sweepers: { @@ -33,7 +35,7 @@ exports.createClient = async ({ executionId }) => { }, users: { interval: 3600, - filter: () => (user) => user.id !== client.user.id + filter: () => (user) => user.id !== client.user?.id } } }); diff --git a/src/utils/factory/createPlayer.ts b/src/utils/factory/createPlayer.ts index 3b81a51..314c77d 100644 --- a/src/utils/factory/createPlayer.ts +++ b/src/utils/factory/createPlayer.ts @@ -1,12 +1,14 @@ -const { Player } = require('discord-player'); +import { Player } from 'discord-player'; +import loggerModule from '../../services/logger'; +import { CreatePlayerParams } from '../../types/playerTypes'; -exports.createPlayer = async ({ client, executionId }) => { - const logger = require('../../services/logger').child({ +export const createPlayer = async ({ client, executionId }: CreatePlayerParams) => { + const logger = loggerModule.child({ source: 'createPlayer.js', module: 'utilFactory', name: 'createPlayer', executionId: executionId, - shardId: client.shard.ids[0] + shardId: client.shard?.ids[0] }); try { @@ -27,6 +29,7 @@ exports.createPlayer = async ({ client, executionId }) => { // make player accessible from anywhere in the application // primarily to be able to use it in broadcastEval and other sharding methods + // @ts-ignore global.player = player; await player.extractors.loadDefault(); diff --git a/src/utils/other/cookieParser.ts b/src/utils/other/cookieParser.ts index db0e0ae..8948097 100644 --- a/src/utils/other/cookieParser.ts +++ b/src/utils/other/cookieParser.ts @@ -1,5 +1,6 @@ import path from 'node:path'; import fs from 'node:fs'; +/* eslint-disable @typescript-eslint/no-var-requires */ const cookies = require(path.resolve('./cookies.json')); try { diff --git a/src/utils/other/postBotStats.ts b/src/utils/other/postBotStats.ts index 8e5bfde..1b41044 100644 --- a/src/utils/other/postBotStats.ts +++ b/src/utils/other/postBotStats.ts @@ -1,7 +1,8 @@ import https from 'node:https'; +import loggerModule from '../../services/logger'; -exports.postBotStats = async ({ client, executionId }) => { - const logger = require('../../services/logger').child({ +export const postBotStats = async ({ client, executionId }) => { + const logger = loggerModule.child({ source: 'postBotStats.js', module: 'utilOther', name: 'postBotStats', diff --git a/src/utils/other/startLoadTest.ts b/src/utils/other/startLoadTest.ts index 985aa5a..191af1a 100644 --- a/src/utils/other/startLoadTest.ts +++ b/src/utils/other/startLoadTest.ts @@ -1,8 +1,9 @@ import config from 'config'; +import loggerModule from '../../services/logger'; const loadTestOptions = config.get('loadTestOptions'); -exports.startLoadTest = async ({ client, executionId }) => { - const logger = require('../../services/logger').child({ +export const startLoadTest = async ({ client, executionId }) => { + const logger = loggerModule.child({ source: 'startLoadTest.js', module: 'utilOther', name: 'startLoadTest', diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index ea45d37..718eea9 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -1,9 +1,10 @@ import fs from 'node:fs'; import path from 'node:path'; -const { Collection } = require('discord.js'); +import { Collection } from 'discord.js'; +import loggerModule from '../services/logger'; -exports.registerClientCommands = ({ client, executionId }) => { - const logger = require('../services/logger').child({ +export const registerClientCommands = ({ client, executionId }) => { + const logger = loggerModule.child({ source: 'registerClientCommands.js', module: 'register', name: 'registerClientCommands', @@ -27,6 +28,7 @@ exports.registerClientCommands = ({ client, executionId }) => { delete require.cache[require.resolve(`../commands/${folder}/${file}`)]; // register command + /* eslint-disable @typescript-eslint/no-var-requires */ const command = require(`../commands/${folder}/${file}`); client.commands.delete(command.data.name); client.commands.set(command.data.name, command); diff --git a/src/utils/registerEventListeners.ts b/src/utils/registerEventListeners.ts index 3507ca1..628c6f4 100644 --- a/src/utils/registerEventListeners.ts +++ b/src/utils/registerEventListeners.ts @@ -1,11 +1,11 @@ import fs from 'node:fs'; import path from 'node:path'; import config from 'config'; - +import loggerModule from '../services/logger'; const loggerOptions = config.get('loggerOptions'); -exports.registerEventListeners = ({ client, player, executionId }) => { - const logger = require('../services/logger').child({ +export const registerEventListeners = ({ client, player, executionId }) => { + const logger = loggerModule.child({ source: 'registerEventListeners.js', module: 'register', name: 'registerEventListeners', @@ -24,6 +24,7 @@ exports.registerEventListeners = ({ client, player, executionId }) => { .filter((file) => file.endsWith('.js')); for (const file of eventFiles) { + /* eslint-disable @typescript-eslint/no-var-requires */ const event = require(`../events/${folder}/${file}`); switch (folder) { case 'client': diff --git a/src/utils/system/getUptimeFormatted.ts b/src/utils/system/getUptimeFormatted.ts index d66958e..f355ba3 100644 --- a/src/utils/system/getUptimeFormatted.ts +++ b/src/utils/system/getUptimeFormatted.ts @@ -1,5 +1,7 @@ -exports.getUptimeFormatted = async ({ executionId }) => { - const logger = require('../../services/logger').child({ +import loggerModule from '../../services/logger'; + +export const getUptimeFormatted = async ({ executionId }) => { + const logger = loggerModule.child({ source: 'getUptimeFormatted.js', module: 'utilSystem', name: 'getUptimeFormatted', diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index 9b9044c..b3904da 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { EmbedBuilder } = require('discord.js'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { EmbedBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; -exports.cannotJoinVoiceOrTalk = async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ +export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }) => { + const logger = loggerModule.child({ source: 'permissionValidator.js', module: 'utilValidation', name: 'cannotJoinVoiceOrTalk', @@ -34,8 +36,8 @@ exports.cannotJoinVoiceOrTalk = async ({ interaction, executionId }) => { return false; }; -exports.cannotSendMessageInChannel = async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ +export const cannotSendMessageInChannel = async ({ interaction, executionId }) => { + const logger = loggerModule.child({ source: 'permissionValidator.js', module: 'utilValidation', name: 'cannotSendMessageInChannel', diff --git a/src/utils/validation/queueValidator.ts b/src/utils/validation/queueValidator.ts index 6579fda..3d64934 100644 --- a/src/utils/validation/queueValidator.ts +++ b/src/utils/validation/queueValidator.ts @@ -1,9 +1,11 @@ import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { EmbedBuilder } = require('discord.js'); +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { EmbedBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; -exports.queueDoesNotExist = async ({ interaction, queue, executionId }) => { - const logger = require('../../services/logger').child({ +export const queueDoesNotExist = async ({ interaction, queue, executionId }) => { + const logger = loggerModule.child({ source: 'queueValidator.js', module: 'utilValidation', name: 'queueDoesNotExist', @@ -30,8 +32,8 @@ exports.queueDoesNotExist = async ({ interaction, queue, executionId }) => { return false; }; -exports.queueNoCurrentTrack = async ({ interaction, queue, executionId }) => { - const logger = require('../../services/logger').child({ +export const queueNoCurrentTrack = async ({ interaction, queue, executionId }) => { + const logger = loggerModule.child({ source: 'queueValidator.js', module: 'utilValidation', name: 'queueNoCurrentTrack', @@ -58,8 +60,8 @@ exports.queueNoCurrentTrack = async ({ interaction, queue, executionId }) => { return false; }; -exports.queueIsEmpty = async ({ interaction, queue, executionId }) => { - const logger = require('../../services/logger').child({ +export const queueIsEmpty = async ({ interaction, queue, executionId }) => { + const logger = loggerModule.child({ source: 'queueValidator.js', module: 'utilValidation', name: 'queueIsEmpty', diff --git a/src/utils/validation/searchQueryValidator.ts b/src/utils/validation/searchQueryValidator.ts index 5300a82..8d19916 100644 --- a/src/utils/validation/searchQueryValidator.ts +++ b/src/utils/validation/searchQueryValidator.ts @@ -1,5 +1,7 @@ -exports.transformQuery = async ({ query, executionId }) => { - const logger = require('../../services/logger').child({ +import loggerModule from '../../services/logger'; + +export const transformQuery = async ({ query, executionId }) => { + const logger = loggerModule.child({ source: 'searchQueryValidator.js', module: 'utilValidation', name: 'transformQuery', diff --git a/src/utils/validation/systemCommandValidator.ts b/src/utils/validation/systemCommandValidator.ts index 0ff7c78..22d6e91 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/utils/validation/systemCommandValidator.ts @@ -1,10 +1,13 @@ -import config from 'config'; -const embedOptions = config.get('embedOptions'); -const systemOptions = config.get('systemOptions'); -const { EmbedBuilder } = require('discord.js'); +import loggerModule from '../../services/logger'; -exports.notValidGuildId = async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ +import config from 'config'; +import { EmbedOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const systemOptions = config.get('systemOptions'); +import { EmbedBuilder } from 'discord.js'; + +export const notValidGuildId = async ({ interaction, executionId }) => { + const logger = loggerModule.child({ source: 'systemCommandValidator.js', module: 'utilValidation', name: 'notValidGuildId', diff --git a/src/utils/validation/voiceChannelValidator.ts b/src/utils/validation/voiceChannelValidator.ts index da90230..264d79c 100644 --- a/src/utils/validation/voiceChannelValidator.ts +++ b/src/utils/validation/voiceChannelValidator.ts @@ -1,9 +1,11 @@ +import { EmbedOptions } from '../../types/configTypes'; +import loggerModule from '../../services/logger'; import config from 'config'; -const embedOptions = config.get('embedOptions'); -const { EmbedBuilder } = require('discord.js'); +const embedOptions: EmbedOptions = config.get('embedOptions'); +import { EmbedBuilder } from 'discord.js'; -exports.notInVoiceChannel = async ({ interaction, executionId }) => { - const logger = require('../../services/logger').child({ +export const notInVoiceChannel = async ({ interaction, executionId }) => { + const logger = loggerModule.child({ source: 'voiceChannelValidator.js', module: 'validator', name: 'notInVoiceChannel', @@ -30,8 +32,8 @@ exports.notInVoiceChannel = async ({ interaction, executionId }) => { return false; }; -exports.notInSameVoiceChannel = async ({ interaction, queue, executionId }) => { - const logger = require('../../services/logger').child({ +export const notInSameVoiceChannel = async ({ interaction, queue, executionId }) => { + const logger = loggerModule.child({ source: 'voiceChannelValidator.js', module: 'utilValidation', name: 'notInSameVoiceChannel', diff --git a/tsconfig.json b/tsconfig.json index 460d0d2..40ab056 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -9,6 +9,6 @@ "skipLibCheck": true, // Skip type checking of declaration files "forceConsistentCasingInFileNames": true // Disallow inconsistently-cased references to the same file }, - "include": ["src/**/*.ts"], // Source files to be compiled + "include": ["src/**/*.ts", "src/types/**/*.ts"], // Source files to be compiled "exclude": ["node_modules"] // Exclude node_modules from compilation } From 89f8e2d0d168297891e662261bbd40a8ce5d6773 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 01:07:33 +0200 Subject: [PATCH 08/24] fix: Fixed annotations --- src/types/clientTypes.ts | 3 ++- src/types/eventTypes.ts | 3 +++ src/types/utilTypes.ts | 13 +++++++++++++ src/utils/deploySlashCommands.ts | 25 +++++++++++++++++-------- src/utils/registerClientCommands.ts | 11 ++++++++--- src/utils/registerEventListeners.ts | 21 ++++++++++++--------- 6 files changed, 55 insertions(+), 21 deletions(-) create mode 100644 src/types/eventTypes.ts create mode 100644 src/types/utilTypes.ts diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index fcc2613..74fb273 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -1,7 +1,8 @@ -import { Client } from 'discord.js'; +import { Client, Collection } from 'discord.js'; type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; export interface ExtendedClient extends Client { registerClientCommands?: RegisterClientCommandsFunction; + commands?: Collection; } diff --git a/src/types/eventTypes.ts b/src/types/eventTypes.ts new file mode 100644 index 0000000..38cdd28 --- /dev/null +++ b/src/types/eventTypes.ts @@ -0,0 +1,3 @@ +export type ClientEventArguments = unknown[]; +export type ProcessEventArguments = unknown[]; +export type PlayerEventArguments = unknown[]; diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts new file mode 100644 index 0000000..f843aa9 --- /dev/null +++ b/src/types/utilTypes.ts @@ -0,0 +1,13 @@ +import { Player } from 'discord-player'; +import { ExtendedClient } from './clientTypes'; + +export interface RegisterEventListenersParams { + client: ExtendedClient; + player: Player; + executionId: string; +} + +export interface RegisterClientCommandsParams { + client: ExtendedClient; + executionId: string; +} diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index b58681e..f09d19d 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -1,11 +1,12 @@ import 'dotenv/config'; import fs from 'node:fs'; import path from 'node:path'; -import { REST, Routes } from 'discord.js'; +import { REST, RouteLike, Routes, SlashCommandBuilder } from 'discord.js'; import config from 'config'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../services/logger'; -const systemOptions = config.get('systemOptions'); +import { SystemOptions } from '../types/configTypes'; +const systemOptions: SystemOptions = config.get('systemOptions'); const executionId = uuidv4(); @@ -16,8 +17,8 @@ const logger = loggerModule.child({ executionId: executionId }); -const slashCommands = []; -const systemCommands = []; +const slashCommands: SlashCommandBuilder[] = []; +const systemCommands: SlashCommandBuilder[] = []; const commandFolders = fs.readdirSync(path.resolve('./dist/commands')); for (const folder of commandFolders) { const commandFiles = fs @@ -33,6 +34,14 @@ for (const folder of commandFolders) { } } +if (!process.env.DISCORD_BOT_TOKEN) { + throw new Error('DISCORD_BOT_TOKEN environment variable is not set.'); +} + +if (!process.env.DISCORD_APPLICATION_ID) { + throw new Error('DISCORD_APPLICATION_ID environment variable is not set.'); +} + const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN); (async () => { @@ -46,7 +55,7 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN) logger.debug(`Bot user slash commands found: ${slashCommands.map((command) => `/${command.name}`).join(', ')}`); logger.info('Started refreshing user slash commands.'); - await refreshCommands(Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID), slashCommands); + await refreshCommands(Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID!), slashCommands); logger.info('Successfully refreshed user slash commands.'); } catch (error) { logger.error(error, 'Failed to refresh user slash commands.'); @@ -62,10 +71,10 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN) logger.info('Started refreshing system slash commands.'); const systemGuildIds = systemOptions.systemGuildIds; await Promise.all( - systemGuildIds.map((systemGuildId) => { + systemGuildIds.map((systemGuildId: string) => { logger.debug(`Refreshing system slash command for guild id '${systemGuildId}'.`); refreshCommands( - Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, systemGuildId), + Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID!, systemGuildId), systemCommands ); }) @@ -79,6 +88,6 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN) } })(); -async function refreshCommands(route, commands) { +async function refreshCommands(route: RouteLike, commands: object[]) { await rest.put(route, { body: commands }); } diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index 718eea9..1542e0b 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -2,14 +2,15 @@ import fs from 'node:fs'; import path from 'node:path'; import { Collection } from 'discord.js'; import loggerModule from '../services/logger'; +import { RegisterClientCommandsParams } from '../types/utilTypes'; -export const registerClientCommands = ({ client, executionId }) => { +export const registerClientCommands = ({ client, executionId }: RegisterClientCommandsParams) => { const logger = loggerModule.child({ source: 'registerClientCommands.js', module: 'register', name: 'registerClientCommands', executionId: executionId, - shardId: client.shard.ids[0] + shardId: client.shard?.ids[0] }); logger.debug('Registering client commands...'); @@ -33,7 +34,11 @@ export const registerClientCommands = ({ client, executionId }) => { client.commands.delete(command.data.name); client.commands.set(command.data.name, command); } catch (error) { - logger.error(`Error registering command ${folder}/${file}: ${error.message}`); + if (error instanceof Error) { + logger.error(`Error registering command ${folder}/${file}: ${error.message}`); + } else { + throw error; + } } } } diff --git a/src/utils/registerEventListeners.ts b/src/utils/registerEventListeners.ts index 628c6f4..62eb477 100644 --- a/src/utils/registerEventListeners.ts +++ b/src/utils/registerEventListeners.ts @@ -2,15 +2,18 @@ import fs from 'node:fs'; import path from 'node:path'; import config from 'config'; import loggerModule from '../services/logger'; -const loggerOptions = config.get('loggerOptions'); +import { LoggerOptions } from '../types/configTypes'; +import { RegisterEventListenersParams } from '../types/utilTypes'; +import { ClientEventArguments, PlayerEventArguments, ProcessEventArguments } from '../types/eventTypes'; +const loggerOptions: LoggerOptions = config.get('loggerOptions'); -export const registerEventListeners = ({ client, player, executionId }) => { +export const registerEventListeners = ({ client, player, executionId }: RegisterEventListenersParams) => { const logger = loggerModule.child({ source: 'registerEventListeners.js', module: 'register', name: 'registerEventListeners', executionId: executionId, - shardId: client.shard.ids[0] + shardId: client.shard?.ids[0] }); logger.debug('Registering event listeners...'); @@ -29,20 +32,20 @@ export const registerEventListeners = ({ client, player, executionId }) => { switch (folder) { case 'client': if (event.once) { - client.once(event.name, (...args) => event.execute(...args)); + client.once(event.name, (...args: ClientEventArguments) => event.execute(...args)); } else { if (!event.isDebug || process.env.MINIMUM_LOG_LEVEL === 'debug') { - client.on(event.name, (...args) => event.execute(...args)); + client.on(event.name, (...args: ClientEventArguments) => event.execute(...args)); } } break; case 'interactions': - client.on(event.name, (...args) => event.execute(...args, { client })); + client.on(event.name, (...args: ClientEventArguments) => event.execute(...args, { client })); break; case 'process': - process.on(event.name, (...args) => event.execute(...args)); + process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args)); break; case 'player': @@ -51,10 +54,10 @@ export const registerEventListeners = ({ client, player, executionId }) => { (loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug) ) { if (event.isPlayerEvent) { - player.events.on(event.name, (...args) => event.execute(...args)); + player.events.on(event.name, (...args: PlayerEventArguments) => event.execute(...args)); break; } else { - player.on(event.name, (...args) => event.execute(...args)); + player.on(event.name, (...args: PlayerEventArguments) => event.execute(...args)); } } break; From d38ed188429ab7e532c8bdd261ebb3dc0ddbf8d9 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 01:36:21 +0200 Subject: [PATCH 09/24] fix: annotated util validation --- src/types/utilTypes.ts | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts index f843aa9..e71613b 100644 --- a/src/types/utilTypes.ts +++ b/src/types/utilTypes.ts @@ -1,5 +1,7 @@ import { Player } from 'discord-player'; import { ExtendedClient } from './clientTypes'; +import { ChatInputCommandInteraction } from 'discord.js'; +import { GuildQueue } from 'discord-player'; export interface RegisterEventListenersParams { client: ExtendedClient; @@ -11,3 +13,52 @@ export interface RegisterClientCommandsParams { client: ExtendedClient; executionId: string; } + +export interface NotInVoiceChannelParams { + interaction: ChatInputCommandInteraction; + executionId: string; +} + +export interface NotInSameVoiceChannelParams { + interaction: ChatInputCommandInteraction; + queue: GuildQueue; + executionId: string; +} + +export interface NotValidGuildIdParams { + interaction: ChatInputCommandInteraction; + executionId: string; +} + +export interface TransformQueryParams { + query: string; + executionId: string; +} + +export interface QueueDoesNotExistParams { + interaction: ChatInputCommandInteraction; + queue: GuildQueue; + executionId: string; +} + +export interface QueueNoCurrentTrackParams { + interaction: ChatInputCommandInteraction; + queue: GuildQueue; + executionId: string; +} + +export interface QueueIsEmptyParams { + interaction: ChatInputCommandInteraction; + queue: GuildQueue; + executionId: string; +} + +export interface CannotJoinVoiceOrTalkParams { + interaction: ChatInputCommandInteraction; + executionId: string; +} + +export interface CannotSendMessageInChannelParams { + interaction: ChatInputCommandInteraction; + executionId: string; +} From 1ae950347713378408d1429b54680a116155f071 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 01:36:58 +0200 Subject: [PATCH 10/24] fix: annotated util validation functions --- src/utils/validation/permissionValidator.ts | 46 ++++++++++--------- src/utils/validation/queueValidator.ts | 19 ++++---- src/utils/validation/searchQueryValidator.ts | 14 ++++-- .../validation/systemCommandValidator.ts | 13 +++--- src/utils/validation/voiceChannelValidator.ts | 22 +++++---- 5 files changed, 64 insertions(+), 50 deletions(-) diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index b3904da..23cec3a 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -1,22 +1,23 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -import { EmbedBuilder } from 'discord.js'; +import { EmbedBuilder, GuildMember, VoiceChannel, TextChannel } from 'discord.js'; import loggerModule from '../../services/logger'; +import { CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams } from '../../types/utilTypes'; -export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }) => { +export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: CannotJoinVoiceOrTalkParams) => { const logger = loggerModule.child({ source: 'permissionValidator.js', module: 'utilValidation', name: 'cannotJoinVoiceOrTalk', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); - const channel = interaction.member.voice.channel; + const channel = interaction.member instanceof GuildMember ? interaction.member.voice.channel : null; - if (!channel.joinable || !channel.speakable) { + if (channel instanceof VoiceChannel && (!channel.joinable || !channel.speakable)) { await interaction.editReply({ embeds: [ new EmbedBuilder() @@ -36,20 +37,20 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }) => { return false; }; -export const cannotSendMessageInChannel = async ({ interaction, executionId }) => { +export const cannotSendMessageInChannel = async ({ interaction, executionId }: CannotSendMessageInChannelParams) => { const logger = loggerModule.child({ source: 'permissionValidator.js', module: 'utilValidation', name: 'cannotSendMessageInChannel', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); const channel = interaction.channel; // only checks if channel is viewable, as bot will have permission to send interaction replies if channel is viewable - if (!channel.viewable) { + if (channel instanceof TextChannel && !channel.viewable) { logger.info( `User tried to use command '${interaction.commandName}' but the bot had no permission to send reply in text channel.` ); @@ -66,20 +67,23 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }) = `**${embedOptions.icons.warning} Oops!**\nI do not have permission to send message replies in the channel you are in.\n\nPlease make sure I have the **\`View Channel\`** permission in this text channel.` ) .setColor(embedOptions.colors.warning) - ], - ephemeral: true + ] }); } catch (error) { - if (error.message == 'The reply to this interaction has already been sent or deferred.') { - logger.warn( - 'Error while sending ephemereal message about insufficient permissions to send message in channel.' - ); - logger.debug(error); + if (error instanceof Error) { + if (error.message == 'The reply to this interaction has already been sent or deferred.') { + logger.warn( + 'Error while sending ephemereal message about insufficient permissions to send message in channel.' + ); + logger.debug(error); + } else { + logger.error( + error, + 'Failed to send ephemeral reply to user in channel that bot cannot view/send message in.' + ); + } } else { - logger.error( - error, - 'Failed to send ephemeral reply to user in channel that bot cannot view/send message in.' - ); + throw error; } } diff --git a/src/utils/validation/queueValidator.ts b/src/utils/validation/queueValidator.ts index 3d64934..08935d6 100644 --- a/src/utils/validation/queueValidator.ts +++ b/src/utils/validation/queueValidator.ts @@ -3,15 +3,16 @@ import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); import { EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; +import { QueueDoesNotExistParams, QueueNoCurrentTrackParams, QueueIsEmptyParams } from '../../types/utilTypes'; -export const queueDoesNotExist = async ({ interaction, queue, executionId }) => { +export const queueDoesNotExist = async ({ interaction, queue, executionId }: QueueDoesNotExistParams) => { const logger = loggerModule.child({ source: 'queueValidator.js', module: 'utilValidation', name: 'queueDoesNotExist', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (!queue) { @@ -32,14 +33,14 @@ export const queueDoesNotExist = async ({ interaction, queue, executionId }) => return false; }; -export const queueNoCurrentTrack = async ({ interaction, queue, executionId }) => { +export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: QueueNoCurrentTrackParams) => { const logger = loggerModule.child({ source: 'queueValidator.js', module: 'utilValidation', name: 'queueNoCurrentTrack', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (!queue.currentTrack) { @@ -60,14 +61,14 @@ export const queueNoCurrentTrack = async ({ interaction, queue, executionId }) = return false; }; -export const queueIsEmpty = async ({ interaction, queue, executionId }) => { +export const queueIsEmpty = async ({ interaction, queue, executionId }: QueueIsEmptyParams) => { const logger = loggerModule.child({ source: 'queueValidator.js', module: 'utilValidation', name: 'queueIsEmpty', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (queue.tracks.data.length === 0) { diff --git a/src/utils/validation/searchQueryValidator.ts b/src/utils/validation/searchQueryValidator.ts index 8d19916..7915e13 100644 --- a/src/utils/validation/searchQueryValidator.ts +++ b/src/utils/validation/searchQueryValidator.ts @@ -1,6 +1,7 @@ import loggerModule from '../../services/logger'; +import { TransformQueryParams } from '../../types/utilTypes'; -export const transformQuery = async ({ query, executionId }) => { +export const transformQuery = async ({ query, executionId }: TransformQueryParams) => { const logger = loggerModule.child({ source: 'searchQueryValidator.js', module: 'utilValidation', @@ -11,7 +12,7 @@ export const transformQuery = async ({ query, executionId }) => { if (query.startsWith('https://open.spotify.com/')) { try { // regex to check for country-based Spotify url - const regex = new RegExp( + const regex: RegExp = new RegExp( 'https://open.spotify.com/((?:[a-z]{2,4}-[a-z]{2,4}/)|(?:[a-z]{2,4}/))(track|playlist)/([a-zA-Z0-9]+)' ); const isCountryBased = regex.test(query); @@ -19,9 +20,12 @@ export const transformQuery = async ({ query, executionId }) => { // if country-based, transform to normal Spotify url if (isCountryBased) { logger.debug(`Transforming country-based Spotify url to normal Spotify url from query '${query}'.`); - const type = query.match(regex)[2]; - const trackId = query.match(regex)[3]; - query = `https://open.spotify.com/${type}/${trackId}`; + const matches = query.match(regex); + if (matches) { + const type = matches[2]; + const trackId = matches[3]; + query = `https://open.spotify.com/${type}/${trackId}`; + } } } catch (error) { logger.error(error, 'Error while validating or transforming Spotify url.'); diff --git a/src/utils/validation/systemCommandValidator.ts b/src/utils/validation/systemCommandValidator.ts index 22d6e91..1d17e24 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/utils/validation/systemCommandValidator.ts @@ -1,22 +1,23 @@ import loggerModule from '../../services/logger'; import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { EmbedOptions, SystemOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const systemOptions = config.get('systemOptions'); +const systemOptions: SystemOptions = config.get('systemOptions'); import { EmbedBuilder } from 'discord.js'; +import { NotValidGuildIdParams } from '../../types/utilTypes'; -export const notValidGuildId = async ({ interaction, executionId }) => { +export const notValidGuildId = async ({ interaction, executionId }: NotValidGuildIdParams) => { const logger = loggerModule.child({ source: 'systemCommandValidator.js', module: 'utilValidation', name: 'notValidGuildId', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); - if (!systemOptions.systemGuildIds.includes(interaction.guildId)) { + if (interaction.guildId && !systemOptions.systemGuildIds.includes(interaction.guildId)) { await interaction.editReply({ embeds: [ new EmbedBuilder() diff --git a/src/utils/validation/voiceChannelValidator.ts b/src/utils/validation/voiceChannelValidator.ts index 264d79c..554fcb4 100644 --- a/src/utils/validation/voiceChannelValidator.ts +++ b/src/utils/validation/voiceChannelValidator.ts @@ -2,19 +2,20 @@ import { EmbedOptions } from '../../types/configTypes'; import loggerModule from '../../services/logger'; import config from 'config'; const embedOptions: EmbedOptions = config.get('embedOptions'); -import { EmbedBuilder } from 'discord.js'; +import { EmbedBuilder, GuildMember } from 'discord.js'; +import { NotInVoiceChannelParams, NotInSameVoiceChannelParams } from '../../types/utilTypes'; -export const notInVoiceChannel = async ({ interaction, executionId }) => { +export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoiceChannelParams) => { const logger = loggerModule.child({ source: 'voiceChannelValidator.js', module: 'validator', name: 'notInVoiceChannel', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); - if (!interaction.member.voice.channel) { + if (interaction.member instanceof GuildMember && !interaction.member.voice.channel) { await interaction.editReply({ embeds: [ new EmbedBuilder() @@ -32,14 +33,14 @@ export const notInVoiceChannel = async ({ interaction, executionId }) => { return false; }; -export const notInSameVoiceChannel = async ({ interaction, queue, executionId }) => { +export const notInSameVoiceChannel = async ({ interaction, queue, executionId }: NotInSameVoiceChannelParams) => { const logger = loggerModule.child({ source: 'voiceChannelValidator.js', module: 'utilValidation', name: 'notInSameVoiceChannel', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (!queue || !queue.dispatcher) { @@ -47,7 +48,10 @@ export const notInSameVoiceChannel = async ({ interaction, queue, executionId }) return false; } - if (interaction.member.voice.channel.id !== queue.dispatcher.channel.id) { + if ( + interaction.member instanceof GuildMember && + interaction.member.voice.channel?.id !== queue.dispatcher.channel.id + ) { await interaction.editReply({ embeds: [ new EmbedBuilder() From 39e818283d517e8b8caf9803fc997ca955ab626d Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 01:54:46 +0200 Subject: [PATCH 11/24] fix: more annotation for util functions --- src/types/utilTypes.ts | 23 +++++++++++++ src/utils/other/cookieParser.ts | 2 +- src/utils/other/postBotStats.ts | 45 +++++++++++++++----------- src/utils/other/startLoadTest.ts | 14 +++++--- src/utils/system/getUptimeFormatted.ts | 7 ++-- 5 files changed, 64 insertions(+), 27 deletions(-) diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts index e71613b..4f504b9 100644 --- a/src/types/utilTypes.ts +++ b/src/types/utilTypes.ts @@ -62,3 +62,26 @@ export interface CannotSendMessageInChannelParams { interaction: ChatInputCommandInteraction; executionId: string; } + +export interface GetUptimeFormattedParams { + executionId: string; +} + +export interface StartLoadTestParams { + client: ExtendedClient; + executionId: string; +} + +export interface PostBotStatsParams { + client: ExtendedClient; + executionId: string; +} + +export interface PostBotStatsSite { + enabled: boolean; + hostname: string; + path: string; + method: string; + body: object; + token: string; +} diff --git a/src/utils/other/cookieParser.ts b/src/utils/other/cookieParser.ts index 8948097..d795362 100644 --- a/src/utils/other/cookieParser.ts +++ b/src/utils/other/cookieParser.ts @@ -5,7 +5,7 @@ const cookies = require(path.resolve('./cookies.json')); try { const cookieString = cookies - .map(({ name, value }) => { + .map(({ name, value }: { name: string; value: string }) => { return `${name}=${value}`; }) .join('; '); diff --git a/src/utils/other/postBotStats.ts b/src/utils/other/postBotStats.ts index 1b41044..da788b4 100644 --- a/src/utils/other/postBotStats.ts +++ b/src/utils/other/postBotStats.ts @@ -1,17 +1,19 @@ import https from 'node:https'; import loggerModule from '../../services/logger'; +import { PostBotStatsParams, PostBotStatsSite } from '../../types/utilTypes'; +import { Collection, Guild } from 'discord.js'; -export const postBotStats = async ({ client, executionId }) => { +export const postBotStats = async ({ client, executionId }: PostBotStatsParams) => { const logger = loggerModule.child({ source: 'postBotStats.js', module: 'utilOther', name: 'postBotStats', executionId: executionId, - shardId: client.shard.ids[0] + shardId: client.shard?.ids[0] }); try { - if (client.shard.ids[0] !== 0) { + if (client.shard?.ids[0] !== 0) { return; } @@ -24,10 +26,11 @@ export const postBotStats = async ({ client, executionId }) => { await client.shard .fetchClientValues('guilds.cache') .then((results) => { - results.map((guildCache) => { + const guildCaches = results as Collection[]; + guildCaches.map((guildCache) => { if (guildCache) { - guildCount += guildCache.length; - memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0); + guildCount += guildCache.size; + memberCount += guildCache.reduce((acc, guild) => acc + guild.memberCount, 0); } }); @@ -38,7 +41,7 @@ export const postBotStats = async ({ client, executionId }) => { }); /* eslint-disable camelcase */ - const sites = [ + const sites: PostBotStatsSite[] = [ { enabled: false, hostname: 'top.gg', @@ -49,7 +52,7 @@ export const postBotStats = async ({ client, executionId }) => { shard_count: shardCount, server_count: guildCount }, - token: process.env.BOTLIST_TOP_GG_API_TOKEN + token: process.env.BOTLIST_TOP_GG_API_TOKEN ?? '' }, { enabled: false, @@ -61,7 +64,7 @@ export const postBotStats = async ({ client, executionId }) => { users: memberCount, guilds: guildCount }, - token: process.env.BOTLIST_DISCORD_BOT_LIST_COM_API_TOKEN + token: process.env.BOTLIST_DISCORD_BOT_LIST_COM_API_TOKEN ?? '' }, { enabled: false, @@ -71,7 +74,7 @@ export const postBotStats = async ({ client, executionId }) => { body: { server_count: guildCount }, - token: process.env.BOTLIST_DISCORDS_COM_API_TOKEN + token: process.env.BOTLIST_DISCORDS_COM_API_TOKEN ?? '' }, { enabled: false, @@ -83,7 +86,7 @@ export const postBotStats = async ({ client, executionId }) => { shardCount: shardCount, guildCount: guildCount }, - token: process.env.BOTLIST_DISCORD_BOTS_GG_API_TOKEN + token: process.env.BOTLIST_DISCORD_BOTS_GG_API_TOKEN ?? '' }, { enabled: false, @@ -94,7 +97,7 @@ export const postBotStats = async ({ client, executionId }) => { shard_count: shardCount, server_count: guildCount }, - token: process.env.BOTLIST_BOTLIST_ME_API_TOKEN + token: process.env.BOTLIST_BOTLIST_ME_API_TOKEN ?? '' }, { enabled: false, @@ -120,10 +123,10 @@ export const postBotStats = async ({ client, executionId }) => { logger.info(`Starting to post bot stats with guild count ${guildCount} and member count ${memberCount}...`); - const statusCodes = []; + const statusCodes: number[] = []; sites.map((site) => { - if (site.disabled) { + if (!site.enabled) { return; } @@ -140,11 +143,17 @@ export const postBotStats = async ({ client, executionId }) => { }; const request = https.request(options, (res) => { - res.statusCode === 200 - ? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`) - : logger.warn(`Request to ${site.hostname}: statusCode: ${res.statusCode}`); + if (typeof res.statusCode === 'number') { + res.statusCode === 200 + ? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`) + : logger.warn(`Request to ${site.hostname}: statusCode: ${res.statusCode}`); - statusCodes.push(res.statusCode); + statusCodes.push(res.statusCode); + } else { + logger.error( + `Request to ${site.hostname}: statusCode is undefined or not a number (${res.statusCode}).` + ); + } }); request.write(JSON.stringify(site.body)); diff --git a/src/utils/other/startLoadTest.ts b/src/utils/other/startLoadTest.ts index 191af1a..6029a77 100644 --- a/src/utils/other/startLoadTest.ts +++ b/src/utils/other/startLoadTest.ts @@ -1,14 +1,17 @@ import config from 'config'; import loggerModule from '../../services/logger'; -const loadTestOptions = config.get('loadTestOptions'); +import { LoadTestOptions } from '../../types/configTypes'; +import { Client } from 'discord.js'; +import { StartLoadTestParams } from '../../types/utilTypes'; +const loadTestOptions: LoadTestOptions = config.get('loadTestOptions'); -export const startLoadTest = async ({ client, executionId }) => { +export const startLoadTest = async ({ client, executionId }: StartLoadTestParams) => { const logger = loggerModule.child({ source: 'startLoadTest.js', module: 'utilOther', name: 'startLoadTest', executionId: executionId, - shardId: client.shard.ids[0] + shardId: client.shard?.ids[0] }); if (!loadTestOptions.enabled) { @@ -22,11 +25,12 @@ export const startLoadTest = async ({ client, executionId }) => { logger.info(`Starting load test in ${channelIds.length} specified channels.`); channelIds.forEach((each) => { - client.shard.broadcastEval( - async (shardClient, { channelId, track }) => { + client.shard?.broadcastEval( + async (shardClient: Client, { channelId, track }: { channelId: string; track: string }) => { const channel = shardClient.channels.cache.get(channelId); if (channel) { /* eslint-disable no-undef */ + // @ts-ignore await player.play(channel.id, track, { nodeOptions: { leaveOnEmpty: false, diff --git a/src/utils/system/getUptimeFormatted.ts b/src/utils/system/getUptimeFormatted.ts index f355ba3..bb6da95 100644 --- a/src/utils/system/getUptimeFormatted.ts +++ b/src/utils/system/getUptimeFormatted.ts @@ -1,6 +1,7 @@ import loggerModule from '../../services/logger'; +import { GetUptimeFormattedParams } from '../../types/utilTypes'; -export const getUptimeFormatted = async ({ executionId }) => { +export const getUptimeFormatted = async ({ executionId }: GetUptimeFormattedParams) => { const logger = loggerModule.child({ source: 'getUptimeFormatted.js', module: 'utilSystem', @@ -11,9 +12,9 @@ export const getUptimeFormatted = async ({ executionId }) => { try { let uptimeFormattedString = ''; - const uptimeInSeconds = process.uptime(); + const uptimeInSeconds = parseFloat(process.uptime().toFixed(0)); const uptimeDate = new Date(0); - uptimeDate.setSeconds(uptimeInSeconds.toFixed(0)); + uptimeDate.setSeconds(uptimeInSeconds); uptimeFormattedString = `${ uptimeDate.getUTCDate() - 1 }d ${uptimeDate.getUTCHours()}h ${uptimeDate.getUTCMinutes()}m ${uptimeDate.getUTCSeconds()}s`; From b118ebdfb0de07b6f2d0895fb022458eb6984034 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 02:46:50 +0200 Subject: [PATCH 12/24] fix: annotations for events --- src/commands/info/help.ts | 2 +- src/commands/player/filters.ts | 2 +- src/commands/player/loop.ts | 2 +- src/commands/player/nowplaying.ts | 2 +- src/commands/player/play.ts | 4 +- src/commands/player/queue.ts | 2 +- src/events/client/debug.ts | 2 +- src/events/client/disconnect.ts | 19 +- src/events/client/error.ts | 2 +- src/events/client/guildCreate.ts | 4 +- src/events/client/guildDelete.ts | 4 +- src/events/client/ready.ts | 25 +-- src/events/client/reconnecting.ts | 17 +- src/events/client/warn.ts | 2 +- src/events/interactions/interactionCreate.ts | 206 ++++++++++--------- src/events/player/generalDebug.ts | 2 +- src/events/player/generalError.ts | 23 ++- src/events/player/playerDebug.ts | 2 +- src/events/player/playerError.ts | 23 ++- src/events/player/playerSkip.ts | 22 +- src/events/player/playerStart.ts | 8 +- src/events/process/uncaughtException.ts | 2 +- src/events/process/unhandledRejection.ts | 2 +- src/services/logger.ts | 2 +- src/types/clientTypes.ts | 10 +- src/types/eventTypes.ts | 13 ++ 26 files changed, 231 insertions(+), 173 deletions(-) diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 327c1a4..2334f45 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -1,7 +1,7 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions = config.get('botOptions'); +const botOptions: BotOptions = config.get('botOptions'); import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; diff --git a/src/commands/player/filters.ts b/src/commands/player/filters.ts index 9047e09..ea981cf 100644 --- a/src/commands/player/filters.ts +++ b/src/commands/player/filters.ts @@ -1,7 +1,7 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const ffmpegFilterOptions = config.get('ffmpegFilterOptions'); +const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; import { diff --git a/src/commands/player/loop.ts b/src/commands/player/loop.ts index 4dce11f..181eec5 100644 --- a/src/commands/player/loop.ts +++ b/src/commands/player/loop.ts @@ -1,7 +1,7 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions = config.get('botOptions'); +const botOptions: BotOptions = config.get('botOptions'); import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; import { queueDoesNotExist } from '../../utils/validation/queueValidator'; import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; diff --git a/src/commands/player/nowplaying.ts b/src/commands/player/nowplaying.ts index d73beee..9a2923d 100644 --- a/src/commands/player/nowplaying.ts +++ b/src/commands/player/nowplaying.ts @@ -1,7 +1,7 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const playerOptions = config.get('playerOptions'); +const playerOptions: PlayerOptions = config.get('playerOptions'); import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; import { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder } from 'discord.js'; diff --git a/src/commands/player/play.ts b/src/commands/player/play.ts index 47d08f9..74180af 100644 --- a/src/commands/player/play.ts +++ b/src/commands/player/play.ts @@ -1,7 +1,7 @@ import config from 'config'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions = config.get('botOptions'); -const playerOptions = config.get('playerOptions'); +const botOptions: BotOptions = config.get('botOptions'); +const playerOptions: PlayerOptions = config.get('playerOptions'); import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; import { cannotJoinVoiceOrTalk } from '../../utils/validation/permissionValidator'; import { transformQuery } from '../../utils/validation/searchQueryValidator'; diff --git a/src/commands/player/queue.ts b/src/commands/player/queue.ts index 83da830..dd570a9 100644 --- a/src/commands/player/queue.ts +++ b/src/commands/player/queue.ts @@ -1,7 +1,7 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const playerOptions = config.get('playerOptions'); +const playerOptions: PlayerOptions = config.get('playerOptions'); import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; diff --git a/src/events/client/debug.ts b/src/events/client/debug.ts index 34a80d9..d3afd14 100644 --- a/src/events/client/debug.ts +++ b/src/events/client/debug.ts @@ -6,7 +6,7 @@ module.exports = { name: Events.Debug, isDebug: true, once: false, - execute: async (message) => { + execute: async (message: string) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'debug.js', diff --git a/src/events/client/disconnect.ts b/src/events/client/disconnect.ts index ffb9e4b..d125b2e 100644 --- a/src/events/client/disconnect.ts +++ b/src/events/client/disconnect.ts @@ -1,36 +1,39 @@ import { v4 as uuidv4 } from 'uuid'; import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { EmbedOptions, SystemOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const systemOptions = config.get('systemOptions'); -import { EmbedBuilder } from 'discord.js'; +const systemOptions: SystemOptions = config.get('systemOptions'); +import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; +import { ExtendedClient } from '../../types/clientTypes'; module.exports = { name: 'disconnect', isDebug: false, once: false, - execute: async (client) => { + execute: async (client: ExtendedClient) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'disconnect.js', module: 'event', name: 'clientDisconnect', executionId: executionId, - shardId: client.shard.ids[0] + shardId: client.shard?.ids[0] }); - logger.warn(`${client.user.tag} lost connection to Discord APIs. Disconnected.`); + logger.warn(`${client.user?.tag} lost connection to Discord APIs. Disconnected.`); // send message to system message channel for event if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) { - const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId); + const channel = (await client.channels.cache.get( + systemOptions.systemMessageChannelId + )) as BaseGuildTextChannel; if (channel) { await channel.send({ embeds: [ new EmbedBuilder() .setDescription( - `${embedOptions.icons.warning} **${client.user.tag}** is **\`disconnected\`**!` + + `${embedOptions.icons.warning} **${client.user?.tag}** is **\`disconnected\`**!` + `\n\n<@${systemOptions.systemUserId}>` ) .setColor(embedOptions.colors.warning) diff --git a/src/events/client/error.ts b/src/events/client/error.ts index cf1bfc1..bbf97f4 100644 --- a/src/events/client/error.ts +++ b/src/events/client/error.ts @@ -6,7 +6,7 @@ module.exports = { name: Events.Error, isDebug: false, once: false, - execute: async (error) => { + execute: async (error: Error) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'error.js', diff --git a/src/events/client/guildCreate.ts b/src/events/client/guildCreate.ts index 4e3c9c3..14d2836 100644 --- a/src/events/client/guildCreate.ts +++ b/src/events/client/guildCreate.ts @@ -1,4 +1,4 @@ -import { Events } from 'discord.js'; +import { Events, Guild } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; @@ -6,7 +6,7 @@ module.exports = { name: Events.GuildCreate, isDebug: false, once: false, - execute: async (guild) => { + execute: async (guild: Guild) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'guildCreate.js', diff --git a/src/events/client/guildDelete.ts b/src/events/client/guildDelete.ts index faf6b9a..c380f25 100644 --- a/src/events/client/guildDelete.ts +++ b/src/events/client/guildDelete.ts @@ -1,4 +1,4 @@ -import { Events } from 'discord.js'; +import { Events, Guild } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; @@ -6,7 +6,7 @@ module.exports = { name: Events.GuildDelete, isDebug: false, once: false, - execute: async (guild) => { + execute: async (guild: Guild) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'guildDelete.js', diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index a2c5998..76c17e7 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -1,42 +1,43 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { EmbedOptions, LoadTestOptions, SystemOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const systemOptions = config.get('systemOptions'); -const presenceStatusOptions = config.get('presenceStatusOptions'); -const loadTestOptions = config.get('loadTestOptions'); +const systemOptions: SystemOptions = config.get('systemOptions'); +const presenceStatusOptions: PresenceData = config.get('presenceStatusOptions'); +const loadTestOptions: LoadTestOptions = config.get('loadTestOptions'); import { postBotStats } from '../../utils/other/postBotStats'; import { startLoadTest } from '../../utils/other/startLoadTest'; -import { Events, EmbedBuilder } from 'discord.js'; +import { Events, EmbedBuilder, PresenceData, BaseGuildTextChannel } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; +import { ExtendedClient } from '../../types/clientTypes'; module.exports = { name: Events.ClientReady, isDebug: false, once: false, - execute: async (client) => { + execute: async (client: ExtendedClient) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'ready.js', module: 'event', name: 'clientReady', executionId: executionId, - shardId: client.shard.ids[0] + shardId: client.shard?.ids[0] }); - logger.debug('Client \'ready\' event received after \'allShardsReady\' event.'); - await client.user.setPresence(presenceStatusOptions); + logger.debug("Client 'ready' event received after 'allShardsReady' event."); + await client.user?.setPresence(presenceStatusOptions); if (loadTestOptions.enabled) { // Only call function from shard with id 0 // The function uses broadcastEval() to call itself on all shards - if (client.shard.ids[0] === 0) { + if (client.shard?.ids[0] === 0) { logger.info('Initiating load test for bot client.'); await startLoadTest({ client, executionId }); } } - const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId); + const channel = (await client.channels.cache.get(systemOptions.systemMessageChannelId)) as BaseGuildTextChannel; // Check if the channel exists in curent shard and send a message if (channel) { @@ -45,7 +46,7 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.success} All shards ready**\n**${client.user.tag}** is now **\`online\`**!` + `**${embedOptions.icons.success} All shards ready**\n**${client.user?.tag}** is now **\`online\`**!` ) .setColor(embedOptions.colors.success) ] diff --git a/src/events/client/reconnecting.ts b/src/events/client/reconnecting.ts index 1ec9797..3c7d798 100644 --- a/src/events/client/reconnecting.ts +++ b/src/events/client/reconnecting.ts @@ -1,23 +1,24 @@ import { v4 as uuidv4 } from 'uuid'; import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { EmbedOptions, SystemOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const systemOptions = config.get('systemOptions'); -import { EmbedBuilder } from 'discord.js'; +const systemOptions: SystemOptions = config.get('systemOptions'); +import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; +import { ExtendedClient } from '../../types/clientTypes'; module.exports = { name: 'reconnecting', isDebug: false, once: false, - execute: async (client) => { + execute: async (client: ExtendedClient) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'reconnecting.js', module: 'event', name: 'clientReconnecting', executionId: executionId, - shardId: client.shard.ids[0] + shardId: client.shard?.ids[0] }); logger.warn('Client is reconnecting to Discord APIs.'); @@ -25,13 +26,15 @@ module.exports = { // send message to system message channel for event if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) { if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) { - const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId); + const channel = (await client.channels.cache.get( + systemOptions.systemMessageChannelId + )) as BaseGuildTextChannel; if (channel) { await channel.send({ embeds: [ new EmbedBuilder() .setDescription( - `${embedOptions.icons.warning} **${client.user.tag}** is **\`reconnecting\`**!` + + `${embedOptions.icons.warning} **${client.user?.tag}** is **\`reconnecting\`**!` + `\n\n<@${systemOptions.systemUserId}>` ) .setColor(embedOptions.colors.warning) diff --git a/src/events/client/warn.ts b/src/events/client/warn.ts index 0390cb6..64fc42d 100644 --- a/src/events/client/warn.ts +++ b/src/events/client/warn.ts @@ -6,7 +6,7 @@ module.exports = { name: Events.Warn, isDebug: false, once: false, - execute: async (warning) => { + execute: async (warning: string) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'warn.js', diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index cb282bb..1327c79 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,125 +1,143 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { BotOptions, EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions = config.get('botOptions'); +const botOptions: BotOptions = config.get('botOptions'); import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator'; -import { Events, EmbedBuilder } from 'discord.js'; +import { Events, EmbedBuilder, Interaction, StringSelectMenuInteraction } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; +import { ExtendedClient, Command } from '../../types/clientTypes'; module.exports = { name: Events.InteractionCreate, isDebug: false, - execute: async (interaction, { client }) => { + execute: async (interaction: Interaction, { client }: { client: ExtendedClient }) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'interactionCreate.js', module: 'event', name: 'interactionCreate', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (interaction.isMessageComponent()) { - logger.debug( - `Message component interaction created for id ${interaction.customId}${ - interaction.values ? ' and values ' + interaction.values : '' - }.` - ); - return; - } - - const command = client.commands.get(interaction.commandName); - if (!command) { - logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); - return; - } - - if (interaction.isAutocomplete()) { - logger.debug('Autocomplete interaction created.'); - try { - await command.autocomplete({ interaction, executionId }); - } catch (error) { - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug( - 'Autocomplete failed to be responded to, unknown interaction or already acknowledged.' - ); - return; - } else { - logger.warn(error, 'Autocomplete failed to execute.'); - } - return; - } - } else if (interaction.isChatInputCommand()) { - logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); - try { - await interaction.deferReply(); - - if (await cannotSendMessageInChannel({ interaction, executionId })) { - return; - } - - const inputTime = new Date(); - - await command.execute({ interaction, client, executionId }); - - const outputTime = new Date(); - const executionTime = outputTime - inputTime; - - logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); - } catch (error) { - logger.warn( - error, - `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` + if (interaction instanceof StringSelectMenuInteraction) { + logger.debug( + `Message component interaction created for id ${interaction.customId}${ + interaction.values ? ' and values ' + interaction.values : '' + }.` ); + } - if ( - error.message === 'Unknown interaction' || - error.message === 'Interaction has already been acknowledged.' - ) { - logger.debug('Command failed to be responded to, unknown interaction or already acknowledged.'); + return; + } + + if (interaction.isChatInputCommand() || interaction.isAutocomplete()) { + const command = client.commands?.get(interaction.commandName) as Command; + + if (interaction.isChatInputCommand()) { + if (!command) { + logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`); return; - } else { - if (!interaction.deferred || !interaction.replied) { - logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); + } + logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`); + try { + await interaction.deferReply(); + + if (await cannotSendMessageInChannel({ interaction, executionId })) { return; } - if (interaction.replied) { - // If the interaction has already been replied to, most likely command executed successfully or error is already handled. - return; - } else if (interaction.deferred) { - logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); - await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); + const inputTime: number = new Date().getTime(); + + await command.execute({ interaction, client, executionId }); + + const outputTime: number = new Date().getTime(); + const executionTime: number = outputTime - inputTime; + + logger.info(`Command '${interaction}' executed in ${executionTime} ms.`); + } catch (error) { + if (error instanceof Error) { + logger.warn( + error, + `Command '${interaction}' throwed an unhandled error and might have failed to execute properly.` + ); + + if ( + error.message === 'Unknown interaction' || + error.message === 'Interaction has already been acknowledged.' + ) { + logger.debug( + 'Command failed to be responded to, unknown interaction or already acknowledged.' + ); + return; + } else { + if (!interaction.deferred || !interaction.replied) { + logger.warn('Interaction was not deferred or replied to, and an error was thrown.'); + return; + } + + if (interaction.replied) { + // If the interaction has already been replied to, most likely command executed successfully or error is already handled. + return; + } else if (interaction.deferred) { + logger.info('Interaction was deferred, editing reply and sending Uh-oh message.'); + await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } else { + logger.info( + 'Interaction was not deferred or replied, sending new reply with Uh-oh message.' + ); + await interaction.reply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } + } } else { - logger.info('Interaction was not deferred or replied, sending new reply with Uh-oh message.'); - await interaction.reply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); + throw error; + } + } + } else if (interaction.isAutocomplete()) { + logger.debug('Autocomplete interaction created.'); + try { + command?.autocomplete && (await command?.autocomplete({ interaction, executionId })); + } catch (error) { + if (error instanceof Error) { + if ( + error.message === 'Unknown interaction' || + error.message === 'Interaction has already been acknowledged.' + ) { + logger.debug( + 'Autocomplete failed to be responded to, unknown interaction or already acknowledged.' + ); + return; + } else { + logger.warn(error, 'Autocomplete failed to execute.'); + } + return; + } else { + throw error; } } } - } else { + logger.warn(interaction, 'Interaction created but was not a chat input or autocomplete interaction.'); } } diff --git a/src/events/player/generalDebug.ts b/src/events/player/generalDebug.ts index 6108593..10306dd 100644 --- a/src/events/player/generalDebug.ts +++ b/src/events/player/generalDebug.ts @@ -5,7 +5,7 @@ module.exports = { name: 'debug', isDebug: true, isPlayerEvent: false, - execute: async (message) => { + execute: async (message: string) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'generalDebug.js', diff --git a/src/events/player/generalError.ts b/src/events/player/generalError.ts index b9f247a..3ffaed6 100644 --- a/src/events/player/generalError.ts +++ b/src/events/player/generalError.ts @@ -1,31 +1,32 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions = config.get('botOptions'); -const systemOptions = config.get('systemOptions'); -import { EmbedBuilder } from 'discord.js'; +const botOptions: BotOptions = config.get('botOptions'); +const systemOptions: SystemOptions = config.get('systemOptions'); +import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; +import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; // Emitted when the player queue encounters error (general error with queue) module.exports = { name: 'error', isDebug: false, isPlayerEvent: true, - execute: async (queue, error) => { + execute: async (queue: ExtendedGuildQueuePlayerNode, error: Error) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'generalError.js', module: 'event', name: 'playerGeneralError', executionId: executionId, - shardId: queue.metadata.client.shard.ids[0], - guildId: queue.metadata.channel.guild.id + shardId: queue.metadata?.client.shard?.ids[0], + guildId: queue.metadata?.channel.guild.id }); - logger.error(error, 'player.events.on(\'error\'): Player queue encountered error event'); + logger.error(error, "player.events.on('error'): Player queue encountered error event"); - await queue.metadata.channel.send({ + await queue.metadata?.channel.send({ embeds: [ new EmbedBuilder() .setDescription( @@ -37,7 +38,9 @@ module.exports = { }); if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) { - const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId); + const channel = (await queue.metadata?.client.channels.cache.get( + systemOptions.systemMessageChannelId + )) as BaseGuildTextChannel; if (channel) { await channel.send({ embeds: [ diff --git a/src/events/player/playerDebug.ts b/src/events/player/playerDebug.ts index 8ee6a38..e30906d 100644 --- a/src/events/player/playerDebug.ts +++ b/src/events/player/playerDebug.ts @@ -5,7 +5,7 @@ module.exports = { name: 'error', isDebug: true, isPlayerEvent: true, - execute: async (message) => { + execute: async (message: string) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'playerDebug.js', diff --git a/src/events/player/playerError.ts b/src/events/player/playerError.ts index 75a9c86..d1ed1f3 100644 --- a/src/events/player/playerError.ts +++ b/src/events/player/playerError.ts @@ -1,31 +1,32 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions = config.get('botOptions'); -const systemOptions = config.get('systemOptions'); -import { EmbedBuilder } from 'discord.js'; +const botOptions: BotOptions = config.get('botOptions'); +const systemOptions: SystemOptions = config.get('systemOptions'); +import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; +import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; // Emitted when the player encounters an error while streaming audio track module.exports = { name: 'error', isDebug: false, isPlayerEvent: true, - execute: async (queue, error) => { + execute: async (queue: ExtendedGuildQueuePlayerNode, error: Error) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'playerError.js', module: 'event', name: 'playerError', executionId: executionId, - shardId: queue.metadata.client.shard.ids[0], - guildId: queue.metadata.channel.guild.id + shardId: queue.metadata?.client.shard?.ids[0], + guildId: queue.metadata?.channel.guild.id }); - logger.error(error, 'player.events.on(\'playerError\'): Player error while streaming track'); + logger.error(error, "player.events.on('playerError'): Player error while streaming track"); - await queue.metadata.channel.send({ + await queue.metadata?.channel.send({ embeds: [ new EmbedBuilder() .setDescription( @@ -37,7 +38,9 @@ module.exports = { }); if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) { - const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId); + const channel = (await queue.metadata?.client.channels.cache.get( + systemOptions.systemMessageChannelId + )) as BaseGuildTextChannel; if (channel) { await channel.send({ embeds: [ diff --git a/src/events/player/playerSkip.ts b/src/events/player/playerSkip.ts index 6baed0c..8213e58 100644 --- a/src/events/player/playerSkip.ts +++ b/src/events/player/playerSkip.ts @@ -1,31 +1,33 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions = config.get('botOptions'); -const systemOptions = config.get('systemOptions'); -import { EmbedBuilder } from 'discord.js'; +const botOptions: BotOptions = config.get('botOptions'); +const systemOptions: SystemOptions = config.get('systemOptions'); +import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; +import { Track } from 'discord-player'; +import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; // Emitted when the audio player fails to load the stream for a track module.exports = { name: 'playerSkip', isDebug: false, isPlayerEvent: true, - execute: async (queue, track) => { + execute: async (queue: ExtendedGuildQueuePlayerNode, track: Track) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'playerSkip.js', module: 'event', name: 'playerSkip', executionId: executionId, - shardId: queue.metadata.client.shard.ids[0], - guildId: queue.metadata.channel.guild.id + shardId: queue.metadata?.client.shard?.ids[0], + guildId: queue.metadata?.channel.guild.id }); logger.error(`player.events.on('playerSkip'): Failed to play '${track.url}'.`); - await queue.metadata.channel.send({ + await queue.metadata?.channel.send({ embeds: [ new EmbedBuilder() .setDescription( @@ -37,7 +39,9 @@ module.exports = { }); if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) { - const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId); + const channel = (await queue.metadata?.client.channels.cache.get( + systemOptions.systemMessageChannelId + )) as BaseGuildTextChannel; if (channel) { await channel.send({ embeds: [ diff --git a/src/events/player/playerStart.ts b/src/events/player/playerStart.ts index 06f24ca..3ce24a1 100644 --- a/src/events/player/playerStart.ts +++ b/src/events/player/playerStart.ts @@ -1,19 +1,21 @@ import { v4 as uuidv4 } from 'uuid'; import loggerModule from '../../services/logger'; +import { Track } from 'discord-player'; +import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; module.exports = { name: 'playerStart', isDebug: false, isPlayerEvent: true, - execute: async (queue, track) => { + execute: async (queue: ExtendedGuildQueuePlayerNode, track: Track) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'playerStart.js', module: 'event', name: 'playerStart', executionId: executionId, - shardId: queue.metadata.client.shard.ids[0], - guildId: queue.metadata.channel.guild.id + shardId: queue.metadata?.client.shard?.ids[0], + guildId: queue.metadata?.channel.guild.id }); logger.debug(`playerStart event: Started playing '${track.url}'.`); diff --git a/src/events/process/uncaughtException.ts b/src/events/process/uncaughtException.ts index 0041f59..b6822a1 100644 --- a/src/events/process/uncaughtException.ts +++ b/src/events/process/uncaughtException.ts @@ -4,7 +4,7 @@ import loggerModule from '../../services/logger'; module.exports = { name: 'uncaughtException', isDebug: false, - execute: async (error) => { + execute: async (error: Error) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'uncaughtException.js', diff --git a/src/events/process/unhandledRejection.ts b/src/events/process/unhandledRejection.ts index a33a34a..66634a7 100644 --- a/src/events/process/unhandledRejection.ts +++ b/src/events/process/unhandledRejection.ts @@ -4,7 +4,7 @@ import loggerModule from '../../services/logger'; module.exports = { name: 'unhandledRejection', isDebug: false, - execute: async (error) => { + execute: async (error: Error) => { const executionId = uuidv4(); const logger = loggerModule.child({ source: 'unhandledRejection.js', diff --git a/src/services/logger.ts b/src/services/logger.ts index 5bdf4a5..65f3e9e 100644 --- a/src/services/logger.ts +++ b/src/services/logger.ts @@ -2,7 +2,7 @@ import pino from 'pino'; import config from 'config'; // Retrieve logger options from config -const loggerOptions = config.get('loggerOptions'); +const loggerOptions: LoggerOptions = config.get('loggerOptions'); const targets = [ { diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index 74fb273..2429adb 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -2,7 +2,15 @@ import { Client, Collection } from 'discord.js'; type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; +export interface Command { + isNew: boolean; + isBeta: boolean; + data: object; + execute: (params: { interaction: object; client: ExtendedClient | undefined; executionId: string }) => void; + autocomplete?: (params: { interaction: object; executionId: string }) => void; +} + export interface ExtendedClient extends Client { registerClientCommands?: RegisterClientCommandsFunction; - commands?: Collection; + commands?: Collection; } diff --git a/src/types/eventTypes.ts b/src/types/eventTypes.ts index 38cdd28..5e48e38 100644 --- a/src/types/eventTypes.ts +++ b/src/types/eventTypes.ts @@ -1,3 +1,16 @@ +import { GuildQueuePlayerNode } from 'discord-player'; +import { ExtendedClient } from './clientTypes'; +import { BaseGuildTextChannel } from 'discord.js'; + export type ClientEventArguments = unknown[]; export type ProcessEventArguments = unknown[]; export type PlayerEventArguments = unknown[]; + +export interface ExtendedGuildQueuePlayerNode extends GuildQueuePlayerNode { + metadata: + | undefined + | { + client: ExtendedClient; + channel: BaseGuildTextChannel; + }; +} From 179f7ddbfd9d77cb32d8c5f362eecb34432a1bbd Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 02:52:41 +0200 Subject: [PATCH 13/24] fix: add annotations to command parameters --- src/commands/player/filters.ts | 3 ++- src/commands/player/leave.ts | 3 ++- src/commands/player/loop.ts | 3 ++- src/commands/player/lyrics.ts | 5 +++-- src/commands/player/nowplaying.ts | 3 ++- src/commands/player/pause.ts | 3 ++- src/commands/player/play.ts | 5 +++-- src/commands/player/queue.ts | 3 ++- src/commands/player/remove.ts | 3 ++- src/commands/player/seek.ts | 3 ++- src/commands/player/shuffle.ts | 3 ++- src/commands/player/skip.ts | 3 ++- src/commands/player/stop.ts | 3 ++- src/commands/player/volume.ts | 3 ++- src/commands/system/guilds.ts | 3 ++- src/commands/system/reload.ts | 3 ++- src/commands/system/shards.ts | 3 ++- src/commands/system/systemstatus.ts | 3 ++- src/types/commandTypes.ts | 14 ++++++++++++++ 19 files changed, 52 insertions(+), 20 deletions(-) create mode 100644 src/types/commandTypes.ts diff --git a/src/commands/player/filters.ts b/src/commands/player/filters.ts index ea981cf..4651dd0 100644 --- a/src/commands/player/filters.ts +++ b/src/commands/player/filters.ts @@ -14,6 +14,7 @@ import { } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -23,7 +24,7 @@ module.exports = { .setDescription('Toggle various audio filters during playback.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'filters.js', module: 'slashCommand', diff --git a/src/commands/player/leave.ts b/src/commands/player/leave.ts index cf88094..22d0159 100644 --- a/src/commands/player/leave.ts +++ b/src/commands/player/leave.ts @@ -5,6 +5,7 @@ import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -14,7 +15,7 @@ module.exports = { .setDescription('Clear the track queue and remove the bot from voice channel.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'leave.js', module: 'slashCommand', diff --git a/src/commands/player/loop.ts b/src/commands/player/loop.ts index 181eec5..a4f4461 100644 --- a/src/commands/player/loop.ts +++ b/src/commands/player/loop.ts @@ -7,6 +7,7 @@ import { queueDoesNotExist } from '../../utils/validation/queueValidator'; import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -28,7 +29,7 @@ module.exports = { { name: 'Disabled', value: '0' } ) ), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'loop.js', module: 'slashCommand', diff --git a/src/commands/player/lyrics.ts b/src/commands/player/lyrics.ts index 0f2130a..28e4db3 100644 --- a/src/commands/player/lyrics.ts +++ b/src/commands/player/lyrics.ts @@ -7,6 +7,7 @@ import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useMainPlayer, useQueue, QueryType } from 'discord-player'; import { lyricsExtractor } from '@discord-player/extractor'; import loggerModule from '../../services/logger'; +import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; const recentQueries = new Map(); @@ -33,7 +34,7 @@ module.exports = { .setMaxLength(500) .setAutocomplete(true) ), - autocomplete: async ({ interaction, executionId }) => { + autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild.shardId, @@ -93,7 +94,7 @@ module.exports = { logger.debug(`Responding to autocomplete with results for query: '${query}'.`); return interaction.respond(response); }, - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild.shardId, diff --git a/src/commands/player/nowplaying.ts b/src/commands/player/nowplaying.ts index 9a2923d..dee9a61 100644 --- a/src/commands/player/nowplaying.ts +++ b/src/commands/player/nowplaying.ts @@ -7,6 +7,7 @@ import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/q import { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -16,7 +17,7 @@ module.exports = { .setDescription('Show information about the track currently playing.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'nowplaying.js', module: 'slashCommand', diff --git a/src/commands/player/pause.ts b/src/commands/player/pause.ts index bd704d1..6bfe904 100644 --- a/src/commands/player/pause.ts +++ b/src/commands/player/pause.ts @@ -6,6 +6,7 @@ import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/q import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -15,7 +16,7 @@ module.exports = { .setDescription('Pause or resume the current track.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'pause.js', module: 'slashCommand', diff --git a/src/commands/player/play.ts b/src/commands/player/play.ts index 74180af..c1f5187 100644 --- a/src/commands/player/play.ts +++ b/src/commands/player/play.ts @@ -9,6 +9,7 @@ import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useMainPlayer, useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; +import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; const recentQueries = new Map(); @@ -35,7 +36,7 @@ module.exports = { .setMaxLength(500) .setAutocomplete(true) ), - autocomplete: async ({ interaction, executionId }) => { + autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild.shardId, @@ -87,7 +88,7 @@ module.exports = { logger.debug(`Responding to autocomplete with results for query: '${query}'.`); return interaction.respond(response); }, - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerTemplate.child({ executionId: executionId, shardId: interaction.guild.shardId, diff --git a/src/commands/player/queue.ts b/src/commands/player/queue.ts index dd570a9..6f92bcb 100644 --- a/src/commands/player/queue.ts +++ b/src/commands/player/queue.ts @@ -6,6 +6,7 @@ import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -16,7 +17,7 @@ module.exports = { .setDMPermission(false) .setNSFW(false) .addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'queue.js', module: 'slashCommand', diff --git a/src/commands/player/remove.ts b/src/commands/player/remove.ts index 05e9116..6d023cf 100644 --- a/src/commands/player/remove.ts +++ b/src/commands/player/remove.ts @@ -6,6 +6,7 @@ import { queueDoesNotExist } from '../../utils/validation/queueValidator'; import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -22,7 +23,7 @@ module.exports = { .setMinValue(1) .setRequired(true) ), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'remove.js', module: 'slashCommand', diff --git a/src/commands/player/seek.ts b/src/commands/player/seek.ts index ba06c88..3f059f6 100644 --- a/src/commands/player/seek.ts +++ b/src/commands/player/seek.ts @@ -6,6 +6,7 @@ import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/q import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -21,7 +22,7 @@ module.exports = { .setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.') .setRequired(true) ), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'seek.js', module: 'slashCommand', diff --git a/src/commands/player/shuffle.ts b/src/commands/player/shuffle.ts index 3ab5f23..07a906e 100644 --- a/src/commands/player/shuffle.ts +++ b/src/commands/player/shuffle.ts @@ -6,6 +6,7 @@ import { queueDoesNotExist, queueIsEmpty } from '../../utils/validation/queueVal import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -15,7 +16,7 @@ module.exports = { .setDescription('Shuffle tracks in the queue randomly.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'shuffle.js', module: 'slashCommand', diff --git a/src/commands/player/skip.ts b/src/commands/player/skip.ts index 8cc8e71..e2a4ba8 100644 --- a/src/commands/player/skip.ts +++ b/src/commands/player/skip.ts @@ -6,6 +6,7 @@ import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/q import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -18,7 +19,7 @@ module.exports = { .addNumberOption((option) => option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1) ), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'skip.js', module: 'slashCommand', diff --git a/src/commands/player/stop.ts b/src/commands/player/stop.ts index 3efed8f..29328dc 100644 --- a/src/commands/player/stop.ts +++ b/src/commands/player/stop.ts @@ -5,6 +5,7 @@ import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -14,7 +15,7 @@ module.exports = { .setDescription('Stop playing audio and clear the track queue.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'stop.js', module: 'slashCommand', diff --git a/src/commands/player/volume.ts b/src/commands/player/volume.ts index 2701c13..3834fa9 100644 --- a/src/commands/player/volume.ts +++ b/src/commands/player/volume.ts @@ -6,6 +6,7 @@ import { queueDoesNotExist } from '../../utils/validation/queueValidator'; import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isNew: false, @@ -22,7 +23,7 @@ module.exports = { .setMinValue(0) .setMaxValue(100) ), - execute: async ({ interaction, executionId }) => { + execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'volume.js', module: 'slashCommand', diff --git a/src/commands/system/guilds.ts b/src/commands/system/guilds.ts index 09b36aa..a468f5b 100644 --- a/src/commands/system/guilds.ts +++ b/src/commands/system/guilds.ts @@ -4,6 +4,7 @@ const embedOptions: EmbedOptions = config.get('embedOptions'); import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isSystemCommand: true, @@ -14,7 +15,7 @@ module.exports = { .setDescription('Show list of guilds where bot is added.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { + execute: async ({ interaction, client, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'guilds.js', module: 'slashCommand', diff --git a/src/commands/system/reload.ts b/src/commands/system/reload.ts index 3ece3e7..0de7fa3 100644 --- a/src/commands/system/reload.ts +++ b/src/commands/system/reload.ts @@ -4,6 +4,7 @@ const embedOptions: EmbedOptions = config.get('embedOptions'); import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isSystemCommand: true, @@ -14,7 +15,7 @@ module.exports = { .setDescription('Reload the bot commands.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { + execute: async ({ interaction, client, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'reload.js', module: 'slashCommand', diff --git a/src/commands/system/shards.ts b/src/commands/system/shards.ts index 67d3822..458d32d 100644 --- a/src/commands/system/shards.ts +++ b/src/commands/system/shards.ts @@ -4,6 +4,7 @@ const embedOptions: EmbedOptions = config.get('embedOptions'); import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; module.exports = { isSystemCommand: true, @@ -31,7 +32,7 @@ module.exports = { ) .addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)), - execute: async ({ interaction, client, executionId }) => { + execute: async ({ interaction, client, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'shards.js', module: 'slashCommand', diff --git a/src/commands/system/systemstatus.ts b/src/commands/system/systemstatus.ts index 81b7af5..ee60f42 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/commands/system/systemstatus.ts @@ -8,6 +8,7 @@ import { version, dependencies } from '../../../package.json'; import loggerModule from '../../services/logger'; import { EmbedOptions } from '../../types/configTypes'; +import { CommandParams } from '../../types/commandTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { @@ -19,7 +20,7 @@ module.exports = { .setDescription('Show the bot and system status.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { + execute: async ({ interaction, client, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'systemstatus.js', module: 'slashCommand', diff --git a/src/types/commandTypes.ts b/src/types/commandTypes.ts new file mode 100644 index 0000000..e17181d --- /dev/null +++ b/src/types/commandTypes.ts @@ -0,0 +1,14 @@ +import { ChatInputCommandInteraction, AutocompleteInteraction } from 'discord.js'; +import { ExtendedClient } from './clientTypes'; + +export interface CommandParams { + interaction: ChatInputCommandInteraction; + client: ExtendedClient | undefined; + executionId: string; +} + +export interface CommandAutocompleteParams { + interaction: AutocompleteInteraction; + client: ExtendedClient | undefined; + executionId: string; +} From 064db46f22bd705beea109ce3a11ab90d3f9627b Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 03:00:03 +0200 Subject: [PATCH 14/24] small fix --- src/events/interactions/interactionCreate.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index 1327c79..d326adc 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -137,7 +137,7 @@ module.exports = { } } } - + } else { logger.warn(interaction, 'Interaction created but was not a chat input or autocomplete interaction.'); } } From f4f418292a4e7fa002df3e79d6da647a3c36f901 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 12:25:41 +0200 Subject: [PATCH 15/24] fix: types for logger service --- src/services/logger.ts | 16 +++++++++------- src/types/serviceTypes.ts | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 7 deletions(-) create mode 100644 src/types/serviceTypes.ts diff --git a/src/services/logger.ts b/src/services/logger.ts index 65f3e9e..9e04f7c 100644 --- a/src/services/logger.ts +++ b/src/services/logger.ts @@ -1,10 +1,13 @@ import pino from 'pino'; import config from 'config'; +import { LoggerOptions } from '../types/configTypes'; +import { TargetOptions } from '../types/serviceTypes'; +import type { LokiOptions } from 'pino-loki'; // Retrieve logger options from config const loggerOptions: LoggerOptions = config.get('loggerOptions'); -const targets = [ +const targets: TargetOptions[] = [ { target: 'pino/file', level: loggerOptions.minimumLogLevel, @@ -17,7 +20,7 @@ const targets = [ }, { target: 'pino/file', - level: pino.levels.values.info, + level: pino.levels.values.info.toString(), options: { destination: './logs/app-info.log', mkdir: true, @@ -27,7 +30,7 @@ const targets = [ }, { target: 'pino/file', - level: pino.levels.values.error, + level: pino.levels.values.error.toString(), options: { destination: './logs/app-error.log', mkdir: true, @@ -46,11 +49,9 @@ const targets = [ // Check for Loki credentials and add Loki as a target if present if (process.env.LOKI_AUTH_PASSWORD && process.env.LOKI_AUTH_USERNAME) { - targets.push({ + const transport = pino.transport({ target: 'pino-loki', - level: loggerOptions.minimumLogLevel, options: { - sync: false, batching: false, interval: 5, host: process.env.LOKI_HOST || 'http://localhost:3100', @@ -60,6 +61,8 @@ if (process.env.LOKI_AUTH_PASSWORD && process.env.LOKI_AUTH_USERNAME) { } } }); + + targets.push(transport); } const transport = pino.transport({ targets }); @@ -77,4 +80,3 @@ const logLevelConfig = { const logger = pino(logLevelConfig, transport); export default logger; -module.exports = logger; diff --git a/src/types/serviceTypes.ts b/src/types/serviceTypes.ts new file mode 100644 index 0000000..1b449fe --- /dev/null +++ b/src/types/serviceTypes.ts @@ -0,0 +1,18 @@ +export type TargetOptions = { + target: string; + level: string; + options: { + destination?: string; + mkdir?: boolean; + sync?: boolean; + minLength?: number; + colorize?: boolean; + batching?: boolean; + interval?: number; + host?: string; + basicAuth?: { + username: string; + password: string; + }; + }; +}; From 0bdc5501bee6874ab9f77812a0235e414f30e0b3 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 13:28:29 +0200 Subject: [PATCH 16/24] fix: annotated system commands --- src/commands/player/filters.ts | 2 +- src/commands/player/nowplaying.ts | 14 ++++++------- src/commands/system/guilds.ts | 15 +++++++++----- src/commands/system/reload.ts | 22 ++++++++++++++------ src/commands/system/shards.ts | 31 ++++++++++++++++++++--------- src/commands/system/systemstatus.ts | 25 ++++++++++++++--------- src/types/clientTypes.ts | 10 +++++++--- src/types/commandTypes.ts | 12 +++++++++++ src/types/globalTypes.ts | 5 +++++ 9 files changed, 96 insertions(+), 40 deletions(-) create mode 100644 src/types/globalTypes.ts diff --git a/src/commands/player/filters.ts b/src/commands/player/filters.ts index 4651dd0..00aaa08 100644 --- a/src/commands/player/filters.ts +++ b/src/commands/player/filters.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { EmbedOptions, FFmpegFilterOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; diff --git a/src/commands/player/nowplaying.ts b/src/commands/player/nowplaying.ts index dee9a61..16a7cd0 100644 --- a/src/commands/player/nowplaying.ts +++ b/src/commands/player/nowplaying.ts @@ -138,8 +138,8 @@ module.exports = { queue.repeatMode === 0 ? '' : `**${ - queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop - } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.` + queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop + } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.` }` ) .addFields( @@ -170,7 +170,7 @@ module.exports = { components: [nowPlayingActionRow] }); - logger.debug(`User used command '${interaction.commandName}', finished sending response.`); + logger.debug('Finished sending response.'); const collectorFilter = (i) => i.user.id === interaction.user.id; try { @@ -249,10 +249,10 @@ module.exports = { queue.repeatMode === 0 ? '' : `\n\n**${ - queue.repeatMode === 3 - ? embedOptions.icons.autoplaying - : embedOptions.icons.looping - } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` + queue.repeatMode === 3 + ? embedOptions.icons.autoplaying + : embedOptions.icons.looping + } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` }` ) .setThumbnail(skippedTrack.thumbnail) diff --git a/src/commands/system/guilds.ts b/src/commands/system/guilds.ts index a468f5b..d9745a1 100644 --- a/src/commands/system/guilds.ts +++ b/src/commands/system/guilds.ts @@ -2,7 +2,7 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { SlashCommandBuilder, EmbedBuilder, Guild } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -21,17 +21,22 @@ module.exports = { module: 'slashCommand', name: '/guilds', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notValidGuildId({ interaction, executionId })) { return; } - let shardGuilds = []; + let shardGuilds: Guild[] = []; let totalGuildCount = 0; + if (!client || !client.shard) { + logger.error('Client is undefined or does not have shard property.'); + return; + } + logger.debug('Fetching guilds from all shards.'); await client.shard .broadcastEval((c) => { @@ -40,7 +45,7 @@ module.exports = { }); }) .then((guilds) => { - shardGuilds = guilds.flat(1); + shardGuilds = guilds.flat(1) as Guild[]; }); totalGuildCount = shardGuilds.length; diff --git a/src/commands/system/reload.ts b/src/commands/system/reload.ts index 0de7fa3..c89f4cf 100644 --- a/src/commands/system/reload.ts +++ b/src/commands/system/reload.ts @@ -2,9 +2,10 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { ExtendedClient } from '../../types/clientTypes'; module.exports = { isSystemCommand: true, @@ -21,19 +22,28 @@ module.exports = { module: 'slashCommand', name: '/reload', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notValidGuildId({ interaction, executionId })) { return; } + if (!client || !client.shard) { + logger.error('Client is undefined or does not have shard property.'); + return; + } + try { logger.debug('Reloading commands across all shards.'); await client.shard .broadcastEval( - async (shardClient, { executionId }) => { + async (shardClient: ExtendedClient, { executionId }) => { + if (!shardClient.registerClientCommands) { + return; + } + shardClient.registerClientCommands({ client: shardClient, executionId }); }, { context: { executionId: executionId } } @@ -58,12 +68,12 @@ module.exports = { }); } - const commands = client.commands.map((command) => { + const commands = client.commands?.map((command) => { const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : ''; return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`; }); - const embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands.join('\n'); + const embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands?.join('\n'); logger.debug('Responding with success embed.'); return await interaction.editReply({ diff --git a/src/commands/system/shards.ts b/src/commands/system/shards.ts index 458d32d..5434278 100644 --- a/src/commands/system/shards.ts +++ b/src/commands/system/shards.ts @@ -2,9 +2,10 @@ import config from 'config'; import { EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; +import { CommandParams, ShardInfo } from '../../types/commandTypes'; +import { ExtendedClient } from '../../types/clientTypes'; module.exports = { isSystemCommand: true, @@ -38,23 +39,35 @@ module.exports = { module: 'slashCommand', name: '/shards', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notValidGuildId({ interaction, executionId })) { return; } - let shardInfoList = []; + let shardInfoList: ShardInfo[] = []; + + if (!client || !client.shard) { + logger.error('Client is undefined or does not have shard property.'); + return; + } logger.debug('Fetching player statistics and client values from each shard.'); try { await client.shard - .broadcastEval((shardClient) => { + .broadcastEval((shardClient: ExtendedClient) => { + if (!shardClient.shard) { + return; + } + /* eslint-disable no-undef */ const playerStats = player.generateStatistics(); - const nodeProcessMemUsageInMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2); + const nodeProcessMemUsageInMb = parseFloat( + (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2) + ); + const shardInfo = { shardId: shardClient.shard.ids[0], memUsage: nodeProcessMemUsageInMb, @@ -70,7 +83,7 @@ module.exports = { return shardInfo; }) .then((results) => { - shardInfoList = results; + shardInfoList = results.filter(Boolean) as ShardInfo[]; switch (interaction.options.getString('sort')) { case 'memory': @@ -132,7 +145,7 @@ module.exports = { const evenShardIndexes = currentPageShards.filter((shard, index) => index % 2 === 0); const oddShardIndexes = currentPageShards.filter((shard, index) => index % 2 !== 0); - function shardInfoToString(shard) { + function shardInfoToString(shard: ShardInfo) { let string = ''; string += `**Shard ${shard.shardId}** - Guilds: ${shard.guildCount.toLocaleString( 'en-US' diff --git a/src/commands/system/systemstatus.ts b/src/commands/system/systemstatus.ts index ee60f42..4fb6370 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/commands/system/systemstatus.ts @@ -1,7 +1,7 @@ import config from 'config'; import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; -import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { SlashCommandBuilder, EmbedBuilder, Guild, Collection } from 'discord.js'; import osu from 'node-os-utils'; // @ts-ignore import { version, dependencies } from '../../../package.json'; @@ -26,8 +26,8 @@ module.exports = { module: 'slashCommand', name: '/systemstatus', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notValidGuildId({ interaction, executionId })) { @@ -59,15 +59,21 @@ module.exports = { const distubeYtdlVersion = dependencies['@distube/ytdl-core']; logger.debug('Fetching player statistics from all shards.'); + + if (!client || !client.shard) { + logger.error('Client is undefined or does not have shard property.'); + return; + } + await client.shard .broadcastEval(() => { /* eslint-disable no-undef */ return player.generateStatistics(); }) .then((results) => { - const queueCountList = []; - const trackCountList = []; - const listenerCountList = []; + const queueCountList: number[] = []; + const trackCountList: number[] = []; + const listenerCountList: number[] = []; results.map((result) => { queueCountList.push(result.queues.length); if (result.queues.length > 0) { @@ -89,10 +95,11 @@ module.exports = { await client.shard .fetchClientValues('guilds.cache') .then((results) => { - results.map((guildCache) => { + const guildCaches = results as Collection[]; + guildCaches.map((guildCache) => { if (guildCache) { - guildCount += guildCache.length; - memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0); + guildCount += guildCache.size; + memberCount += guildCache.reduce((acc, guild) => acc + guild.memberCount, 0); } }); logger.debug('Successfully fetched client values from shards.'); diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index 2429adb..9b38d2f 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -1,16 +1,20 @@ -import { Client, Collection } from 'discord.js'; +import { Client, Collection, SharedNameAndDescription } from 'discord.js'; type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; export interface Command { isNew: boolean; isBeta: boolean; - data: object; + data: { + name: string; + description: string; + options: SharedNameAndDescription[] + }; execute: (params: { interaction: object; client: ExtendedClient | undefined; executionId: string }) => void; autocomplete?: (params: { interaction: object; executionId: string }) => void; } export interface ExtendedClient extends Client { registerClientCommands?: RegisterClientCommandsFunction; - commands?: Collection; + commands?: Collection; } diff --git a/src/types/commandTypes.ts b/src/types/commandTypes.ts index e17181d..d7e5e41 100644 --- a/src/types/commandTypes.ts +++ b/src/types/commandTypes.ts @@ -12,3 +12,15 @@ export interface CommandAutocompleteParams { client: ExtendedClient | undefined; executionId: string; } + +export interface ShardInfo { + shardId: number; + memUsage: number; + guildCount: number; + guildMemberCount: number; + playerStatistics: { + activeVoiceConnections: number; + totalTracks: number; + totalListeners: number; + }; +} diff --git a/src/types/globalTypes.ts b/src/types/globalTypes.ts new file mode 100644 index 0000000..749c65f --- /dev/null +++ b/src/types/globalTypes.ts @@ -0,0 +1,5 @@ +import { Player } from 'discord-player'; + +declare global { + const player: Player; +} From 72e2b2aa138bf87b6a2e6614eca28b1044d4903d Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 13:43:27 +0200 Subject: [PATCH 17/24] chore: formatting and sorting --- src/bot.ts | 12 +++++---- src/commands/info/help.ts | 9 ++++--- src/commands/info/status.ts | 9 ++++--- src/commands/player/filters.ts | 27 ++++++++++--------- src/commands/player/leave.ts | 9 ++++--- src/commands/player/loop.ts | 13 ++++----- src/commands/player/lyrics.ts | 14 +++++----- src/commands/player/nowplaying.ts | 25 ++++++++--------- src/commands/player/pause.ts | 11 ++++---- src/commands/player/play.ts | 19 ++++++------- src/commands/player/queue.ts | 11 ++++---- src/commands/player/remove.ts | 15 ++++++----- src/commands/player/seek.ts | 11 ++++---- src/commands/player/shuffle.ts | 11 ++++---- src/commands/player/skip.ts | 11 ++++---- src/commands/player/stop.ts | 9 ++++--- src/commands/player/volume.ts | 11 ++++---- src/commands/system/guilds.ts | 9 ++++--- src/commands/system/reload.ts | 15 ++++++----- src/commands/system/shards.ts | 15 ++++++----- src/commands/system/systemstatus.ts | 15 ++++++----- src/events/client/debug.ts | 3 ++- src/events/client/disconnect.ts | 9 ++++--- src/events/client/error.ts | 3 ++- src/events/client/guildCreate.ts | 1 + src/events/client/guildDelete.ts | 1 + src/events/client/ready.ts | 15 ++++++----- src/events/client/reconnecting.ts | 9 ++++--- src/events/client/warn.ts | 3 ++- src/events/interactions/interactionCreate.ts | 13 ++++----- src/events/player/generalDebug.ts | 1 + src/events/player/generalError.ts | 11 ++++---- src/events/player/playerDebug.ts | 1 + src/events/player/playerError.ts | 11 ++++---- src/events/player/playerSkip.ts | 13 ++++----- src/events/player/playerStart.ts | 5 ++-- src/events/process/uncaughtException.ts | 1 + src/events/process/unhandledRejection.ts | 1 + src/index.ts | 14 +++++----- src/services/logger.ts | 4 ++- src/types/commandTypes.ts | 3 ++- src/types/configTypes.ts | 12 ++++----- src/types/eventTypes.ts | 3 ++- src/types/utilTypes.ts | 6 ++--- src/utils/deploySlashCommands.ts | 7 +++-- src/utils/factory/createClient.ts | 4 +-- src/utils/factory/createPlayer.ts | 1 + src/utils/other/cookieParser.ts | 3 ++- src/utils/other/postBotStats.ts | 3 ++- src/utils/other/startLoadTest.ts | 4 ++- src/utils/registerClientCommands.ts | 3 ++- src/utils/registerEventListeners.ts | 8 ++++-- src/utils/validation/permissionValidator.ts | 13 +++++---- src/utils/validation/queueValidator.ts | 11 +++++--- .../validation/systemCommandValidator.ts | 10 +++---- src/utils/validation/voiceChannelValidator.ts | 9 ++++--- 56 files changed, 283 insertions(+), 217 deletions(-) diff --git a/src/bot.ts b/src/bot.ts index acaf0f9..b5379c3 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -1,12 +1,14 @@ import 'dotenv/config'; -import { registerEventListeners } from './utils/registerEventListeners'; -import { registerClientCommands } from './utils/registerClientCommands'; -import { createClient } from './utils/factory/createClient'; -import { createPlayer } from './utils/factory/createPlayer'; + +import { Client } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; + import loggerModule from './services/logger'; import { ExtendedClient } from './types/clientTypes'; -import { Client } from 'discord.js'; +import { createClient } from './utils/factory/createClient'; +import { createPlayer } from './utils/factory/createPlayer'; +import { registerClientCommands } from './utils/registerClientCommands'; +import { registerEventListeners } from './utils/registerEventListeners'; const executionId = uuidv4(); const logger = loggerModule.child({ diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 2334f45..898617b 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -1,10 +1,11 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + +import loggerModule from '../../services/logger'; +import { BotOptions, EmbedOptions } from '../../types/configTypes'; + const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); -import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; - module.exports = { data: new SlashCommandBuilder() .setName('help') diff --git a/src/commands/info/status.ts b/src/commands/info/status.ts index b269fa8..cbc5fd8 100644 --- a/src/commands/info/status.ts +++ b/src/commands/info/status.ts @@ -1,13 +1,14 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import osu from 'node-os-utils'; + // @ts-ignore import { version } from '../../../package.json'; import loggerModule from '../../services/logger'; +import { EmbedOptions } from '../../types/configTypes'; +import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/filters.ts b/src/commands/player/filters.ts index 00aaa08..25c1948 100644 --- a/src/commands/player/filters.ts +++ b/src/commands/player/filters.ts @@ -1,21 +1,22 @@ import config from 'config'; -import { EmbedOptions, FFmpegFilterOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { - SlashCommandBuilder, - EmbedBuilder, - ActionRowBuilder, - StringSelectMenuBuilder, - StringSelectMenuOptionBuilder, - ButtonBuilder -} from 'discord.js'; import { useQueue } from 'discord-player'; +import { + ActionRowBuilder, + ButtonBuilder, + EmbedBuilder, + SlashCommandBuilder, + StringSelectMenuBuilder, + StringSelectMenuOptionBuilder +} from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions, FFmpegFilterOptions } from '../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/leave.ts b/src/commands/player/leave.ts index 22d0159..d019327 100644 --- a/src/commands/player/leave.ts +++ b/src/commands/player/leave.ts @@ -1,12 +1,13 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/loop.ts b/src/commands/player/loop.ts index a4f4461..623fcd4 100644 --- a/src/commands/player/loop.ts +++ b/src/commands/player/loop.ts @@ -1,14 +1,15 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const botOptions: BotOptions = config.get('botOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist } from '../../utils/validation/queueValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { BotOptions, EmbedOptions } from '../../types/configTypes'; +import { queueDoesNotExist } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const botOptions: BotOptions = config.get('botOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/lyrics.ts b/src/commands/player/lyrics.ts index 28e4db3..3986875 100644 --- a/src/commands/player/lyrics.ts +++ b/src/commands/player/lyrics.ts @@ -1,14 +1,16 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; -import { useMainPlayer, useQueue, QueryType } from 'discord-player'; +import { QueryType, useMainPlayer, useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import { lyricsExtractor } from '@discord-player/extractor'; + import loggerModule from '../../services/logger'; import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); const recentQueries = new Map(); const loggerTemplate = loggerModule.child({ diff --git a/src/commands/player/nowplaying.ts b/src/commands/player/nowplaying.ts index 16a7cd0..423f89b 100644 --- a/src/commands/player/nowplaying.ts +++ b/src/commands/player/nowplaying.ts @@ -1,14 +1,15 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const playerOptions: PlayerOptions = config.get('playerOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { ActionRowBuilder, ButtonBuilder, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions, PlayerOptions } from '../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const playerOptions: PlayerOptions = config.get('playerOptions'); module.exports = { isNew: false, isBeta: false, @@ -138,8 +139,8 @@ module.exports = { queue.repeatMode === 0 ? '' : `**${ - queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop - } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.` + queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop + } Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.` }` ) .addFields( @@ -249,10 +250,10 @@ module.exports = { queue.repeatMode === 0 ? '' : `\n\n**${ - queue.repeatMode === 3 - ? embedOptions.icons.autoplaying - : embedOptions.icons.looping - } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` + queue.repeatMode === 3 + ? embedOptions.icons.autoplaying + : embedOptions.icons.looping + } Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.` }` ) .setThumbnail(skippedTrack.thumbnail) diff --git a/src/commands/player/pause.ts b/src/commands/player/pause.ts index 6bfe904..9c92e9d 100644 --- a/src/commands/player/pause.ts +++ b/src/commands/player/pause.ts @@ -1,13 +1,14 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/play.ts b/src/commands/player/play.ts index c1f5187..14ebb14 100644 --- a/src/commands/player/play.ts +++ b/src/commands/player/play.ts @@ -1,16 +1,17 @@ import config from 'config'; +import { useMainPlayer, useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + +import loggerModule from '../../services/logger'; +import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; +import { BotOptions, EmbedOptions, PlayerOptions } from '../../types/configTypes'; +import { cannotJoinVoiceOrTalk } from '../../utils/validation/permissionValidator'; +import { transformQuery } from '../../utils/validation/searchQueryValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; + const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); const playerOptions: PlayerOptions = config.get('playerOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { cannotJoinVoiceOrTalk } from '../../utils/validation/permissionValidator'; -import { transformQuery } from '../../utils/validation/searchQueryValidator'; -import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; -import { useMainPlayer, useQueue } from 'discord-player'; -import loggerModule from '../../services/logger'; -import { EmbedOptions } from '../../types/configTypes'; -import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; - const recentQueries = new Map(); const loggerTemplate = loggerModule.child({ diff --git a/src/commands/player/queue.ts b/src/commands/player/queue.ts index 6f92bcb..deb58c0 100644 --- a/src/commands/player/queue.ts +++ b/src/commands/player/queue.ts @@ -1,13 +1,14 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const playerOptions: PlayerOptions = config.get('playerOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions, PlayerOptions } from '../../types/configTypes'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const playerOptions: PlayerOptions = config.get('playerOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/remove.ts b/src/commands/player/remove.ts index 6d023cf..324dc92 100644 --- a/src/commands/player/remove.ts +++ b/src/commands/player/remove.ts @@ -1,13 +1,14 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist } from '../../utils/validation/queueValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { queueDoesNotExist } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, @@ -83,7 +84,9 @@ module.exports = { iconURL: interaction.user.avatarURL() }) .setDescription( - `**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${removedTrack.raw.url ?? removedTrack.url})**` + `**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${ + removedTrack.raw.url ?? removedTrack.url + })**` ) .setThumbnail(removedTrack.thumbnail) .setColor(embedOptions.colors.success) diff --git a/src/commands/player/seek.ts b/src/commands/player/seek.ts index 3f059f6..88a0339 100644 --- a/src/commands/player/seek.ts +++ b/src/commands/player/seek.ts @@ -1,13 +1,14 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/shuffle.ts b/src/commands/player/shuffle.ts index 07a906e..990a3fe 100644 --- a/src/commands/player/shuffle.ts +++ b/src/commands/player/shuffle.ts @@ -1,13 +1,14 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist, queueIsEmpty } from '../../utils/validation/queueValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { queueDoesNotExist, queueIsEmpty } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/skip.ts b/src/commands/player/skip.ts index e2a4ba8..2942fb3 100644 --- a/src/commands/player/skip.ts +++ b/src/commands/player/skip.ts @@ -1,13 +1,14 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; -import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/stop.ts b/src/commands/player/stop.ts index 29328dc..4cb5d9d 100644 --- a/src/commands/player/stop.ts +++ b/src/commands/player/stop.ts @@ -1,12 +1,13 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/player/volume.ts b/src/commands/player/volume.ts index 3834fa9..7f0a673 100644 --- a/src/commands/player/volume.ts +++ b/src/commands/player/volume.ts @@ -1,13 +1,14 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notInVoiceChannel, notInSameVoiceChannel } from '../../utils/validation/voiceChannelValidator'; -import { queueDoesNotExist } from '../../utils/validation/queueValidator'; -import{ SlashCommandBuilder, EmbedBuilder } from 'discord.js'; import { useQueue } from 'discord-player'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { queueDoesNotExist } from '../../utils/validation/queueValidator'; +import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isNew: false, isBeta: false, diff --git a/src/commands/system/guilds.ts b/src/commands/system/guilds.ts index d9745a1..fc76acd 100644 --- a/src/commands/system/guilds.ts +++ b/src/commands/system/guilds.ts @@ -1,11 +1,12 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; -import { SlashCommandBuilder, EmbedBuilder, Guild } from 'discord.js'; +import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; + import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isSystemCommand: true, isNew: false, diff --git a/src/commands/system/reload.ts b/src/commands/system/reload.ts index c89f4cf..dc401ae 100644 --- a/src/commands/system/reload.ts +++ b/src/commands/system/reload.ts @@ -1,12 +1,13 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; -import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { ExtendedClient } from '../../types/clientTypes'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; +import { ExtendedClient } from '../../types/clientTypes'; +import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; + +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isSystemCommand: true, isNew: false, diff --git a/src/commands/system/shards.ts b/src/commands/system/shards.ts index 5434278..fa24251 100644 --- a/src/commands/system/shards.ts +++ b/src/commands/system/shards.ts @@ -1,12 +1,13 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; -import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CommandParams, ShardInfo } from '../../types/commandTypes'; -import { ExtendedClient } from '../../types/clientTypes'; +import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import loggerModule from '../../services/logger'; +import { ExtendedClient } from '../../types/clientTypes'; +import { CommandParams, ShardInfo } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; + +const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { isSystemCommand: true, isNew: false, diff --git a/src/commands/system/systemstatus.ts b/src/commands/system/systemstatus.ts index 4fb6370..ee32d6e 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/commands/system/systemstatus.ts @@ -1,14 +1,15 @@ import config from 'config'; -import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; -import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; -import { SlashCommandBuilder, EmbedBuilder, Guild, Collection } from 'discord.js'; +import { Collection, EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import osu from 'node-os-utils'; -// @ts-ignore -import { version, dependencies } from '../../../package.json'; -import loggerModule from '../../services/logger'; -import { EmbedOptions } from '../../types/configTypes'; +// @ts-ignore +import { dependencies, version } from '../../../package.json'; +import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; +import { EmbedOptions } from '../../types/configTypes'; +import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; +import { notValidGuildId } from '../../utils/validation/systemCommandValidator'; + const embedOptions: EmbedOptions = config.get('embedOptions'); module.exports = { diff --git a/src/events/client/debug.ts b/src/events/client/debug.ts index d3afd14..7647c64 100644 --- a/src/events/client/debug.ts +++ b/src/events/client/debug.ts @@ -1,5 +1,6 @@ -import { v4 as uuidv4 } from 'uuid'; import { Events } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/events/client/disconnect.ts b/src/events/client/disconnect.ts index d125b2e..58a4034 100644 --- a/src/events/client/disconnect.ts +++ b/src/events/client/disconnect.ts @@ -1,12 +1,13 @@ -import { v4 as uuidv4 } from 'uuid'; import config from 'config'; -import { EmbedOptions, SystemOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const systemOptions: SystemOptions = config.get('systemOptions'); import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; import { ExtendedClient } from '../../types/clientTypes'; +import { EmbedOptions, SystemOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const systemOptions: SystemOptions = config.get('systemOptions'); module.exports = { name: 'disconnect', isDebug: false, diff --git a/src/events/client/error.ts b/src/events/client/error.ts index bbf97f4..9b8ffc5 100644 --- a/src/events/client/error.ts +++ b/src/events/client/error.ts @@ -1,5 +1,6 @@ -import { v4 as uuidv4 } from 'uuid'; import { Events } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/events/client/guildCreate.ts b/src/events/client/guildCreate.ts index 14d2836..0bbf035 100644 --- a/src/events/client/guildCreate.ts +++ b/src/events/client/guildCreate.ts @@ -1,5 +1,6 @@ import { Events, Guild } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/events/client/guildDelete.ts b/src/events/client/guildDelete.ts index c380f25..3a23c55 100644 --- a/src/events/client/guildDelete.ts +++ b/src/events/client/guildDelete.ts @@ -1,5 +1,6 @@ import { Events, Guild } from 'discord.js'; import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/events/client/ready.ts b/src/events/client/ready.ts index 76c17e7..9b15bd3 100644 --- a/src/events/client/ready.ts +++ b/src/events/client/ready.ts @@ -1,16 +1,17 @@ import config from 'config'; +import { BaseGuildTextChannel, EmbedBuilder, Events, PresenceData } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + +import loggerModule from '../../services/logger'; +import { ExtendedClient } from '../../types/clientTypes'; import { EmbedOptions, LoadTestOptions, SystemOptions } from '../../types/configTypes'; +import { postBotStats } from '../../utils/other/postBotStats'; +import { startLoadTest } from '../../utils/other/startLoadTest'; + const embedOptions: EmbedOptions = config.get('embedOptions'); const systemOptions: SystemOptions = config.get('systemOptions'); const presenceStatusOptions: PresenceData = config.get('presenceStatusOptions'); const loadTestOptions: LoadTestOptions = config.get('loadTestOptions'); -import { postBotStats } from '../../utils/other/postBotStats'; -import { startLoadTest } from '../../utils/other/startLoadTest'; -import { Events, EmbedBuilder, PresenceData, BaseGuildTextChannel } from 'discord.js'; -import { v4 as uuidv4 } from 'uuid'; -import loggerModule from '../../services/logger'; -import { ExtendedClient } from '../../types/clientTypes'; - module.exports = { name: Events.ClientReady, isDebug: false, diff --git a/src/events/client/reconnecting.ts b/src/events/client/reconnecting.ts index 3c7d798..8a473dc 100644 --- a/src/events/client/reconnecting.ts +++ b/src/events/client/reconnecting.ts @@ -1,12 +1,13 @@ -import { v4 as uuidv4 } from 'uuid'; import config from 'config'; -import { EmbedOptions, SystemOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const systemOptions: SystemOptions = config.get('systemOptions'); import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; import { ExtendedClient } from '../../types/clientTypes'; +import { EmbedOptions, SystemOptions } from '../../types/configTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const systemOptions: SystemOptions = config.get('systemOptions'); module.exports = { name: 'reconnecting', isDebug: false, diff --git a/src/events/client/warn.ts b/src/events/client/warn.ts index 64fc42d..44b847f 100644 --- a/src/events/client/warn.ts +++ b/src/events/client/warn.ts @@ -1,5 +1,6 @@ -import { v4 as uuidv4 } from 'uuid'; import { Events } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/events/interactions/interactionCreate.ts b/src/events/interactions/interactionCreate.ts index d326adc..d313058 100644 --- a/src/events/interactions/interactionCreate.ts +++ b/src/events/interactions/interactionCreate.ts @@ -1,13 +1,14 @@ import config from 'config'; +import { EmbedBuilder, Events, Interaction, StringSelectMenuInteraction } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + +import loggerModule from '../../services/logger'; +import { Command, ExtendedClient } from '../../types/clientTypes'; import { BotOptions, EmbedOptions } from '../../types/configTypes'; +import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator'; + const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); -import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator'; -import { Events, EmbedBuilder, Interaction, StringSelectMenuInteraction } from 'discord.js'; -import { v4 as uuidv4 } from 'uuid'; -import loggerModule from '../../services/logger'; -import { ExtendedClient, Command } from '../../types/clientTypes'; - module.exports = { name: Events.InteractionCreate, isDebug: false, diff --git a/src/events/player/generalDebug.ts b/src/events/player/generalDebug.ts index 10306dd..b085bf5 100644 --- a/src/events/player/generalDebug.ts +++ b/src/events/player/generalDebug.ts @@ -1,4 +1,5 @@ import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/events/player/generalError.ts b/src/events/player/generalError.ts index 3ffaed6..16fa9e7 100644 --- a/src/events/player/generalError.ts +++ b/src/events/player/generalError.ts @@ -1,13 +1,14 @@ import config from 'config'; +import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + +import loggerModule from '../../services/logger'; import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; +import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; + const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); const systemOptions: SystemOptions = config.get('systemOptions'); -import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; -import { v4 as uuidv4 } from 'uuid'; -import loggerModule from '../../services/logger'; -import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; - // Emitted when the player queue encounters error (general error with queue) module.exports = { name: 'error', diff --git a/src/events/player/playerDebug.ts b/src/events/player/playerDebug.ts index e30906d..7a5b707 100644 --- a/src/events/player/playerDebug.ts +++ b/src/events/player/playerDebug.ts @@ -1,4 +1,5 @@ import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/events/player/playerError.ts b/src/events/player/playerError.ts index d1ed1f3..b3da6c6 100644 --- a/src/events/player/playerError.ts +++ b/src/events/player/playerError.ts @@ -1,13 +1,14 @@ import config from 'config'; +import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + +import loggerModule from '../../services/logger'; import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; +import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; + const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); const systemOptions: SystemOptions = config.get('systemOptions'); -import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; -import { v4 as uuidv4 } from 'uuid'; -import loggerModule from '../../services/logger'; -import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; - // Emitted when the player encounters an error while streaming audio track module.exports = { name: 'error', diff --git a/src/events/player/playerSkip.ts b/src/events/player/playerSkip.ts index 8213e58..1237b72 100644 --- a/src/events/player/playerSkip.ts +++ b/src/events/player/playerSkip.ts @@ -1,14 +1,15 @@ import config from 'config'; +import { Track } from 'discord-player'; +import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + +import loggerModule from '../../services/logger'; import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes'; +import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; + const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); const systemOptions: SystemOptions = config.get('systemOptions'); -import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js'; -import { v4 as uuidv4 } from 'uuid'; -import loggerModule from '../../services/logger'; -import { Track } from 'discord-player'; -import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; - // Emitted when the audio player fails to load the stream for a track module.exports = { name: 'playerSkip', diff --git a/src/events/player/playerStart.ts b/src/events/player/playerStart.ts index 3ce24a1..7ee2e55 100644 --- a/src/events/player/playerStart.ts +++ b/src/events/player/playerStart.ts @@ -1,6 +1,7 @@ -import { v4 as uuidv4 } from 'uuid'; -import loggerModule from '../../services/logger'; import { Track } from 'discord-player'; +import { v4 as uuidv4 } from 'uuid'; + +import loggerModule from '../../services/logger'; import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes'; module.exports = { diff --git a/src/events/process/uncaughtException.ts b/src/events/process/uncaughtException.ts index b6822a1..3b45b52 100644 --- a/src/events/process/uncaughtException.ts +++ b/src/events/process/uncaughtException.ts @@ -1,4 +1,5 @@ import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/events/process/unhandledRejection.ts b/src/events/process/unhandledRejection.ts index 66634a7..6813b64 100644 --- a/src/events/process/unhandledRejection.ts +++ b/src/events/process/unhandledRejection.ts @@ -1,4 +1,5 @@ import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../../services/logger'; module.exports = { diff --git a/src/index.ts b/src/index.ts index 661ed07..8cba544 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,13 @@ import 'dotenv/config'; -import config from 'config'; -import { Client, Shard } from 'discord.js'; -import { ShardingManager, ShardEvents } from 'discord.js'; -import { v4 as uuidv4 } from 'uuid'; -import loggerModule from './services/logger'; -const shardingOptions: object = config.get('shardingOptions'); +import config from 'config'; +import { Client, Shard, ShardEvents, ShardingManager } from 'discord.js'; +import { v4 as uuidv4 } from 'uuid'; + +import loggerModule from './services/logger'; +import { ShardingOptions } from './types/configTypes'; + +const shardingOptions: ShardingOptions = config.get('shardingOptions'); const manager = new ShardingManager('./dist/bot.js', { token: process.env.DISCORD_BOT_TOKEN, diff --git a/src/services/logger.ts b/src/services/logger.ts index 9e04f7c..62bc8ad 100644 --- a/src/services/logger.ts +++ b/src/services/logger.ts @@ -1,7 +1,9 @@ -import pino from 'pino'; import config from 'config'; +import pino from 'pino'; + import { LoggerOptions } from '../types/configTypes'; import { TargetOptions } from '../types/serviceTypes'; + import type { LokiOptions } from 'pino-loki'; // Retrieve logger options from config diff --git a/src/types/commandTypes.ts b/src/types/commandTypes.ts index d7e5e41..c122b7d 100644 --- a/src/types/commandTypes.ts +++ b/src/types/commandTypes.ts @@ -1,4 +1,5 @@ -import { ChatInputCommandInteraction, AutocompleteInteraction } from 'discord.js'; +import { AutocompleteInteraction, ChatInputCommandInteraction } from 'discord.js'; + import { ExtendedClient } from './clientTypes'; export interface CommandParams { diff --git a/src/types/configTypes.ts b/src/types/configTypes.ts index ce346bd..f5c18fc 100644 --- a/src/types/configTypes.ts +++ b/src/types/configTypes.ts @@ -1,16 +1,14 @@ -import { ActivityType, PresenceUpdateStatus, ColorResolvable } from 'discord.js'; +import { + ActivityType, ColorResolvable, PresenceUpdateStatus, ShardingManagerOptions +} from 'discord.js'; + export interface BotOptions { name: string; botInviteUrl: string; serverInviteUrl: string; } -export interface ShardingOptions { - totalShards: string; - shardList: string; - mode: string; - respawn: boolean; -} +export interface ShardingOptions extends ShardingManagerOptions {} export interface LoggerOptions { minimumLogLevel: string; diff --git a/src/types/eventTypes.ts b/src/types/eventTypes.ts index 5e48e38..ea7580c 100644 --- a/src/types/eventTypes.ts +++ b/src/types/eventTypes.ts @@ -1,7 +1,8 @@ import { GuildQueuePlayerNode } from 'discord-player'; -import { ExtendedClient } from './clientTypes'; import { BaseGuildTextChannel } from 'discord.js'; +import { ExtendedClient } from './clientTypes'; + export type ClientEventArguments = unknown[]; export type ProcessEventArguments = unknown[]; export type PlayerEventArguments = unknown[]; diff --git a/src/types/utilTypes.ts b/src/types/utilTypes.ts index 4f504b9..812a1c0 100644 --- a/src/types/utilTypes.ts +++ b/src/types/utilTypes.ts @@ -1,7 +1,7 @@ -import { Player } from 'discord-player'; -import { ExtendedClient } from './clientTypes'; +import { GuildQueue, Player } from 'discord-player'; import { ChatInputCommandInteraction } from 'discord.js'; -import { GuildQueue } from 'discord-player'; + +import { ExtendedClient } from './clientTypes'; export interface RegisterEventListenersParams { client: ExtendedClient; diff --git a/src/utils/deploySlashCommands.ts b/src/utils/deploySlashCommands.ts index f09d19d..4e4c839 100644 --- a/src/utils/deploySlashCommands.ts +++ b/src/utils/deploySlashCommands.ts @@ -1,11 +1,14 @@ import 'dotenv/config'; + +import config from 'config'; +import { REST, RouteLike, Routes, SlashCommandBuilder } from 'discord.js'; import fs from 'node:fs'; import path from 'node:path'; -import { REST, RouteLike, Routes, SlashCommandBuilder } from 'discord.js'; -import config from 'config'; import { v4 as uuidv4 } from 'uuid'; + import loggerModule from '../services/logger'; import { SystemOptions } from '../types/configTypes'; + const systemOptions: SystemOptions = config.get('systemOptions'); const executionId = uuidv4(); diff --git a/src/utils/factory/createClient.ts b/src/utils/factory/createClient.ts index 29596a5..4c22aca 100644 --- a/src/utils/factory/createClient.ts +++ b/src/utils/factory/createClient.ts @@ -1,6 +1,6 @@ -import Discord from 'discord.js'; +import Discord, { Client } from 'discord.js'; + import loggerModule from '../../services/logger'; -import { Client } from 'discord.js'; export const createClient = async ({ executionId }: { executionId: string }) => { const logger = loggerModule.child({ diff --git a/src/utils/factory/createPlayer.ts b/src/utils/factory/createPlayer.ts index 314c77d..b3eee1b 100644 --- a/src/utils/factory/createPlayer.ts +++ b/src/utils/factory/createPlayer.ts @@ -1,4 +1,5 @@ import { Player } from 'discord-player'; + import loggerModule from '../../services/logger'; import { CreatePlayerParams } from '../../types/playerTypes'; diff --git a/src/utils/other/cookieParser.ts b/src/utils/other/cookieParser.ts index d795362..34021fd 100644 --- a/src/utils/other/cookieParser.ts +++ b/src/utils/other/cookieParser.ts @@ -1,5 +1,6 @@ -import path from 'node:path'; import fs from 'node:fs'; +import path from 'node:path'; + /* eslint-disable @typescript-eslint/no-var-requires */ const cookies = require(path.resolve('./cookies.json')); diff --git a/src/utils/other/postBotStats.ts b/src/utils/other/postBotStats.ts index da788b4..e85aaa5 100644 --- a/src/utils/other/postBotStats.ts +++ b/src/utils/other/postBotStats.ts @@ -1,7 +1,8 @@ +import { Collection, Guild } from 'discord.js'; import https from 'node:https'; + import loggerModule from '../../services/logger'; import { PostBotStatsParams, PostBotStatsSite } from '../../types/utilTypes'; -import { Collection, Guild } from 'discord.js'; export const postBotStats = async ({ client, executionId }: PostBotStatsParams) => { const logger = loggerModule.child({ diff --git a/src/utils/other/startLoadTest.ts b/src/utils/other/startLoadTest.ts index 6029a77..a29ef40 100644 --- a/src/utils/other/startLoadTest.ts +++ b/src/utils/other/startLoadTest.ts @@ -1,8 +1,10 @@ import config from 'config'; +import { Client } from 'discord.js'; + import loggerModule from '../../services/logger'; import { LoadTestOptions } from '../../types/configTypes'; -import { Client } from 'discord.js'; import { StartLoadTestParams } from '../../types/utilTypes'; + const loadTestOptions: LoadTestOptions = config.get('loadTestOptions'); export const startLoadTest = async ({ client, executionId }: StartLoadTestParams) => { diff --git a/src/utils/registerClientCommands.ts b/src/utils/registerClientCommands.ts index 1542e0b..6a4b664 100644 --- a/src/utils/registerClientCommands.ts +++ b/src/utils/registerClientCommands.ts @@ -1,6 +1,7 @@ +import { Collection } from 'discord.js'; import fs from 'node:fs'; import path from 'node:path'; -import { Collection } from 'discord.js'; + import loggerModule from '../services/logger'; import { RegisterClientCommandsParams } from '../types/utilTypes'; diff --git a/src/utils/registerEventListeners.ts b/src/utils/registerEventListeners.ts index 62eb477..f0b90c8 100644 --- a/src/utils/registerEventListeners.ts +++ b/src/utils/registerEventListeners.ts @@ -1,10 +1,14 @@ +import config from 'config'; import fs from 'node:fs'; import path from 'node:path'; -import config from 'config'; + import loggerModule from '../services/logger'; import { LoggerOptions } from '../types/configTypes'; +import { + ClientEventArguments, PlayerEventArguments, ProcessEventArguments +} from '../types/eventTypes'; import { RegisterEventListenersParams } from '../types/utilTypes'; -import { ClientEventArguments, PlayerEventArguments, ProcessEventArguments } from '../types/eventTypes'; + const loggerOptions: LoggerOptions = config.get('loggerOptions'); export const registerEventListeners = ({ client, player, executionId }: RegisterEventListenersParams) => { diff --git a/src/utils/validation/permissionValidator.ts b/src/utils/validation/permissionValidator.ts index 23cec3a..ff60aa1 100644 --- a/src/utils/validation/permissionValidator.ts +++ b/src/utils/validation/permissionValidator.ts @@ -1,10 +1,13 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -import { EmbedBuilder, GuildMember, VoiceChannel, TextChannel } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams } from '../../types/utilTypes'; +import { EmbedBuilder, GuildMember, TextChannel, VoiceChannel } from 'discord.js'; +import loggerModule from '../../services/logger'; +import { EmbedOptions } from '../../types/configTypes'; +import { + CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams +} from '../../types/utilTypes'; + +const embedOptions: EmbedOptions = config.get('embedOptions'); export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: CannotJoinVoiceOrTalkParams) => { const logger = loggerModule.child({ source: 'permissionValidator.js', diff --git a/src/utils/validation/queueValidator.ts b/src/utils/validation/queueValidator.ts index 08935d6..e762d7a 100644 --- a/src/utils/validation/queueValidator.ts +++ b/src/utils/validation/queueValidator.ts @@ -1,10 +1,13 @@ import config from 'config'; -import { EmbedOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); import { EmbedBuilder } from 'discord.js'; -import loggerModule from '../../services/logger'; -import { QueueDoesNotExistParams, QueueNoCurrentTrackParams, QueueIsEmptyParams } from '../../types/utilTypes'; +import loggerModule from '../../services/logger'; +import { EmbedOptions } from '../../types/configTypes'; +import { + QueueDoesNotExistParams, QueueIsEmptyParams, QueueNoCurrentTrackParams +} from '../../types/utilTypes'; + +const embedOptions: EmbedOptions = config.get('embedOptions'); export const queueDoesNotExist = async ({ interaction, queue, executionId }: QueueDoesNotExistParams) => { const logger = loggerModule.child({ source: 'queueValidator.js', diff --git a/src/utils/validation/systemCommandValidator.ts b/src/utils/validation/systemCommandValidator.ts index 1d17e24..d659b7b 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/utils/validation/systemCommandValidator.ts @@ -1,12 +1,12 @@ -import loggerModule from '../../services/logger'; - import config from 'config'; -import { EmbedOptions, SystemOptions } from '../../types/configTypes'; -const embedOptions: EmbedOptions = config.get('embedOptions'); -const systemOptions: SystemOptions = config.get('systemOptions'); import { EmbedBuilder } from 'discord.js'; + +import loggerModule from '../../services/logger'; +import { EmbedOptions, SystemOptions } from '../../types/configTypes'; import { NotValidGuildIdParams } from '../../types/utilTypes'; +const embedOptions: EmbedOptions = config.get('embedOptions'); +const systemOptions: SystemOptions = config.get('systemOptions'); export const notValidGuildId = async ({ interaction, executionId }: NotValidGuildIdParams) => { const logger = loggerModule.child({ source: 'systemCommandValidator.js', diff --git a/src/utils/validation/voiceChannelValidator.ts b/src/utils/validation/voiceChannelValidator.ts index 554fcb4..8bb3cf2 100644 --- a/src/utils/validation/voiceChannelValidator.ts +++ b/src/utils/validation/voiceChannelValidator.ts @@ -1,10 +1,11 @@ -import { EmbedOptions } from '../../types/configTypes'; -import loggerModule from '../../services/logger'; import config from 'config'; -const embedOptions: EmbedOptions = config.get('embedOptions'); import { EmbedBuilder, GuildMember } from 'discord.js'; -import { NotInVoiceChannelParams, NotInSameVoiceChannelParams } from '../../types/utilTypes'; +import loggerModule from '../../services/logger'; +import { EmbedOptions } from '../../types/configTypes'; +import { NotInSameVoiceChannelParams, NotInVoiceChannelParams } from '../../types/utilTypes'; + +const embedOptions: EmbedOptions = config.get('embedOptions'); export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoiceChannelParams) => { const logger = loggerModule.child({ source: 'voiceChannelValidator.js', From e9ed2eb0b8a10ed0467d6ed9ecd28140a234a9b1 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 13:54:19 +0200 Subject: [PATCH 18/24] fix: annotate volume command --- src/commands/player/volume.ts | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/commands/player/volume.ts b/src/commands/player/volume.ts index 7f0a673..4849c4c 100644 --- a/src/commands/player/volume.ts +++ b/src/commands/player/volume.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -30,15 +30,19 @@ module.exports = { module: 'slashCommand', name: '/volume', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + if (!interaction.guild) { + return; + } + + const queue: NodeResolvable = useQueue(interaction.guild.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -84,14 +88,22 @@ module.exports = { queue.node.setVolume(volume); logger.debug(`Set volume to ${volume}%.`); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + if (volume === 0) { logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to \`${volume}%\`.` @@ -106,8 +118,8 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to \`${volume}%\`.` From ef6f7bef807a92ef7b4398b79ab70bc730a25a7a Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 13:54:34 +0200 Subject: [PATCH 19/24] set command param type --- src/commands/info/help.ts | 3 ++- src/commands/info/status.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 898617b..3ba7a01 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -2,6 +2,7 @@ import config from 'config'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; import { BotOptions, EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); @@ -12,7 +13,7 @@ module.exports = { .setDescription('Show a list of commands and their usage.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { + execute: async ({ interaction, client, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'help.js', module: 'slashCommand', diff --git a/src/commands/info/status.ts b/src/commands/info/status.ts index cbc5fd8..d425a0c 100644 --- a/src/commands/info/status.ts +++ b/src/commands/info/status.ts @@ -5,6 +5,7 @@ import osu from 'node-os-utils'; // @ts-ignore import { version } from '../../../package.json'; import loggerModule from '../../services/logger'; +import { CommandParams } from '../../types/commandTypes'; import { EmbedOptions } from '../../types/configTypes'; import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted'; @@ -17,7 +18,7 @@ module.exports = { .setDescription('Show the bot and system status.') .setDMPermission(false) .setNSFW(false), - execute: async ({ interaction, client, executionId }) => { + execute: async ({ interaction, client, executionId }: CommandParams) => { const logger = loggerModule.child({ source: 'status.js', module: 'slashCommand', From 45d6ffa1798bcbe532d4319f46a9839e607311c6 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 17:52:49 +0200 Subject: [PATCH 20/24] fix: annotated the rest of commands --- config/default.js | 2 +- src/commands/info/help.ts | 11 +- src/commands/info/status.ts | 24 +- src/commands/player/filters.ts | 181 ++++++++----- src/commands/player/leave.ts | 22 +- src/commands/player/loop.ts | 38 +-- src/commands/player/lyrics.ts | 22 +- src/commands/player/nowplaying.ts | 123 ++++++--- src/commands/player/pause.ts | 40 +-- src/commands/player/play.ts | 246 ++++++++++-------- src/commands/player/queue.ts | 36 +-- src/commands/player/remove.ts | 32 ++- src/commands/player/seek.ts | 74 +++--- src/commands/player/shuffle.ts | 22 +- src/commands/player/skip.ts | 47 +++- src/commands/player/stop.ts | 22 +- src/commands/player/volume.ts | 14 +- src/commands/system/guilds.ts | 2 +- src/types/clientTypes.ts | 5 +- src/types/commandTypes.ts | 11 + src/types/configTypes.ts | 2 +- .../validation/systemCommandValidator.ts | 2 +- 22 files changed, 596 insertions(+), 382 deletions(-) diff --git a/config/default.js b/config/default.js index d2a566b..739450f 100644 --- a/config/default.js +++ b/config/default.js @@ -114,7 +114,7 @@ module.exports.playerOptions = { leaveOnEmpty: true, leaveOnEmptyCooldown: 1_800_000, leaveOnEnd: true, - leaveonEndCooldown: 1_800_000, + leaveOnEndCooldown: 1_800_000, leaveOnStop: true, leaveOnStopCooldown: 1_800_000, defaultVolume: 50, diff --git a/src/commands/info/help.ts b/src/commands/info/help.ts index 3ba7a01..7e98801 100644 --- a/src/commands/info/help.ts +++ b/src/commands/info/help.ts @@ -8,6 +8,8 @@ import { BotOptions, EmbedOptions } from '../../types/configTypes'; const embedOptions: EmbedOptions = config.get('embedOptions'); const botOptions: BotOptions = config.get('botOptions'); module.exports = { + isNew: false, + isBeta: false, data: new SlashCommandBuilder() .setName('help') .setDescription('Show a list of commands and their usage.') @@ -19,10 +21,15 @@ module.exports = { module: 'slashCommand', name: '/help', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); + if (!client || !client.commands) { + logger.error('Client is undefined or does not have commands property.'); + return; + } + const commandList = client.commands .filter((command) => { // don't include system commands diff --git a/src/commands/info/status.ts b/src/commands/info/status.ts index d425a0c..afced7a 100644 --- a/src/commands/info/status.ts +++ b/src/commands/info/status.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { Collection, EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import osu from 'node-os-utils'; // @ts-ignore @@ -24,8 +24,8 @@ module.exports = { module: 'slashCommand', name: '/status', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); const uptimeString = await getUptimeFormatted({ executionId }); @@ -38,15 +38,20 @@ module.exports = { let totalTracks = 0; let totalListeners = 0; + if (!client || !client.shard) { + logger.error('Client is undefined or does not have shard property.'); + return; + } + await client.shard .broadcastEval(() => { /* eslint-disable no-undef */ return player.generateStatistics(); }) .then((results) => { - const queueCountList = []; - const trackCountList = []; - const listenerCountList = []; + const queueCountList: number[] = []; + const trackCountList: number[] = []; + const listenerCountList: number[] = []; results.map((result) => { queueCountList.push(result.queues.length); if (result.queues.length > 0) { @@ -70,10 +75,11 @@ module.exports = { await client.shard .fetchClientValues('guilds.cache') .then((results) => { - results.map((guildCache) => { + const guildCaches = results as Collection[]; + guildCaches.map((guildCache) => { if (guildCache) { - guildCount += guildCache.length; - memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0); + guildCount += guildCache.size; + memberCount += guildCache.reduce((acc, guild) => acc + guild.memberCount, 0); } }); diff --git a/src/commands/player/filters.ts b/src/commands/player/filters.ts index 25c1948..fb25c8e 100644 --- a/src/commands/player/filters.ts +++ b/src/commands/player/filters.ts @@ -1,17 +1,22 @@ import config from 'config'; -import { useQueue } from 'discord-player'; +import { NodeResolvable, QueueFilters, useQueue } from 'discord-player'; import { - ActionRowBuilder, + APIActionRowComponent, + APIMessageActionRowComponent, ButtonBuilder, + ButtonStyle, + ComponentType, EmbedBuilder, + GuildMember, + Interaction, SlashCommandBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; -import { EmbedOptions, FFmpegFilterOptions } from '../../types/configTypes'; +import { CommandParams, CustomError } from '../../types/commandTypes'; +import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; @@ -31,15 +36,15 @@ module.exports = { module: 'slashCommand', name: '/filters', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -53,12 +58,12 @@ module.exports = { return; } - const filterOptions = []; + const filterOptions: StringSelectMenuOptionBuilder[] = []; - ffmpegFilterOptions.availableFilters.forEach((filter) => { + ffmpegFilterOptions.availableFilters.forEach((filter: FFmpegFilterOption) => { let isEnabled = false; - if (queue.filters.ffmpeg.filters.includes(filter.value)) { + if (queue.filters.ffmpeg.filters.includes(filter.value as keyof QueueFilters)) { isEnabled = true; } @@ -77,31 +82,37 @@ module.exports = { .setPlaceholder('Select multiple options.') .setMinValues(0) .setMaxValues(filterOptions.length) - .addOptions(filterOptions); + .addOptions(filterOptions) + .toJSON(); - const filterActionRow = new ActionRowBuilder().addComponents(filterSelect); + const filterActionRow: APIActionRowComponent = { + type: ComponentType.ActionRow, + components: [filterSelect] + }; - const disableFiltersActionRow = new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId('disable-filters') - .setLabel('Disable all filters') - .setStyle('Secondary') - .setEmoji(embedOptions.icons.disable) - ); + const disableButton = new ButtonBuilder() + .setCustomId('disable-filters') + .setLabel('Disable all filters') + .setStyle(ButtonStyle.Secondary) + .setEmoji(embedOptions.icons.disable) + .toJSON(); + + const disableFiltersActionRow: APIActionRowComponent = { + type: ComponentType.ActionRow, + components: [disableButton] + }; logger.debug('Sending info embed with action row components.'); const response = await interaction.editReply({ embeds: [ new EmbedBuilder() - .setDescription( - `**Toggle filters** ${embedOptions.icons.beta}\nEnable or disable audio filters for playback from the menu.` - ) + .setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.') .setColor(embedOptions.colors.info) ], components: [filterActionRow, disableFiltersActionRow] }); - const collectorFilter = (i) => i.user.id === interaction.user.id; + const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id; try { const confirmation = await response.awaitMessageComponent({ filter: collectorFilter, @@ -130,14 +141,64 @@ module.exports = { logger.debug('Reset queue filters.'); } - if (confirmation.customId === 'disable-filters' || confirmation.values.length === 0) { + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + + if ('values' in confirmation) { + // if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion + if ( + (confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) && + !confirmation.values.includes('normalizer') + ) { + confirmation.values.push('normalizer'); + } + + // Enable provided filters + queue.filters.ffmpeg.toggle(confirmation.values as (keyof QueueFilters)[]); + logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`); + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' + }) + .setDescription( + `**${ + embedOptions.icons.success + } Filters toggled**\nNow using these filters:\n${confirmation.values + .map((enabledFilter: string) => { + const filter = ffmpegFilterOptions.availableFilters.find( + (filter) => enabledFilter == filter.value + ); + + if (!filter) { + return enabledFilter; + } + + return `- **${filter.emoji} ${filter.label}**`; + }) + .join('\n')}` + ) + .setColor(embedOptions.colors.success) + ], + components: [] + }); + } else if (confirmation.customId === 'disable-filters') { + logger.debug('Responding with success embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setAuthor({ + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.` @@ -146,53 +207,33 @@ module.exports = { ], components: [] }); + } else { + logger.warn('Unhandled component interaction response.'); } - - // if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion - if ( - (confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) && - !confirmation.values.includes('normalizer') - ) { - confirmation.values.push('normalizer'); - } - - // Enable provided filters - queue.filters.ffmpeg.toggle(confirmation.values); - logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`); - - logger.debug('Responding with success embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() - }) - .setDescription( - `**${ - embedOptions.icons.success - } Filters toggled**\nNow using these filters:\n${confirmation.values - .map((enabledFilter) => { - const filter = ffmpegFilterOptions.availableFilters.find( - (filter) => enabledFilter == filter.value - ); - - return `- **${filter.emoji} ${filter.label}**`; - }) - .join('\n')}` - ) - .setColor(embedOptions.colors.success) - ], - components: [] - }); } catch (error) { - if (error.code === 'InteractionCollectorError') { - logger.debug('Interaction response timed out.'); - return; - } + if (error instanceof CustomError) { + if (error.code === 'InteractionCollectorError') { + logger.debug('Interaction response timed out.'); + return; + } - logger.error(error, 'Unhandled error while awaiting or handling component interaction.'); - return; + if (error.message === 'Collector received no interactions before ending with reason: time') { + logger.debug('Interaction response timed out.'); + return; + } + + logger.error(error, 'Unhandled error while awaiting or handling component interaction.'); + return; + } else { + if ( + error instanceof Error && + error.message === 'Collector received no interactions before ending with reason: time' + ) { + logger.debug('Interaction response timed out.'); + return; + } + throw error; + } } } }; diff --git a/src/commands/player/leave.ts b/src/commands/player/leave.ts index d019327..9b5308e 100644 --- a/src/commands/player/leave.ts +++ b/src/commands/player/leave.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -22,15 +22,15 @@ module.exports = { module: 'slashCommand', name: '/leave', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (!queue) { logger.debug('There is already no queue.'); @@ -56,13 +56,21 @@ module.exports = { logger.debug('Deleted the queue.'); } + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!` diff --git a/src/commands/player/loop.ts b/src/commands/player/loop.ts index 623fcd4..1424691 100644 --- a/src/commands/player/loop.ts +++ b/src/commands/player/loop.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -36,15 +36,15 @@ module.exports = { module: 'slashCommand', name: '/loop', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -61,7 +61,7 @@ module.exports = { [3, 'autoplay'] ]); - const mode = parseInt(interaction.options.getString('mode')); + const mode = parseInt(interaction.options.getString('mode')!); const modeUserString = loopModesFormatted.get(mode); const currentMode = queue.repeatMode; const currentModeUserString = loopModesFormatted.get(currentMode); @@ -76,7 +76,7 @@ module.exports = { .setDescription( `**${ currentMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop - } Current loop mode**\nThe looping mode is currently set to \`${currentModeUserString}\`.` + } Current loop mode**\nThe looping mode is currently set to **\`${currentModeUserString}\`**.` ) .setColor(embedOptions.colors.info) ] @@ -91,7 +91,7 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nLoop mode is already \`${modeUserString}\`.` + `**${embedOptions.icons.warning} Oops!**\nLoop mode is already **\`${modeUserString}\`**.` ) .setColor(embedOptions.colors.warning) ] @@ -112,7 +112,7 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to \`${modeUserString}\`, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + `**${embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to **\`${modeUserString}\`**, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` ) .setColor(embedOptions.colors.error) .setFooter({ text: `Execution ID: ${executionId}` }) @@ -120,6 +120,14 @@ module.exports = { }); } + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + if (queue.repeatMode === 0) { logger.debug('Disabled loop mode.'); @@ -128,8 +136,8 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.success} Loop mode disabled**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${currentModeUserString} will no longer play on repeat!` @@ -147,8 +155,8 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.autoplaying} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nWhen the queue is empty, similar tracks will start playing!` @@ -165,8 +173,8 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.looping} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${modeUserString} will now play on repeat!` diff --git a/src/commands/player/lyrics.ts b/src/commands/player/lyrics.ts index 3986875..332fa83 100644 --- a/src/commands/player/lyrics.ts +++ b/src/commands/player/lyrics.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { QueryType, useMainPlayer, useQueue } from 'discord-player'; +import { NodeResolvable, QueryType, useMainPlayer, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import { lyricsExtractor } from '@discord-player/extractor'; @@ -39,8 +39,8 @@ module.exports = { autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { const logger = loggerTemplate.child({ executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); const query = interaction.options.getString('query', true); @@ -63,7 +63,7 @@ module.exports = { if (!lyricsResult) { logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`); - const player = useMainPlayer(); + const player = useMainPlayer()!; const searchResults = await player.search(query); response = searchResults.tracks.slice(0, 1).map((track) => ({ name: @@ -99,12 +99,12 @@ module.exports = { execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerTemplate.child({ executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); const query = interaction.options.getString('query'); - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; let geniusSearchQuery = ''; if (!query) { @@ -123,7 +123,7 @@ module.exports = { if (await queueNoCurrentTrack({ interaction, queue, executionId })) { return; } - geniusSearchQuery = queue.currentTrack.title.slice(0, 50); + geniusSearchQuery = queue.currentTrack!.title.slice(0, 50); logger.debug( `No input query provided, using current track. Using query for genius: '${geniusSearchQuery}'` @@ -133,7 +133,7 @@ module.exports = { let searchResult; if (query) { logger.debug(`Query input provided, using query '${query}' for player.search().`); - const player = useMainPlayer(); + const player = useMainPlayer()!; const searchResults = await player.search(query, { searchEngine: QueryType.SPOTIFY_SEARCH }); @@ -220,7 +220,7 @@ module.exports = { logger.debug('Lyrics text too long, splitting into multiple messages.'); const messageCount = Math.ceil(lyricsResult.lyrics.length / 3800); for (let i = 0; i < messageCount; i++) { - logger.debuf(`Lyrics, sending message ${i + 1} of ${messageCount}.`); + logger.debug(`Lyrics, sending message ${i + 1} of ${messageCount}.`); const message = lyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800); if (i === 0) { logger.debug('Responding with info embed for first message with lyrics.'); @@ -239,7 +239,7 @@ module.exports = { continue; } else { logger.debug('Sending consecutive message with lyrics.'); - await interaction.channel.send({ + await interaction.channel!.send({ embeds: [ new EmbedBuilder() .setDescription(`\`\`\`fix\n${message}\`\`\``) diff --git a/src/commands/player/nowplaying.ts b/src/commands/player/nowplaying.ts index 423f89b..f56a8d9 100644 --- a/src/commands/player/nowplaying.ts +++ b/src/commands/player/nowplaying.ts @@ -1,9 +1,19 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { ActionRowBuilder, ButtonBuilder, EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, Track, useQueue } from 'discord-player'; +import { + APIActionRowComponent, + APIMessageActionRowComponent, + ButtonBuilder, + ButtonStyle, + ComponentType, + EmbedBuilder, + GuildMember, + Interaction, + SlashCommandBuilder +} from 'discord.js'; import loggerModule from '../../services/logger'; -import { CommandParams } from '../../types/commandTypes'; +import { CommandParams, TrackMetadata, CustomError } from '../../types/commandTypes'; import { EmbedOptions, PlayerOptions } from '../../types/configTypes'; import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator'; import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator'; @@ -24,15 +34,15 @@ module.exports = { module: 'slashCommand', name: '/nowplaying', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -62,28 +72,27 @@ module.exports = { ['arbitrary', embedOptions.icons.sourceArbitrary] ]); - const currentTrack = queue.currentTrack; + const currentTrack: Track = queue.currentTrack!; let author = currentTrack.author ? currentTrack.author : 'Unavailable'; if (author === 'cdn.discordapp.com') { author = 'Unavailable'; } - let plays = currentTrack.views !== 0 ? currentTrack.views : 0; + const plays = currentTrack.views !== 0 ? currentTrack.views : 0; - if ( - plays === 0 && - currentTrack.metadata.bridge && - currentTrack.metadata.bridge.views !== 0 && - currentTrack.metadata.bridge.views !== undefined - ) { - plays = currentTrack.metadata.bridge.views; + let displayPlays: string = plays.toLocaleString('en-US'); + + const metadata = currentTrack.metadata as TrackMetadata; + + if (plays === 0 && metadata.bridge && metadata.bridge.views !== 0 && metadata.bridge.views !== undefined) { + displayPlays = metadata.bridge.views.toLocaleString('en-US'); } else if (plays === 0) { - plays = 'Unavailable'; + displayPlays = 'Unavailable'; } - const source = sourceStringsFormatted.get(currentTrack.raw.source) ?? 'Unavailable'; + const source = sourceStringsFormatted.get(currentTrack.raw.source!) ?? 'Unavailable'; const queueLength = queue.tracks.data.length; - const timestamp = queue.node.getTimestamp(); + const timestamp = queue.node.getTimestamp()!; let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({ queue: false, length: playerOptions.progressBar.length ?? 12, @@ -93,7 +102,7 @@ module.exports = { rightChar: playerOptions.progressBar.rightChar ?? '▬' })} **\`${timestamp.total.label}\`**`; - if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') { + if (Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00') { bar = '_No duration available._'; } @@ -101,13 +110,17 @@ module.exports = { bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`; } - const nowPlayingActionRow = new ActionRowBuilder().addComponents( - new ButtonBuilder() - .setCustomId('nowplaying-skip') - .setLabel('Skip track') - .setStyle('Secondary') - .setEmoji(embedOptions.icons.nextTrack) - ); + const nowPlayingButton = new ButtonBuilder() + .setCustomId('nowplaying-skip') + .setLabel('Skip track') + .setStyle(ButtonStyle.Secondary) + .setEmoji(embedOptions.icons.nextTrack) + .toJSON(); // Convert the builder to a raw object + + const nowPlayingActionRow: APIActionRowComponent = { + type: ComponentType.ActionRow, // This might vary based on your discord.js version + components: [nowPlayingButton] + }; const loopModesFormatted = new Map([ [0, 'disabled'], @@ -125,15 +138,15 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, - iconURL: interaction.guild.iconURL() + name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`, + iconURL: interaction.guild!.iconURL() || '' }) .setDescription( (queue.node.isPaused() ? '**Currently Paused**\n' : `**${embedOptions.icons.audioPlaying} Now Playing**\n`) + `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` + - `\nRequested by: <@${currentTrack.requestedBy.id}>` + + `\nRequested by: <@${currentTrack.requestedBy?.id}>` + `\n ${bar}\n\n` + `${ queue.repeatMode === 0 @@ -151,12 +164,12 @@ module.exports = { }, { name: '**Plays**', - value: plays.toLocaleString('en-US'), + value: displayPlays, inline: true }, { name: '**Track source**', - value: `**${sourceIcons.get(currentTrack.raw.source)} [${source}](${ + value: `**${sourceIcons.get(currentTrack.raw.source!)} [${source}](${ currentTrack.raw.url ?? currentTrack.url })**`, inline: true @@ -165,15 +178,15 @@ module.exports = { .setFooter({ text: queueLength ? `${queueLength} other tracks in the queue...` : ' ' }) - .setThumbnail(queue.currentTrack.thumbnail) + .setThumbnail(queue.currentTrack!.thumbnail) .setColor(embedOptions.colors.info) ], - components: [nowPlayingActionRow] + components: [nowPlayingActionRow as APIActionRowComponent] }); logger.debug('Finished sending response.'); - const collectorFilter = (i) => i.user.id === interaction.user.id; + const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id; try { const confirmation = await response.awaitMessageComponent({ filter: collectorFilter, @@ -222,7 +235,7 @@ module.exports = { const skippedTrack = queue.currentTrack; let durationFormat = - skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' + Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' ? '' : `\`${skippedTrack.duration}\``; @@ -234,13 +247,21 @@ module.exports = { const repeatModeUserString = loopModesFormatted.get(queue.repeatMode); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.followUp({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ @@ -263,13 +284,29 @@ module.exports = { }); } } catch (error) { - if (error.code === 'InteractionCollectorError') { - logger.debug('Interaction response timed out.'); - return; - } + if (error instanceof CustomError) { + if (error.code === 'InteractionCollectorError') { + logger.debug('Interaction response timed out.'); + return; + } - logger.error(error, 'Unhandled error while awaiting or handling component interaction.'); - return; + if (error.message === 'Collector received no interactions before ending with reason: time') { + logger.debug('Interaction response timed out.'); + return; + } + + logger.error(error, 'Unhandled error while awaiting or handling component interaction.'); + return; + } else { + if ( + error instanceof Error && + error.message === 'Collector received no interactions before ending with reason: time' + ) { + logger.debug('Interaction response timed out.'); + return; + } + throw error; + } } } }; diff --git a/src/commands/player/pause.ts b/src/commands/player/pause.ts index 9c92e9d..029cf31 100644 --- a/src/commands/player/pause.ts +++ b/src/commands/player/pause.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -23,15 +23,15 @@ module.exports = { module: 'slashCommand', name: '/pause', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -45,12 +45,14 @@ module.exports = { return; } - let durationFormat = - queue.currentTrack.raw.duration === 0 || queue.currentTrack.duration === '0:00' - ? '' - : `\`${queue.currentTrack.duration}\``; + const currentTrack = queue.currentTrack!; - if (queue.currentTrack.raw.live) { + let durationFormat = + Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00' + ? '' + : `\`${currentTrack.duration}\``; + + if (currentTrack.raw.live) { durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; } @@ -58,22 +60,28 @@ module.exports = { queue.node.setPaused(!queue.node.isPaused()); logger.debug(`Set paused state to ${queue.node.isPaused()}.`); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.pauseResumed} ${ queue.node.isPaused() ? 'Paused Track' : 'Resumed track' - }**\n**${durationFormat} [${queue.currentTrack.title}](${ - queue.currentTrack.raw.url ?? queue.currentTrack.url - })**` + }**\n**${durationFormat} [${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` ) - .setThumbnail(queue.currentTrack.thumbnail) + .setThumbnail(currentTrack.thumbnail) .setColor(embedOptions.colors.success) ] }); diff --git a/src/commands/player/play.ts b/src/commands/player/play.ts index 14ebb14..371689c 100644 --- a/src/commands/player/play.ts +++ b/src/commands/player/play.ts @@ -1,6 +1,6 @@ import config from 'config'; import { useMainPlayer, useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes'; @@ -40,11 +40,11 @@ module.exports = { autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => { const logger = loggerTemplate.child({ executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); - const player = useMainPlayer(); + const player = useMainPlayer()!; const query = interaction.options.getString('query', true); const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {}; @@ -92,8 +92,8 @@ module.exports = { execute: async ({ interaction, executionId }: CommandParams) => { const logger = loggerTemplate.child({ executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { @@ -104,13 +104,13 @@ module.exports = { return; } - let queue = useQueue(interaction.guild.id); + let queue = useQueue(interaction.guild!.id); if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) { return; } - const player = useMainPlayer(); - const query = interaction.options.getString('query'); + const player = useMainPlayer()!; + const query = interaction.options.getString('query')!; const transformedQuery = await transformQuery({ query, executionId }); @@ -132,17 +132,17 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} No track found**\nNo results found for \`${transformedQuery}\`.\n\nIf you specified a URL, please make sure it is valid and public.` + `**${embedOptions.icons.warning} No track found**\nNo results found for **\`${transformedQuery}\`**.\n\nIf you specified a URL, please make sure it is valid and public.` ) .setColor(embedOptions.colors.warning) ] }); } - queue = useQueue(interaction.guild.id); + queue = useQueue(interaction.guild!.id); const queueSize = queue?.size ?? 0; - if ((searchResult.playlist && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) { + if ((searchResult.playlist! && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) { logger.debug(`Playlist found but would exceed max queue size. Query: '${query}'.`); logger.debug('Responding with warning embed.'); @@ -162,7 +162,7 @@ module.exports = { try { logger.debug(`Attempting to add track with player.play(). Query: '${query}'.`); - ({ track } = await player.play(interaction.member.voice.channel, searchResult, { + ({ track } = await player.play((interaction.member as GuildMember).voice.channel!, searchResult, { requestedBy: interaction.user, nodeOptions: { leaveOnEmpty: playerOptions.leaveOnEmpty ?? true, @@ -185,98 +185,106 @@ module.exports = { } })); } catch (error) { - if (error.message.includes('Sign in to confirm your age')) { - logger.debug('Found track but failed to retrieve audio due to age confirmation warning.'); + if (error instanceof Error) { + if (error.message.includes('Sign in to confirm your age')) { + logger.debug('Found track but failed to retrieve audio due to age confirmation warning.'); - logger.debug('Responding with warning embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.warning) - ] - }); + logger.debug('Responding with warning embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + + if (error.message.includes('The following content may contain')) { + logger.debug( + 'Found track but failed to retrieve audio due to graphic/mature/sensitive topic warning.' + ); + + logger.debug('Responding with warning embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source cannot be played as the video source has a warning for graphic or sensistive topics. It requires a manual confirmation to to play the video, and because of this I am unable to extract the audio for this source.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.warning) + ] + }); + } + + if ( + error.message.includes("Cannot read properties of null (reading 'createStream')") || + error.message.includes('Failed to fetch resources for ytdl streaming') || + error.message.includes('Could not extract stream for this track') + ) { + logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`); + + logger.debug('Responding with error embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nAfter finding a result, I was unable to retrieve audio for the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } + + if (error.message === 'Cancelled') { + logger.debug(error, `Operation cancelled. Query: ${query}.`); + + logger.debug('Responding with error embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and the operation was cancelled.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } + + if (error.message === "Cannot read properties of null (reading 'createStream')") { + // Can happen if /play then /leave before track starts playing + logger.warn( + error, + 'Found track but failed to play back audio. Voice connection might be unavailable.' + ); + + logger.debug('Responding with error embed.'); + return await interaction.editReply({ + embeds: [ + new EmbedBuilder() + .setDescription( + `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and it was not possible to start playing the track. This could happen if the voice connection is lost or queue is destroyed while adding the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` + ) + .setColor(embedOptions.colors.error) + .setFooter({ text: `Execution ID: ${executionId}` }) + ] + }); + } + + logger.error(error, 'Failed to play track with player.play(), unhandled error.'); + } else { + throw error; } - - if (error.message.includes('The following content may contain')) { - logger.debug('Found track but failed to retrieve audio due to graphic/mature/sensitive topic warning.'); - - logger.debug('Responding with warning embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source cannot be played as the video source has a warning for graphic or sensistive topics. It requires a manual confirmation to to play the video, and because of this I am unable to extract the audio for this source.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.warning) - ] - }); - } - - if ( - (error.type === 'TypeError' && - (error.message.includes("Cannot read properties of null (reading 'createStream')") || - error.message.includes('Failed to fetch resources for ytdl streaming'))) || - error.message.includes('Could not extract stream for this track') - ) { - logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`); - - logger.debug('Responding with error embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nAfter finding a result, I was unable to retrieve audio for the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } - - if (error.message === 'Cancelled') { - logger.debug(error, `Operation cancelled. Query: ${query}.`); - - logger.debug('Responding with error embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and the operation was cancelled.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } - - if (error.message === "Cannot read properties of null (reading 'createStream')") { - // Can happen if /play then /leave before track starts playing - logger.warn(error, 'Found track but failed to play back audio. Voice connection might be unavailable.'); - - logger.debug('Responding with error embed.'); - return await interaction.editReply({ - embeds: [ - new EmbedBuilder() - .setDescription( - `**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and it was not possible to start playing the track. This could happen if the voice connection is lost or queue is destroyed while adding the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._` - ) - .setColor(embedOptions.colors.error) - .setFooter({ text: `Execution ID: ${executionId}` }) - ] - }); - } - - logger.error(error, 'Failed to play track with player.play(), unhandled error.'); } logger.debug(`Successfully added track with player.play(). Query: '${query}'.`); - queue = useQueue(interaction.guild.id); + queue = useQueue(interaction.guild!.id); - if (!queue) { + if (!queue || !track) { logger.warn(`After player.play(), queue is undefined. Query: '${query}'.`); logger.debug('Responding with error embed.'); @@ -295,7 +303,7 @@ module.exports = { if ( track.source.length === 0 || track.source === 'arbitrary' || - track.thumnail === null || + track.thumbnail === null || track.thumbnail === undefined || track.thumbnail === '' ) { @@ -305,7 +313,8 @@ module.exports = { track.thumbnail = embedOptions.info.fallbackThumbnailUrl; } - let durationFormat = track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; + let durationFormat = + Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; if (track.raw.live) { durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; @@ -314,13 +323,21 @@ module.exports = { if (searchResult.playlist && searchResult.tracks.length > 1) { logger.debug(`Playlist found and added with player.play(). Query: '${query}'`); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${ @@ -338,14 +355,21 @@ module.exports = { if (queue.currentTrack === track && queue.tracks.data.length === 0) { logger.debug(`Track found and added with player.play(), started playing. Query: '${query}'.`); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: - interaction.member.nickname || interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${ @@ -360,13 +384,21 @@ module.exports = { logger.debug(`Track found and added with player.play(), added to queue. Query: '${query}'.`); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${ diff --git a/src/commands/player/queue.ts b/src/commands/player/queue.ts index deb58c0..02208fd 100644 --- a/src/commands/player/queue.ts +++ b/src/commands/player/queue.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { useQueue } from 'discord-player'; +import { NodeResolvable, useQueue } from 'discord-player'; import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; @@ -24,15 +24,15 @@ module.exports = { module: 'slashCommand', name: '/queue', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await notInSameVoiceChannel({ interaction, queue, executionId })) { return; @@ -50,9 +50,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nPage \`${ + `**${embedOptions.icons.warning} Oops!**\nPage **\`${ pageIndex + 1 - }\` is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!` + }\`** is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!` ) .setColor(embedOptions.colors.warning) ] @@ -67,8 +67,8 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.guild.name, - iconURL: interaction.guild.iconURL() + name: interaction.guild!.name, + iconURL: interaction.guild!.iconURL() || '' }) .setDescription(`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`) .setColor(embedOptions.colors.info) @@ -90,9 +90,9 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nPage \`${ + `**${embedOptions.icons.warning} Oops!**\nPage **\`${ pageIndex + 1 - }\` is not a valid page number.\n\nThere are only a total of \`${totalPages}\` pages in the queue.` + }\`** is not a valid page number.\n\nThere are only a total of **\`${totalPages}\`** pages in the queue.` ) .setColor(embedOptions.colors.warning) ] @@ -107,7 +107,7 @@ module.exports = { .slice(pageIndex * 10, pageIndex * 10 + 10) .map((track, index) => { let durationFormat = - track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; + Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``; if (track.raw.live) { durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; @@ -147,8 +147,8 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, - iconURL: interaction.guild.iconURL() + name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`, + iconURL: interaction.guild!.iconURL() || '' }) .setDescription( `${repeatModeString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}` @@ -161,7 +161,7 @@ module.exports = { }); } else { logger.debug('Queue exists with current track, gathering information.'); - const timestamp = queue.node.getTimestamp(); + const timestamp = queue.node.getTimestamp()!; let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({ queue: false, length: playerOptions.progressBar.length ?? 12, @@ -171,7 +171,7 @@ module.exports = { rightChar: playerOptions.progressBar.rightChar ?? '▬' })} **\`${timestamp.total.label}\`**`; - if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') { + if (Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00') { bar = '_No duration available._'; } @@ -184,15 +184,15 @@ module.exports = { embeds: [ new EmbedBuilder() .setAuthor({ - name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`, - iconURL: interaction.guild.iconURL() + name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`, + iconURL: interaction.guild!.iconURL() || '' }) .setDescription( `**${embedOptions.icons.audioPlaying} Now playing**\n` + (currentTrack ? `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` : 'None') + - `\nRequested by: <@${currentTrack.requestedBy.id}>` + + `\nRequested by: <@${currentTrack.requestedBy?.id}>` + `\n ${bar}\n\n` + `${repeatModeString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}` diff --git a/src/commands/player/remove.ts b/src/commands/player/remove.ts index 324dc92..de23dc2 100644 --- a/src/commands/player/remove.ts +++ b/src/commands/player/remove.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -30,15 +30,15 @@ module.exports = { module: 'slashCommand', name: '/remove', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -48,7 +48,7 @@ module.exports = { return; } - const removeTrackNumber = interaction.options.getNumber('tracknumber'); + const removeTrackNumber = interaction.options.getNumber('tracknumber')!; if (removeTrackNumber > queue.tracks.data.length) { logger.debug('Specified track number is higher than total tracks.'); @@ -58,7 +58,7 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nTrack \`${removeTrackNumber}\` is not a valid track number. There are a total of\`${queue.tracks.data.length}\` tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.` + `**${embedOptions.icons.warning} Oops!**\nTrack **\`${removeTrackNumber}\`** is not a valid track number. There are a total of **\`${queue.tracks.data.length}\`** tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.` ) .setColor(embedOptions.colors.warning) ] @@ -66,22 +66,32 @@ module.exports = { } // Remove specified track number from queue - const removedTrack = queue.node.remove(removeTrackNumber - 1); + const removedTrack = queue.node.remove(removeTrackNumber - 1)!; logger.debug(`Removed track '${removedTrack.url}' from queue.`); let durationFormat = - removedTrack.raw.duration === 0 || removedTrack.duration === '0:00' ? '' : `\`${removedTrack.duration}\``; + Number(removedTrack.raw.duration) === 0 || removedTrack.duration === '0:00' + ? '' + : `\`${removedTrack.duration}\``; if (removedTrack.raw.live) { durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``; } + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${ diff --git a/src/commands/player/seek.ts b/src/commands/player/seek.ts index 88a0339..2d18851 100644 --- a/src/commands/player/seek.ts +++ b/src/commands/player/seek.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -29,15 +29,15 @@ module.exports = { module: 'slashCommand', name: '/seek', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -52,7 +52,8 @@ module.exports = { } const durationInput = interaction.options.getString('duration'); - let durationArray = durationInput.split(':'); + + let durationArray = durationInput!.split(':'); switch (durationArray.length) { case 1: @@ -65,6 +66,12 @@ module.exports = { break; } + durationArray = durationArray.map((value) => { + return value.padStart(2, '0'); + }); + + const durationString = durationArray.join(':'); + if (durationArray.length === 0 || durationArray.length > 3) { logger.debug('Invalid duration format input.'); @@ -73,22 +80,16 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + - '- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + - '- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + - '- `/seek` **`42`** - Seek to 42 seconds.' + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + + '- **`/seek`** **`42`** - Seek to 42 seconds.' ) .setColor(embedOptions.colors.warning) ] }); } - durationArray = durationArray.map((value) => { - return value.padStart(2, '0'); - }); - - const durationString = durationArray.join(':'); - const validElements = durationArray.every((value) => { return value.length === 2; }); @@ -101,10 +102,10 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + - '- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + - '- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + - '- `/seek` **`42`** - Seek to 42 seconds.' + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + + '- **`/seek`** **`42`** - Seek to 42 seconds.' ) .setColor(embedOptions.colors.warning) ] @@ -124,18 +125,19 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` + - '- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + - '- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + - '- `/seek` **`42`** - Seek to 42 seconds.' + `**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` + + '- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' + + '- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' + + '- **`/seek`** **`42`** - Seek to 42 seconds.' ) .setColor(embedOptions.colors.warning) ] }); } - const currentTrackMaxDurationInMs = queue.currentTrack.durationMS; - const durationInMilliseconds = durationArray[0] * 3600000 + durationArray[1] * 60000 + durationArray[2] * 1000; + const currentTrackMaxDurationInMs = queue.currentTrack!.durationMS; + const durationInMilliseconds: number = + Number(durationArray[0]) * 3600000 + Number(durationArray[1]) * 60000 + Number(durationArray[2]) * 1000; if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) { logger.debug('Duration specified is longer than the track duration.'); @@ -145,7 +147,11 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${queue.currentTrack.duration}\`**).` + `**${ + embedOptions.icons.warning + } Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${ + queue.currentTrack!.duration + }\`**).` ) .setColor(embedOptions.colors.warning) ] @@ -155,18 +161,26 @@ module.exports = { queue.node.seek(durationInMilliseconds); logger.debug(`Seeked to '${durationString}' in current track.`); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.` ) - .setThumbnail(queue.currentTrack.thumbnail) + .setThumbnail(queue.currentTrack!.thumbnail) .setColor(embedOptions.colors.success) ] }); diff --git a/src/commands/player/shuffle.ts b/src/commands/player/shuffle.ts index 990a3fe..e5692e8 100644 --- a/src/commands/player/shuffle.ts +++ b/src/commands/player/shuffle.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -23,15 +23,15 @@ module.exports = { module: 'slashCommand', name: '/shuffle', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -48,13 +48,21 @@ module.exports = { queue.tracks.shuffle(); logger.debug('Shuffled queue tracks.'); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.shuffled} Shuffled queue tracks**\nThe **${queue.tracks.data.length}** tracks in the queue has been shuffled.\n\nView the new queue order with **\`/queue\`**.` diff --git a/src/commands/player/skip.ts b/src/commands/player/skip.ts index 2942fb3..7724852 100644 --- a/src/commands/player/skip.ts +++ b/src/commands/player/skip.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -26,15 +26,15 @@ module.exports = { module: 'slashCommand', name: '/skip', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -59,15 +59,17 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nThere are only \`${queue.tracks.data.length}\` tracks in the queue. You cannot skip to track \`${skipToTrack}\`.\n\nView tracks added to the queue with **\`/queue\`**.` + `**${embedOptions.icons.warning} Oops!**\nThere are only **\`${queue.tracks.data.length}\`** tracks in the queue. You cannot skip to track **\`${skipToTrack}\`**.\n\nView tracks added to the queue with **\`/queue\`**.` ) .setColor(embedOptions.colors.warning) ] }); } else { - const skippedTrack = queue.currentTrack; + const skippedTrack = queue.currentTrack!; + logger.debug('Responding with warning embed.'); + let durationFormat = - skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' + Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' ? '' : `\`${skippedTrack.duration}\``; @@ -78,13 +80,21 @@ module.exports = { queue.node.skipTo(skipToTrack - 1); logger.debug('Skipped to specified track number.'); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ @@ -112,9 +122,10 @@ module.exports = { }); } - const skippedTrack = queue.currentTrack; + const skippedTrack = queue.currentTrack!; + let durationFormat = - skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00' + Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00' ? '' : `\`${skippedTrack.duration}\``; @@ -133,13 +144,21 @@ module.exports = { const loopModeUserString = loopModesFormatted.get(queue.repeatMode); + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${ diff --git a/src/commands/player/stop.ts b/src/commands/player/stop.ts index 4cb5d9d..c3c15c7 100644 --- a/src/commands/player/stop.ts +++ b/src/commands/player/stop.ts @@ -1,6 +1,6 @@ import config from 'config'; -import { useQueue } from 'discord-player'; -import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; +import { NodeResolvable, useQueue } from 'discord-player'; +import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js'; import loggerModule from '../../services/logger'; import { CommandParams } from '../../types/commandTypes'; @@ -22,15 +22,15 @@ module.exports = { module: 'slashCommand', name: '/stop', executionId: executionId, - shardId: interaction.guild.shardId, - guildId: interaction.guild.id + shardId: interaction.guild?.shardId, + guildId: interaction.guild?.id }); if (await notInVoiceChannel({ interaction, executionId })) { return; } - const queue = useQueue(interaction.guild.id); + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (!queue) { logger.debug('There is no queue.'); @@ -58,13 +58,21 @@ module.exports = { logger.debug('Cleared and stopped the queue.'); } + let authorName: string; + + if (interaction.member instanceof GuildMember) { + authorName = interaction.member.nickname || interaction.user.username; + } else { + authorName = interaction.user.username; + } + logger.debug('Responding with success embed.'); return await interaction.editReply({ embeds: [ new EmbedBuilder() .setAuthor({ - name: interaction.member.nickname || interaction.user.username, - iconURL: interaction.user.avatarURL() + name: authorName, + iconURL: interaction.user.avatarURL() || '' }) .setDescription( `**${embedOptions.icons.success} Stopped playing**\nStopped playing audio and cleared the track queue.\n\nTo play more music, use the **\`/play\`** command!` diff --git a/src/commands/player/volume.ts b/src/commands/player/volume.ts index 4849c4c..989e652 100644 --- a/src/commands/player/volume.ts +++ b/src/commands/player/volume.ts @@ -38,11 +38,7 @@ module.exports = { return; } - if (!interaction.guild) { - return; - } - - const queue: NodeResolvable = useQueue(interaction.guild.id)!; + const queue: NodeResolvable = useQueue(interaction.guild!.id)!; if (await queueDoesNotExist({ interaction, queue, executionId })) { return; @@ -66,7 +62,7 @@ module.exports = { .setDescription( `**${ currentVolume === 0 ? embedOptions.icons.volumeIsMuted : embedOptions.icons.volume - } Playback volume**\nThe playback volume is currently set to \`${currentVolume}%\`.` + } Playback volume**\nThe playback volume is currently set to **\`${currentVolume}%\`**.` ) .setColor(embedOptions.colors.info) ] @@ -79,7 +75,7 @@ module.exports = { embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to \`${volume}\`, please pick a value betwen \`1\`% and \`100\`%.` + `**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to **\`${volume}%\`**, please pick a value betwen **\`1%\`** and **\`100%\`**.` ) .setColor(embedOptions.colors.warning) ] @@ -106,7 +102,7 @@ module.exports = { iconURL: interaction.user.avatarURL() || '' }) .setDescription( - `**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to \`${volume}%\`.` + `**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to **\`${volume}%\`**.` ) .setColor(embedOptions.colors.success) ] @@ -122,7 +118,7 @@ module.exports = { iconURL: interaction.user.avatarURL() || '' }) .setDescription( - `**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to \`${volume}%\`.` + `**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to **\`${volume}%\`**.` ) .setColor(embedOptions.colors.success) ] diff --git a/src/commands/system/guilds.ts b/src/commands/system/guilds.ts index fc76acd..5f45a35 100644 --- a/src/commands/system/guilds.ts +++ b/src/commands/system/guilds.ts @@ -71,7 +71,7 @@ module.exports = { `**${embedOptions.icons.bot} ${ totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds' } by member count (${totalGuildCount} total)**\n${guildListFormatted}` + - `\n\n**Total members:** \`${totalMemberCount}\``; + `\n\n**Total members:** **\`${totalMemberCount}\`**`; logger.debug('Transformed guild into into embed description.'); diff --git a/src/types/clientTypes.ts b/src/types/clientTypes.ts index 9b38d2f..921106b 100644 --- a/src/types/clientTypes.ts +++ b/src/types/clientTypes.ts @@ -3,8 +3,9 @@ import { Client, Collection, SharedNameAndDescription } from 'discord.js'; type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void; export interface Command { - isNew: boolean; - isBeta: boolean; + isNew?: boolean; + isBeta?: boolean; + isSystemCommand?: boolean; data: { name: string; description: string; diff --git a/src/types/commandTypes.ts b/src/types/commandTypes.ts index c122b7d..d5a1316 100644 --- a/src/types/commandTypes.ts +++ b/src/types/commandTypes.ts @@ -25,3 +25,14 @@ export interface ShardInfo { totalListeners: number; }; } + +export interface TrackMetadata { + bridge: { + views: number; + }; +} + +export class CustomError extends Error { + type?: string; + code?: string; +} diff --git a/src/types/configTypes.ts b/src/types/configTypes.ts index f5c18fc..d5e4f7e 100644 --- a/src/types/configTypes.ts +++ b/src/types/configTypes.ts @@ -91,7 +91,7 @@ export interface PlayerOptions { leaveOnEmpty: boolean; leaveOnEmptyCooldown: number; leaveOnEnd: boolean; - leaveonEndCooldown: number; + leaveOnEndCooldown: number; leaveOnStop: boolean; leaveOnStopCooldown: number; defaultVolume: number; diff --git a/src/utils/validation/systemCommandValidator.ts b/src/utils/validation/systemCommandValidator.ts index d659b7b..cdcb647 100644 --- a/src/utils/validation/systemCommandValidator.ts +++ b/src/utils/validation/systemCommandValidator.ts @@ -22,7 +22,7 @@ export const notValidGuildId = async ({ interaction, executionId }: NotValidGuil embeds: [ new EmbedBuilder() .setDescription( - `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command \`${interaction.commandName}\` cannot be executed in this server.` + `**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interaction.commandName}\`** cannot be executed in this server.` ) .setColor(embedOptions.colors.warning) ] From 7185fe4071990b822d9b4cd2eb983302dce50345 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 18:28:01 +0200 Subject: [PATCH 21/24] fix: fix annotation issue for guild cache list --- src/commands/info/status.ts | 18 +++++++++--------- src/commands/system/systemstatus.ts | 8 ++++---- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/commands/info/status.ts b/src/commands/info/status.ts index afced7a..41b3221 100644 --- a/src/commands/info/status.ts +++ b/src/commands/info/status.ts @@ -32,11 +32,11 @@ module.exports = { const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US'); const cpuUsage = await osu.cpu.usage(); const releaseVersion = version; - let guildCount = 0; - let memberCount = 0; - let activeVoiceConnections = 0; - let totalTracks = 0; - let totalListeners = 0; + let guildCount: number = 0; + let memberCount: number = 0; + let activeVoiceConnections: number = 0; + let totalTracks: number = 0; + let totalListeners: number = 0; if (!client || !client.shard) { logger.error('Client is undefined or does not have shard property.'); @@ -75,11 +75,11 @@ module.exports = { await client.shard .fetchClientValues('guilds.cache') .then((results) => { - const guildCaches = results as Collection[]; - guildCaches.map((guildCache) => { + const guildCaches = results as Guild[][]; + guildCaches.map((guildCache: Guild[]) => { if (guildCache) { - guildCount += guildCache.size; - memberCount += guildCache.reduce((acc, guild) => acc + guild.memberCount, 0); + guildCount += guildCache.length; + memberCount += guildCache.reduce((acc: number, guild: Guild) => acc + guild.memberCount, 0); } }); diff --git a/src/commands/system/systemstatus.ts b/src/commands/system/systemstatus.ts index ee32d6e..9585010 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/commands/system/systemstatus.ts @@ -96,11 +96,11 @@ module.exports = { await client.shard .fetchClientValues('guilds.cache') .then((results) => { - const guildCaches = results as Collection[]; - guildCaches.map((guildCache) => { + const guildCaches = results as Guild[][]; + guildCaches.map((guildCache: Guild[]) => { if (guildCache) { - guildCount += guildCache.size; - memberCount += guildCache.reduce((acc, guild) => acc + guild.memberCount, 0); + guildCount += guildCache.length; + memberCount += guildCache.reduce((acc: number, guild: Guild) => acc + guild.memberCount, 0); } }); logger.debug('Successfully fetched client values from shards.'); From f21bfbae6f900d800b3d8edd0808918630f00b18 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 18:35:52 +0200 Subject: [PATCH 22/24] fix: update Dockerfile and CI/CD workflows --- .github/workflows/docker_release.yml | 23 ++++++++++++++++++----- .github/workflows/node.js.yml | 3 ++- Dockerfile | 14 +++++++++++--- package-lock.json | 11 ----------- package.json | 4 ++-- 5 files changed, 33 insertions(+), 22 deletions(-) diff --git a/.github/workflows/docker_release.yml b/.github/workflows/docker_release.yml index cae845c..f17a283 100644 --- a/.github/workflows/docker_release.yml +++ b/.github/workflows/docker_release.yml @@ -12,6 +12,17 @@ jobs: - name: Checkout code uses: actions/checkout@v2 + - name: Setup Docker Buildx + uses: docker/setup-buildx-action@v1 + + - name: Cache Docker layers + uses: actions/cache@v2 + with: + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- + - name: Login to DockerHub uses: docker/login-action@v1 with: @@ -22,8 +33,10 @@ jobs: run: echo "RELEASE_VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV - name: Build and Push Docker Image - run: | - docker build -t mariusbegby/cadence:${{ env.RELEASE_VERSION }} . - docker tag mariusbegby/cadence:${{ env.RELEASE_VERSION }} mariusbegby/cadence:latest - docker push mariusbegby/cadence:${{ env.RELEASE_VERSION }} - docker push mariusbegby/cadence:latest + uses: docker/build-push-action@v2 + with: + context: . + push: true + tags: mariusbegby/cadence:${{ env.RELEASE_VERSION }}, mariusbegby/cadence:latest + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,dest=/tmp/.buildx-cache diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 36e6c78..05c3fa0 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -26,5 +26,6 @@ jobs: node-version: ${{ matrix.node-version }} cache: 'npm' - run: npm install -g npm@latest - - run: npm ci --legacy-peer-deps + - run: npm ci - run: npm run eslint + - run: npm run build diff --git a/Dockerfile b/Dockerfile index c4f5648..e60980d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,16 +13,24 @@ RUN apk add --no-cache python3 make build-base ffmpeg WORKDIR /cadence-discord-bot # Copy the rest of the source files into the image. -COPY . . +COPY package*.json ./ +COPY tsconfig.json ./ +COPY src/ ./src/ +COPY config/ ./config/ # Install dependencies from package-lock.json and omit dev dependencies # Leverage a cache mount to /root/.npm to speed up subsequent builds. RUN --mount=type=cache,target=/root/.npm \ + npm ci + +# Transpile TypeScript to JavaScript, remove dev dependencies, and install production dependencies +RUN npm run build && \ + rm -rf node_modules && \ npm ci --omit=dev -# Cleanup of unneeded packages and apk cache +# Cleanup of unneeded packages, apk cache, and TypeScript source files RUN apk del python3 make build-base && \ - rm -rf /var/cache/apk/* /tmp/* + rm -rf /var/cache/apk/* /tmp/* ./src/ # Startup command to run the bot after deploying slash commands CMD /bin/sh -c "npm run deploy && npm run start" diff --git a/package-lock.json b/package-lock.json index f2d867b..afebc98 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,7 +28,6 @@ "@types/config": "^3.3.0", "@types/node": "^20.5.6", "@types/node-os-utils": "^1.3.1", - "@types/pino": "^7.0.5", "@types/uuid": "^9.0.2", "@typescript-eslint/eslint-plugin": "^6.4.1", "eslint": "^8.47.0", @@ -480,16 +479,6 @@ "integrity": "sha512-gokG1AaQo78X3f1KXOPAfwbhERX95XL0nhosOhwFck0hZ3BG52Mfch3oj3gAhXuUsou3lwi+ewZWjDo0wshKwQ==", "dev": true }, - "node_modules/@types/pino": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/@types/pino/-/pino-7.0.5.tgz", - "integrity": "sha512-wKoab31pknvILkxAF8ss+v9iNyhw5Iu/0jLtRkUD74cNfOOLJNnqfFKAv0r7wVaTQxRZtWrMpGfShwwBjOcgcg==", - "deprecated": "This is a stub types definition. pino provides its own type definitions, so you do not need this installed.", - "dev": true, - "dependencies": { - "pino": "*" - } - }, "node_modules/@types/prettier": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.3.tgz", diff --git a/package.json b/package.json index 511b4ee..8a257b8 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,8 @@ "start-pretty-no-ignore": "node ./dist/index.js | pino-pretty", "deploy": "node ./dist/utils/deploySlashCommands.js", "deploy-pretty": "node ./dist/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId", - "eslint": "eslint ./src" + "eslint": "eslint ./src", + "build": "tsc" }, "dependencies": { "@discord-player/extractor": "^4.4.2-dev.1", @@ -46,7 +47,6 @@ "@types/config": "^3.3.0", "@types/node": "^20.5.6", "@types/node-os-utils": "^1.3.1", - "@types/pino": "^7.0.5", "@types/uuid": "^9.0.2", "@typescript-eslint/eslint-plugin": "^6.4.1", "eslint": "^8.47.0", From 1b00222ecf376a193302fb9d3323b9a1e7a9ea44 Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 18:36:50 +0200 Subject: [PATCH 23/24] chore: removed unused import --- src/commands/info/status.ts | 2 +- src/commands/system/systemstatus.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/commands/info/status.ts b/src/commands/info/status.ts index 41b3221..7105116 100644 --- a/src/commands/info/status.ts +++ b/src/commands/info/status.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { Collection, EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; +import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import osu from 'node-os-utils'; // @ts-ignore diff --git a/src/commands/system/systemstatus.ts b/src/commands/system/systemstatus.ts index 9585010..19c7a60 100644 --- a/src/commands/system/systemstatus.ts +++ b/src/commands/system/systemstatus.ts @@ -1,5 +1,5 @@ import config from 'config'; -import { Collection, EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; +import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js'; import osu from 'node-os-utils'; // @ts-ignore From 98f8d4338f4e73ff164f39c6f7ad12dccb16deea Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Sun, 27 Aug 2023 18:38:43 +0200 Subject: [PATCH 24/24] chore: initiate RELEASE_VERSION env var --- .github/workflows/docker_release.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/docker_release.yml b/.github/workflows/docker_release.yml index f17a283..e3f465d 100644 --- a/.github/workflows/docker_release.yml +++ b/.github/workflows/docker_release.yml @@ -1,5 +1,8 @@ name: Build and Push Docker Image on Release +env: + RELEASE_VERSION: + on: release: types: [published]