Merge pull request #196 from mariusbegby/something

fix: more type annotation
This commit is contained in:
Marius Begby authored and GitHub committed 2023-08-30 14:13:54 +02:00
commit d0f1e940a5
65 files changed
+408 -343

No files matched your search

+1 -1
View File
@@ -53,4 +53,4 @@
"prettier-eslint": "^15.0.1",
"typescript": "^5.2.2"
}
}
}
+5 -3
View File
@@ -9,9 +9,11 @@ import { createClient } from './utils/factory/createClient';
import { createPlayer } from './utils/factory/createPlayer';
import { registerClientCommands } from './utils/registerClientCommands';
import { registerEventListeners } from './utils/registerEventListeners';
import { Player } from 'discord-player';
import { Logger } from 'pino';
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'bot.js',
module: 'shardingClient',
name: 'shardingClient',
@@ -22,7 +24,7 @@ const logger = loggerModule.child({
(async () => {
try {
const client: ExtendedClient = await createClient({ executionId });
const player = await createPlayer({ client, executionId });
const player: Player = await createPlayer({ client, executionId });
client.on('allShardsReady', async () => {
client.registerClientCommands = registerClientCommands;
+3 -2
View File
@@ -2,14 +2,15 @@ import { Events } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { Logger } from 'pino';
module.exports = {
name: Events.Debug,
isDebug: true,
once: false,
execute: async (message: string) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'debug.js',
module: 'event',
name: 'clientDebug',
+4 -3
View File
@@ -5,6 +5,7 @@ import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { EmbedOptions, SystemOptions } from '../../types/configTypes';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
@@ -13,8 +14,8 @@ module.exports = {
isDebug: false,
once: false,
execute: async (client: ExtendedClient) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'disconnect.js',
module: 'event',
name: 'clientDisconnect',
@@ -26,7 +27,7 @@ module.exports = {
// send message to system message channel for event
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = (await client.channels.cache.get(
const channel: BaseGuildTextChannel = (await client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
+3 -2
View File
@@ -2,14 +2,15 @@ import { Events } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { Logger } from 'pino';
module.exports = {
name: Events.Error,
isDebug: false,
once: false,
execute: async (error: Error) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'error.js',
module: 'event',
name: 'clientError',
+3 -2
View File
@@ -2,14 +2,15 @@ import { Events, Guild } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { Logger } from 'pino';
module.exports = {
name: Events.GuildCreate,
isDebug: false,
once: false,
execute: async (guild: Guild) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'guildCreate.js',
module: 'event',
name: 'guildCreate',
+3 -2
View File
@@ -2,14 +2,15 @@ import { Events, Guild } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { Logger } from 'pino';
module.exports = {
name: Events.GuildDelete,
isDebug: false,
once: false,
execute: async (guild: Guild) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'guildDelete.js',
module: 'event',
name: 'guildDelete',
+6 -3
View File
@@ -2,6 +2,7 @@ import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder, Events, PresenceData } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { EmbedOptions, LoadTestOptions, SystemOptions } from '../../types/configTypes';
@@ -17,8 +18,8 @@ module.exports = {
isDebug: false,
once: false,
execute: async (client: ExtendedClient) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'ready.js',
module: 'event',
name: 'clientReady',
@@ -38,7 +39,9 @@ module.exports = {
}
}
const channel = (await client.channels.cache.get(systemOptions.systemMessageChannelId)) as BaseGuildTextChannel;
const channel: BaseGuildTextChannel = (await client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
// Check if the channel exists in curent shard and send a message
if (channel) {
+4 -3
View File
@@ -2,6 +2,7 @@ import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { EmbedOptions, SystemOptions } from '../../types/configTypes';
@@ -13,8 +14,8 @@ module.exports = {
isDebug: false,
once: false,
execute: async (client: ExtendedClient) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'reconnecting.js',
module: 'event',
name: 'clientReconnecting',
@@ -27,7 +28,7 @@ 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(
const channel: BaseGuildTextChannel = (await client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
+3 -3
View File
@@ -1,6 +1,6 @@
import { Events } from 'discord.js';
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
@@ -8,8 +8,8 @@ module.exports = {
isDebug: false,
once: false,
execute: async (warning: string) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'warn.js',
module: 'event',
name: 'clientWarn',
+5 -5
View File
@@ -6,8 +6,8 @@ import {
InteractionType,
MessageComponentInteraction
} from 'discord.js';
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import { handleAutocomplete } from '../../handlers/interactionAutocompleteHandler';
import { handleCommand } from '../../handlers/interactionCommandHandler';
import { handleComponent } from '../../handlers/interactionComponentHandler';
@@ -21,8 +21,8 @@ module.exports = {
isDebug: false,
execute: async (interaction: Interaction, { client }: { client: ExtendedClient }) => {
const inputTime: number = new Date().getTime();
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'interactionCreate.js',
module: 'event',
name: 'interactionCreate',
@@ -33,7 +33,7 @@ module.exports = {
logger.debug('Interaction received.');
let interactionIdentifier = 'Unknown';
let interactionIdentifier: string = 'Unknown';
if (
interaction.type === InteractionType.ApplicationCommand ||
interaction.type === InteractionType.ApplicationCommandAutocomplete
@@ -73,7 +73,7 @@ module.exports = {
const outputTime: number = new Date().getTime();
const executionTime: number = outputTime - inputTime;
const interactionType = InteractionType[interaction.type];
const interactionType: string = InteractionType[interaction.type];
logger.info(
{
+3 -3
View File
@@ -1,5 +1,5 @@
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
@@ -7,8 +7,8 @@ module.exports = {
isDebug: true,
isPlayerEvent: false,
execute: async (message: string) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'generalDebug.js',
module: 'event',
name: 'playerGeneralDebug',
+4 -4
View File
@@ -1,7 +1,7 @@
import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes';
import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes';
@@ -15,8 +15,8 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue: ExtendedGuildQueuePlayerNode, error: Error) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'generalError.js',
module: 'event',
name: 'playerGeneralError',
@@ -39,7 +39,7 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = (await queue.metadata?.client.channels.cache.get(
const channel: BaseGuildTextChannel = (await queue.metadata?.client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
+3 -3
View File
@@ -1,5 +1,5 @@
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
@@ -7,8 +7,8 @@ module.exports = {
isDebug: true,
isPlayerEvent: true,
execute: async (message: string) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'playerDebug.js',
module: 'event',
name: 'playerDebug',
+4 -4
View File
@@ -1,7 +1,7 @@
import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes';
import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes';
@@ -15,8 +15,8 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue: ExtendedGuildQueuePlayerNode, error: Error) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'playerError.js',
module: 'event',
name: 'playerError',
@@ -39,7 +39,7 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = (await queue.metadata?.client.channels.cache.get(
const channel: BaseGuildTextChannel = (await queue.metadata?.client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
+4 -4
View File
@@ -1,8 +1,8 @@
import config from 'config';
import { Track } from 'discord-player';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes';
import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes';
@@ -16,8 +16,8 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue: ExtendedGuildQueuePlayerNode, track: Track) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'playerSkip.js',
module: 'event',
name: 'playerSkip',
@@ -40,7 +40,7 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = (await queue.metadata?.client.channels.cache.get(
const channel: BaseGuildTextChannel = (await queue.metadata?.client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
+3 -3
View File
@@ -1,6 +1,6 @@
import { Track } from 'discord-player';
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes';
@@ -9,8 +9,8 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue: ExtendedGuildQueuePlayerNode, track: Track) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'playerStart.js',
module: 'event',
name: 'playerStart',
+3 -3
View File
@@ -1,13 +1,13 @@
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: 'uncaughtException',
isDebug: false,
execute: async (error: Error) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'uncaughtException.js',
module: 'event',
name: 'uncaughtException',
+3 -3
View File
@@ -1,13 +1,13 @@
import { Logger } from 'pino';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: 'unhandledRejection',
isDebug: false,
execute: async (error: Error) => {
const executionId = uuidv4();
const logger = loggerModule.child({
const executionId: string = uuidv4();
const logger: Logger = loggerModule.child({
source: 'unhandledRejection.js',
module: 'event',
name: 'unhandledRejection',
@@ -1,14 +1,17 @@
import { AutocompleteInteraction } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../services/logger';
export const handleAutocomplete = async (interaction: AutocompleteInteraction, executionId: string) => {
const logger = loggerModule.child({
// TODO: Define TS Type for handlers, and require logger constant?
const logger: Logger = loggerModule.child({
source: 'interactionCutocompleteHandler.ts',
module: 'handler',
name: 'interactionAutocompleteHandler',
executionId: executionId
});
// TODO: Create TS Type for autocompleteModule
const autocompleteModule = await import(`../interactions/autocomplete/${interaction.commandName}.js`);
const { default: autocomplete } = autocompleteModule;
+5 -3
View File
@@ -1,14 +1,15 @@
import { ChatInputCommandInteraction } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../services/logger';
import { Command, ExtendedClient } from '../types/clientTypes';
import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator';
import loggerModule from '../services/logger';
export const handleCommand = async (
interaction: ChatInputCommandInteraction,
client: ExtendedClient,
executionId: string
) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'interactionCommandHandler.ts',
module: 'handler',
name: 'interactionCommandHandler',
@@ -18,7 +19,8 @@ export const handleCommand = async (
await interaction.deferReply();
logger.debug('Interaction deferred.');
const command = client.commands?.get(interaction.commandName) as Command;
// TODO: Update TS Type for command
const command: Command = client.commands?.get(interaction.commandName) as Command;
if (!command) {
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
return;
+5 -3
View File
@@ -1,9 +1,10 @@
import { MessageComponentInteraction } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../services/logger';
import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator';
export const handleComponent = async (interaction: MessageComponentInteraction, executionId: string) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'interactionComponentHandler.js',
module: 'handler',
name: 'interactionComponentHandler',
@@ -13,8 +14,8 @@ export const handleComponent = async (interaction: MessageComponentInteraction,
await interaction.deferReply();
logger.debug('Interaction deferred.');
const componentId = interaction.customId.split('_')[0];
const referenceId = interaction.customId.split('_')[1];
const componentId: string = interaction.customId.split('_')[0];
const referenceId: string = interaction.customId.split('_')[1];
logger.debug(`Parsed componentId: ${componentId}`);
@@ -22,6 +23,7 @@ export const handleComponent = async (interaction: MessageComponentInteraction,
return;
}
// TODO: Create TS Type for component
const componentModule = await import(`../interactions/components/${componentId}.js`);
const { default: component } = componentModule;
+8 -4
View File
@@ -1,25 +1,29 @@
import config from 'config';
import { ChatInputCommandInteraction, EmbedBuilder, Interaction, MessageComponentInteraction } from 'discord.js';
import { BotOptions, EmbedOptions } from '../types/configTypes';
import { ChatInputCommandInteraction, EmbedBuilder, Interaction, InteractionReplyOptions, MessageComponentInteraction } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../services/logger';
import { BotOptions, EmbedOptions } from '../types/configTypes';
import { CustomError } from '../types/interactionTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
// TODO: Update TS Type for handlError
export const handleError = async (
interaction: Interaction,
error: CustomError,
interactionIdentifier: string,
executionId: string
) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'interactionErrorHandler.ts',
module: 'handler',
name: 'interactionErrorHandler',
executionId: executionId
});
const errorReply = {
// TODO: Extract replies for embeds
const errorReply: InteractionReplyOptions = {
embeds: [
new EmbedBuilder()
.setDescription(
+5 -4
View File
@@ -4,22 +4,23 @@ import config from 'config';
import { Client, Shard, ShardEvents, ShardingManager } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import { Logger } from 'pino';
import loggerModule from './services/logger';
import { ShardingOptions } from './types/configTypes';
const shardingOptions: ShardingOptions = config.get('shardingOptions');
const manager = new ShardingManager('./dist/bot.js', {
const manager: ShardingManager = new ShardingManager('./dist/bot.js', {
token: process.env.DISCORD_BOT_TOKEN,
...shardingOptions
});
const readyShards = new Set();
const readyShards: Set<number> = new Set();
manager.on('shardCreate', (shard: Shard) => {
const executionId = uuidv4();
const executionId: string = uuidv4();
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'index.js',
module: 'shardingManager',
name: 'shardingManager',
+14 -10
View File
@@ -1,27 +1,30 @@
import { useMainPlayer } from 'discord-player';
import { LyricsData, lyricsExtractor } from '@discord-player/extractor';
import { Player, SearchResult, useMainPlayer } from 'discord-player';
import { ApplicationCommandOptionChoiceData } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { CustomAutocompleteInteraction } from '../../types/interactionTypes';
import { lyricsExtractor } from '@discord-player/extractor';
const loggerTemplate = loggerModule.child({
const loggerTemplate: Logger = loggerModule.child({
source: 'lyrics.js',
module: 'autocompleteInteraction',
name: '/lyrics'
});
// TODO: create interface for recent query object
const recentQueries = new Map();
const autocomplete: CustomAutocompleteInteraction = {
execute: async ({ interaction, executionId }) => {
const logger = loggerTemplate.child({
const logger: Logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const query = interaction.options.getString('query', true);
const query: string = interaction.options.getString('query', true);
const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {};
const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id);
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
logger.debug(`Responding with results from lastQuery for query '${query}'`);
@@ -34,13 +37,14 @@ const autocomplete: CustomAutocompleteInteraction = {
}
const genius = lyricsExtractor();
const lyricsResult = await genius.search(query).catch(() => null);
let response = [];
const lyricsResult: LyricsData = (await genius.search(query).catch(() => null)) as LyricsData;
// TODO: Update TS Type for lyricsResult and create response object interface
let response: ApplicationCommandOptionChoiceData<string>[] = [];
if (!lyricsResult) {
logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`);
const player = useMainPlayer()!;
const searchResults = await player.search(query);
const player: Player = useMainPlayer()!;
const searchResults: SearchResult = await player.search(query);
response = searchResults.tracks.slice(0, 1).map((track) => ({
name:
`${track.title} [Artist: ${track.author}]`.length > 100
+10 -7
View File
@@ -1,25 +1,28 @@
import { useMainPlayer } from 'discord-player';
import { Player, SearchResult, useMainPlayer } from 'discord-player';
import { ApplicationCommandOptionChoiceData } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { CustomAutocompleteInteraction } from '../../types/interactionTypes';
const loggerTemplate = loggerModule.child({
const loggerTemplate: Logger = loggerModule.child({
source: 'play.js',
module: 'autocompleteInteraction',
name: '/play'
});
// TODO: create interface for recent query object
const recentQueries = new Map();
const autocomplete: CustomAutocompleteInteraction = {
execute: async ({ interaction, executionId }) => {
const logger = loggerTemplate.child({
const logger: Logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const player = useMainPlayer()!;
const query = interaction.options.getString('query', true);
const player: Player = useMainPlayer()!;
const query: string = interaction.options.getString('query', true);
const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {};
@@ -32,9 +35,9 @@ const autocomplete: CustomAutocompleteInteraction = {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const searchResults = await player.search(query);
const searchResults: SearchResult = await player.search(query);
let response = [];
let response: ApplicationCommandOptionChoiceData<string>[] = [];
response = searchResults.tracks.slice(0, 5).map((track) => {
if (track.url.length > 100) {
+10 -9
View File
@@ -1,9 +1,9 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { BotOptions, EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
@@ -17,7 +17,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'help.js',
module: 'slashCommand',
name: '/help',
@@ -26,6 +26,7 @@ const command: CustomSlashCommandInteraction = {
guildId: interaction.guild?.id
});
// TODO: Create interface for command list
const commandList = client!.commands!
.filter((command) => {
// don't include system commands
@@ -35,18 +36,18 @@ const command: CustomSlashCommandInteraction = {
return true;
})
.map((command) => {
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} ` : '';
const params: string = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
const beta: string = command.isBeta ? `${embedOptions.icons.beta} ` : '';
const newCommand: string = command.isNew ? `${embedOptions.icons.new} ` : '';
return `- **\`/${command.data.name}\`** ${params}- ${beta}${newCommand}${command.data.description}`;
});
const commandListString = commandList.join('\n');
const commandListString: string = commandList.join('\n');
const supportServerString = botOptions.serverInviteUrl
const supportServerString: string = botOptions.serverInviteUrl
? `${embedOptions.icons.support} **Support server**\nJoin the support server for help or to suggest improvements: \n**${botOptions.serverInviteUrl}**\n\n`
: '';
const addBotString = botOptions.botInviteUrl
const addBotString: string = botOptions.botInviteUrl
? `${embedOptions.icons.bot} **Enjoying ${botOptions.name}?**\nAdd me to another server: \n**[Click me!](${botOptions.botInviteUrl})**`
: '';
+9 -9
View File
@@ -1,13 +1,13 @@
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import osu from 'node-os-utils';
import { Logger } from 'pino';
// @ts-ignore
import { version } from '../../../../package.json';
import loggerModule from '../../../services/logger';
import { EmbedOptions } from '../../../types/configTypes';
import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted';
const embedOptions: EmbedOptions = config.get('embedOptions');
@@ -20,7 +20,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'status.js',
module: 'slashCommand',
name: '/status',
@@ -29,10 +29,10 @@ const command: CustomSlashCommandInteraction = {
guildId: interaction.guild?.id
});
const uptimeString = await getUptimeFormatted({ executionId });
const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
const cpuUsage = await osu.cpu.usage();
const releaseVersion = version;
const uptimeString: string = await getUptimeFormatted({ executionId });
const usedMemoryInMB: string = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
const cpuUsage: number = await osu.cpu.usage();
const releaseVersion: string = version;
let guildCount: number = 0;
let memberCount: number = 0;
let activeVoiceConnections: number = 0;
@@ -62,7 +62,7 @@ const command: CustomSlashCommandInteraction = {
await client!
.shard!.fetchClientValues('guilds.cache')
.then((results) => {
const guildCaches = results as Guild[][];
const guildCaches: Guild[][] = results as Guild[][];
guildCaches.map((guildCache: Guild[]) => {
if (guildCache) {
guildCount += guildCache.length;
@@ -89,7 +89,7 @@ const command: CustomSlashCommandInteraction = {
const systemStatusString =
`**${uptimeString}** Uptime\n` + `**${cpuUsage}%** CPU usage\n` + `**${usedMemoryInMB} MB** Memory usage`;
const discordStatusString = `**${client!.ws.ping} ms** Discord API latency`;
const discordStatusString: string = `**${client!.ws.ping} ms** Discord API latency`;
logger.debug('Transformed status into into embed description.');
+8 -6
View File
@@ -2,7 +2,9 @@ import config from 'config';
import { GuildQueue, QueueFilters, useQueue } from 'discord-player';
import {
APIActionRowComponent,
APIButtonComponent,
APIMessageActionRowComponent,
APIStringSelectComponent,
ButtonBuilder,
ButtonStyle,
ComponentType,
@@ -11,10 +13,10 @@ import {
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder
} from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
@@ -30,7 +32,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'filters.js',
module: 'slashCommand',
name: '/filters',
@@ -57,7 +59,7 @@ const command: CustomSlashCommandInteraction = {
const filterOptions: StringSelectMenuOptionBuilder[] = [];
ffmpegFilterOptions.availableFilters.forEach((filter: FFmpegFilterOption) => {
let isEnabled = false;
let isEnabled: boolean = false;
if (queue.filters.ffmpeg.filters.includes(filter.value as keyof QueueFilters)) {
isEnabled = true;
@@ -73,7 +75,7 @@ const command: CustomSlashCommandInteraction = {
);
});
const filterSelect = new StringSelectMenuBuilder()
const filterSelect: APIStringSelectComponent = new StringSelectMenuBuilder()
.setCustomId('filters-select-menu')
.setPlaceholder('Select multiple options.')
.setMinValues(0)
@@ -86,7 +88,7 @@ const command: CustomSlashCommandInteraction = {
components: [filterSelect]
};
const disableButton = new ButtonBuilder()
const disableButton: APIButtonComponent = new ButtonBuilder()
.setCustomId('filters-disable-button')
.setLabel('Disable all filters')
.setStyle(ButtonStyle.Secondary)
+4 -4
View File
@@ -1,12 +1,12 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
@@ -19,7 +19,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'leave.js',
module: 'slashCommand',
name: '/leave',
+10 -9
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { GuildQueue, QueueRepeatMode, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder, SlashCommandStringOption } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { BotOptions, EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
@@ -32,7 +32,7 @@ const command: CustomSlashCommandInteraction = {
)
),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'loop.js',
module: 'slashCommand',
name: '/loop',
@@ -55,17 +55,18 @@ const command: CustomSlashCommandInteraction = {
}
}
const loopModesFormatted = new Map([
// TODO: create type for loop modes formatted
const loopModesFormatted: Map<number, string> = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const mode = parseInt(interaction.options.getString('mode')!);
const modeUserString = loopModesFormatted.get(mode);
const currentMode = queue.repeatMode;
const currentModeUserString = loopModesFormatted.get(currentMode);
const mode: number = parseInt(interaction.options.getString('mode')!);
const modeUserString: string = loopModesFormatted.get(mode)!;
const currentMode: QueueRepeatMode = queue.repeatMode;
const currentModeUserString: string = loopModesFormatted.get(currentMode)!;
if (!mode && mode !== 0) {
logger.debug('No mode input was provided, responding with current loop mode.');
+12 -11
View File
@@ -1,18 +1,19 @@
import config from 'config';
import { GuildQueue, QueryType, useMainPlayer, useQueue } from 'discord-player';
import { GuildQueue, Player, QueryType, useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { lyricsExtractor } from '@discord-player/extractor';
import { LyricsData, lyricsExtractor } from '@discord-player/extractor';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
const loggerTemplate = loggerModule.child({
const loggerTemplate: Logger = loggerModule.child({
source: 'lyrics.js',
module: 'slashCommand',
name: '/lyrics'
@@ -36,15 +37,15 @@ const command: CustomSlashCommandInteraction = {
.setAutocomplete(true)
),
execute: async ({ interaction, executionId }) => {
const logger = loggerTemplate.child({
const logger: Logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const query = interaction.options.getString('query');
const query: string = interaction.options.getString('query')!;
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
let geniusSearchQuery = '';
let geniusSearchQuery: string = '';
if (!query) {
const validators = [
@@ -70,7 +71,7 @@ const command: CustomSlashCommandInteraction = {
let searchResult;
if (query) {
logger.debug(`Query input provided, using query '${query}' for player.search().`);
const player = useMainPlayer()!;
const player: Player = useMainPlayer()!;
const searchResults = await player.search(query, {
searchEngine: QueryType.SPOTIFY_SEARCH
});
@@ -97,7 +98,7 @@ const command: CustomSlashCommandInteraction = {
// get lyrics
const genius = lyricsExtractor();
let lyricsResult = await genius.search(geniusSearchQuery).catch(() => null);
let lyricsResult: LyricsData | null = await genius.search(geniusSearchQuery).catch(() => null);
// try again with shorter query (some titles just have added info in the end)
if (!lyricsResult && geniusSearchQuery.length > 20) {
@@ -155,10 +156,10 @@ const command: CustomSlashCommandInteraction = {
// If message length is too long, split into multiple messages
if (lyricsResult.lyrics.length > 3800) {
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++) {
const messageCount: number = Math.ceil(lyricsResult.lyrics.length / 3800);
for (let i: number = 0; i < messageCount; i++) {
logger.debug(`Lyrics, sending message ${i + 1} of ${messageCount}.`);
const message = lyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800);
const message: string = lyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800);
if (i === 0) {
logger.debug('Responding with info embed for first message with lyrics.');
await interaction.editReply({
+18 -15
View File
@@ -1,7 +1,8 @@
import config from 'config';
import { GuildQueue, Track, useQueue } from 'discord-player';
import { GuildQueue, PlayerTimestamp, Track, useQueue } from 'discord-player';
import {
APIActionRowComponent,
APIButtonComponent,
APIMessageActionRowComponent,
ButtonBuilder,
ButtonStyle,
@@ -15,6 +16,7 @@ import { CustomSlashCommandInteraction, TrackMetadata } from '../../../types/int
import { EmbedOptions, PlayerOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
@@ -28,7 +30,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'nowplaying.js',
module: 'slashCommand',
name: '/nowplaying',
@@ -39,6 +41,7 @@ const command: CustomSlashCommandInteraction = {
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
// TODO: define TS type/interface for validators
const validators = [
() => notInVoiceChannel({ interaction, executionId }),
() => notInSameVoiceChannel({ interaction, queue, executionId }),
@@ -52,7 +55,7 @@ const command: CustomSlashCommandInteraction = {
}
}
const sourceStringsFormatted = new Map([
const sourceStringsFormatted: Map<string, string> = new Map([
['youtube', 'YouTube'],
['soundcloud', 'SoundCloud'],
['spotify', 'Spotify'],
@@ -60,7 +63,7 @@ const command: CustomSlashCommandInteraction = {
['arbitrary', 'Direct source']
]);
const sourceIcons = new Map([
const sourceIcons: Map<string, string> = new Map([
['youtube', embedOptions.icons.sourceYouTube],
['soundcloud', embedOptions.icons.sourceSoundCloud],
['spotify', embedOptions.icons.sourceSpotify],
@@ -70,15 +73,15 @@ const command: CustomSlashCommandInteraction = {
const currentTrack: Track = queue.currentTrack!;
let author = currentTrack.author ? currentTrack.author : 'Unavailable';
let author: string = currentTrack.author ? currentTrack.author : 'Unavailable';
if (author === 'cdn.discordapp.com') {
author = 'Unavailable';
}
const plays = currentTrack.views !== 0 ? currentTrack.views : 0;
const plays: number = currentTrack.views !== 0 ? currentTrack.views : 0;
let displayPlays: string = plays.toLocaleString('en-US');
const metadata = currentTrack.metadata as TrackMetadata;
const metadata: TrackMetadata = currentTrack.metadata as TrackMetadata;
if (plays === 0 && metadata.bridge && metadata.bridge.views !== 0 && metadata.bridge.views !== undefined) {
displayPlays = metadata.bridge.views.toLocaleString('en-US');
@@ -86,10 +89,10 @@ const command: CustomSlashCommandInteraction = {
displayPlays = 'Unavailable';
}
const source = sourceStringsFormatted.get(currentTrack.raw.source!) ?? 'Unavailable';
const queueLength = queue.tracks.data.length;
const timestamp = queue.node.getTimestamp()!;
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
const source: string = sourceStringsFormatted.get(currentTrack.raw.source!) ?? 'Unavailable';
const queueLength: number = queue.tracks.data.length;
const timestamp: PlayerTimestamp = queue.node.getTimestamp()!;
let bar: string = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false,
length: playerOptions.progressBar.length ?? 12,
timecodes: playerOptions.progressBar.timecodes ?? false,
@@ -106,10 +109,10 @@ const command: CustomSlashCommandInteraction = {
bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
}
const customId = `nowplaying-skip-button_${currentTrack.id}`;
const customId: string = `nowplaying-skip-button_${currentTrack.id}`;
logger.debug(`Generated custom id for skip button: ${customId}`);
const nowPlayingButton = new ButtonBuilder()
const nowPlayingButton: APIButtonComponent = new ButtonBuilder()
.setCustomId(customId)
.setLabel('Skip track')
.setStyle(ButtonStyle.Secondary)
@@ -121,14 +124,14 @@ const command: CustomSlashCommandInteraction = {
components: [nowPlayingButton]
};
const loopModesFormatted = new Map([
const loopModesFormatted: Map<number, string> = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
const loopModeUserString: string = loopModesFormatted.get(queue.repeatMode)!;
logger.debug('Successfully retrieved information about the current track.');
+5 -5
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { GuildQueue, Track, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
@@ -19,7 +19,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'pause.js',
module: 'slashCommand',
name: '/pause',
@@ -43,7 +43,7 @@ const command: CustomSlashCommandInteraction = {
}
}
const currentTrack = queue.currentTrack!;
const currentTrack: Track = queue.currentTrack!;
let durationFormat =
Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00'
+2 -1
View File
@@ -8,12 +8,13 @@ import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTy
import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator';
import { transformQuery } from '../../../utils/validation/searchQueryValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
const loggerTemplate = loggerModule.child({
const loggerTemplate: Logger = loggerModule.child({
source: 'play.js',
module: 'slashCommand',
name: '/play'
+15 -15
View File
@@ -1,12 +1,12 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { GuildQueue, PlayerTimestamp, Track, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions, PlayerOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
@@ -21,7 +21,7 @@ const command: CustomSlashCommandInteraction = {
.setNSFW(false)
.addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'queue.js',
module: 'slashCommand',
name: '/queue',
@@ -44,11 +44,11 @@ const command: CustomSlashCommandInteraction = {
}
}
const pageIndex = (interaction.options.getNumber('page') || 1) - 1;
let queueString = '';
const pageIndex: number = (interaction.options.getNumber('page') || 1) - 1;
let queueString: string = '';
const queueLength = queue.tracks.data.length;
const totalPages = Math.ceil(queueLength / 10) || 1;
const queueLength: number = queue.tracks.data.length;
const totalPages: number = Math.ceil(queueLength / 10) || 1;
if (pageIndex > totalPages - 1) {
logger.debug('Specified page was higher than total pages.');
@@ -88,7 +88,7 @@ const command: CustomSlashCommandInteraction = {
.join('\n');
}
const currentTrack = queue.currentTrack;
const currentTrack: Track = queue.currentTrack!;
const loopModesFormatted = new Map([
[0, 'disabled'],
@@ -97,9 +97,9 @@ const command: CustomSlashCommandInteraction = {
[3, 'autoplay']
]);
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
const loopModeUserString: string = loopModesFormatted.get(queue.repeatMode)!;
const repeatModeString = `${
const repeatModeString: string = `${
queue.repeatMode === 0
? ''
: `**${
@@ -129,8 +129,8 @@ const command: CustomSlashCommandInteraction = {
});
} else {
logger.debug('Queue exists with current track, gathering information.');
const timestamp = queue.node.getTimestamp()!;
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
const timestamp: PlayerTimestamp = queue.node.getTimestamp()!;
let bar: string = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false,
length: playerOptions.progressBar.length ?? 12,
timecodes: playerOptions.progressBar.timecodes ?? false,
@@ -165,7 +165,7 @@ const command: CustomSlashCommandInteraction = {
`${repeatModeString}` +
`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`
)
.setThumbnail(queue.currentTrack.thumbnail)
.setThumbnail(currentTrack.thumbnail)
.setFooter({
text: `Page ${pageIndex + 1} of ${totalPages} (${queueLength} tracks)`
})
+6 -6
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { GuildQueue, Track, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
@@ -26,7 +26,7 @@ const command: CustomSlashCommandInteraction = {
.setRequired(true)
),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'remove.js',
module: 'slashCommand',
name: '/remove',
@@ -49,7 +49,7 @@ const command: CustomSlashCommandInteraction = {
}
}
const removeTrackNumber = interaction.options.getNumber('tracknumber')!;
const removeTrackNumber: number = interaction.options.getNumber('tracknumber')!;
if (removeTrackNumber > queue.tracks.data.length) {
logger.debug('Specified track number is higher than total tracks.');
@@ -67,7 +67,7 @@ const command: CustomSlashCommandInteraction = {
}
// Remove specified track number from queue
const removedTrack = queue.node.remove(removeTrackNumber - 1)!;
const removedTrack: Track = queue.node.remove(removeTrackNumber - 1)!;
logger.debug(`Removed track '${removedTrack.url}' from queue.`);
let durationFormat =
Number(removedTrack.raw.duration) === 0 || removedTrack.duration === '0:00'
+10 -10
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
@@ -25,7 +25,7 @@ const command: CustomSlashCommandInteraction = {
.setRequired(true)
),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'seek.js',
module: 'slashCommand',
name: '/seek',
@@ -49,9 +49,9 @@ const command: CustomSlashCommandInteraction = {
}
}
const durationInput = interaction.options.getString('duration');
const durationInput: string = interaction.options.getString('duration')!;
let durationArray = durationInput!.split(':');
let durationArray: string[] = durationInput!.split(':');
switch (durationArray.length) {
case 1:
@@ -68,7 +68,7 @@ const command: CustomSlashCommandInteraction = {
return value.padStart(2, '0');
});
const durationString = durationArray.join(':');
const durationString: string = durationArray.join(':');
if (durationArray.length === 0 || durationArray.length > 3) {
logger.debug('Invalid duration format input.');
@@ -88,7 +88,7 @@ const command: CustomSlashCommandInteraction = {
});
}
const validElements = durationArray.every((value) => {
const validElements: boolean = durationArray.every((value) => {
return value.length === 2;
});
@@ -112,8 +112,8 @@ const command: CustomSlashCommandInteraction = {
// Now array should only be 3 elements long, all with 2 characters, e.g. ['00', '00', '00'].
// Regex can now validate if this is a valid duration format. E.g. check if the first element is 0-23, second element is 0-59 and third element is 0-59.
const regex = new RegExp('([0-1][0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]');
const isValidDuration = regex.test(durationString);
const regex: RegExp = new RegExp('([0-1][0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]');
const isValidDuration: boolean = regex.test(durationString);
if (!isValidDuration) {
logger.debug('Invalid duration after regex checks.');
@@ -133,7 +133,7 @@ const command: CustomSlashCommandInteraction = {
});
}
const currentTrackMaxDurationInMs = queue.currentTrack!.durationMS;
const currentTrackMaxDurationInMs: number = queue.currentTrack!.durationMS;
const durationInMilliseconds: number =
Number(durationArray[0]) * 3600000 + Number(durationArray[1]) * 60000 + Number(durationArray[2]) * 1000;
+3 -3
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist, queueIsEmpty } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
@@ -19,7 +19,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'shuffle.js',
module: 'slashCommand',
name: '/shuffle',
+9 -9
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { GuildQueue, Track, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
@@ -22,7 +22,7 @@ const command: CustomSlashCommandInteraction = {
option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1)
),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'skip.js',
module: 'slashCommand',
name: '/skip',
@@ -46,7 +46,7 @@ const command: CustomSlashCommandInteraction = {
}
}
const skipToTrack = interaction.options.getNumber('tracknumber');
const skipToTrack: number = interaction.options.getNumber('tracknumber')!;
if (skipToTrack) {
if (skipToTrack > queue.tracks.data.length) {
@@ -63,7 +63,7 @@ const command: CustomSlashCommandInteraction = {
]
});
} else {
const skippedTrack = queue.currentTrack!;
const skippedTrack: Track = queue.currentTrack!;
logger.debug('Responding with warning embed.');
let durationFormat =
@@ -120,7 +120,7 @@ const command: CustomSlashCommandInteraction = {
});
}
const skippedTrack = queue.currentTrack!;
const skippedTrack: Track = queue.currentTrack!;
let durationFormat =
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
@@ -133,14 +133,14 @@ const command: CustomSlashCommandInteraction = {
queue.node.skip();
logger.debug('Skipped current track.');
const loopModesFormatted = new Map([
const loopModesFormatted: Map<number, string> = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
const loopModeUserString: string = loopModesFormatted.get(queue.repeatMode)!;
let authorName: string;
+4 -4
View File
@@ -1,12 +1,12 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
@@ -19,7 +19,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'stop.js',
module: 'slashCommand',
name: '/stop',
+5 -5
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
@@ -26,7 +26,7 @@ const command: CustomSlashCommandInteraction = {
.setMaxValue(100)
),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'volume.js',
module: 'slashCommand',
name: '/volume',
@@ -49,10 +49,10 @@ const command: CustomSlashCommandInteraction = {
}
}
const volume = interaction.options.getNumber('percentage');
const volume: number = interaction.options.getNumber('percentage')!;
if (!volume && volume !== 0) {
const currentVolume = queue.node.volume;
const currentVolume: number = queue.node.volume;
logger.debug('No volume input was provided, showing current volume.');
+6 -6
View File
@@ -1,9 +1,9 @@
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
@@ -18,7 +18,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'guilds.js',
module: 'slashCommand',
name: '/guilds',
@@ -32,7 +32,7 @@ const command: CustomSlashCommandInteraction = {
}
let shardGuilds: Guild[] = [];
let totalGuildCount = 0;
let totalGuildCount: number = 0;
logger.debug('Fetching guilds from all shards.');
await client!.shard!
@@ -49,7 +49,7 @@ const command: CustomSlashCommandInteraction = {
logger.debug(`Successfully fetched ${totalGuildCount} guilds.`);
const guildListFormatted = shardGuilds
const guildListFormatted: string = shardGuilds
.map((guild) => {
return {
name: guild.name,
@@ -61,7 +61,7 @@ const command: CustomSlashCommandInteraction = {
.map((guild, index) => `${index + 1}. \`${guild.name} (#${guild.memberCount})\``)
.join('\n');
const totalMemberCount = shardGuilds.reduce((a, b) => a + b.memberCount, 0);
const totalMemberCount: number = shardGuilds.reduce((a, b) => a + b.memberCount, 0);
let embedDescription =
`**${embedOptions.icons.bot} ${
+6 -6
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { ExtendedClient } from '../../../types/clientTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
@@ -19,7 +19,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'reload.js',
module: 'slashCommand',
name: '/reload',
@@ -61,12 +61,12 @@ const command: CustomSlashCommandInteraction = {
});
}
const commands = client!.commands?.map((command) => {
const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
const commands: string[] | undefined = client!.commands?.map((command) => {
const params: string = 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: string = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands?.join('\n');
logger.debug('Responding with success embed.');
return await interaction.editReply({
+17 -16
View File
@@ -1,10 +1,10 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { EmbedBuilder, EmbedField, SlashCommandBuilder } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../../services/logger';
import { ExtendedClient } from '../../../types/clientTypes';
import { ShardInfo, CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { CustomSlashCommandInteraction, ShardInfo } from '../../../types/interactionTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
@@ -36,7 +36,7 @@ const command: CustomSlashCommandInteraction = {
.addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)),
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'shards.js',
module: 'slashCommand',
name: '/shards',
@@ -55,12 +55,13 @@ const command: CustomSlashCommandInteraction = {
try {
await client!
.shard!.broadcastEval((shardClient: ExtendedClient) => {
/* eslint-disable no-undef */
// Type for generateStatistics?
const playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = parseFloat(
const nodeProcessMemUsageInMb: number = parseFloat(
(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)
);
// TODO: Create shardInfo type
const shardInfo = {
shardId: shardClient.shard!.ids[0],
memUsage: nodeProcessMemUsageInMb,
@@ -129,17 +130,17 @@ const command: CustomSlashCommandInteraction = {
});
}
const shardCount = shardInfoList.length;
const totalPages = Math.ceil(shardCount / 10) || 1;
const pageIndex = (interaction.options.getNumber('page') || 1) - 1;
const shardCount: number = shardInfoList.length;
const totalPages:number = Math.ceil(shardCount / 10) || 1;
const pageIndex:number = (interaction.options.getNumber('page') || 1) - 1;
const currentPageShards = shardInfoList.slice(pageIndex * 10, pageIndex * 10 + 10);
const currentPageShards: ShardInfo[] = shardInfoList.slice(pageIndex * 10, pageIndex * 10 + 10);
const evenShardIndexes = currentPageShards.filter((shard, index) => index % 2 === 0);
const oddShardIndexes = currentPageShards.filter((shard, index) => index % 2 !== 0);
const evenShardIndexes: ShardInfo[] = currentPageShards.filter((shard, index) => index % 2 === 0);
const oddShardIndexes: ShardInfo[] = currentPageShards.filter((shard, index) => index % 2 !== 0);
function shardInfoToString(shard: ShardInfo) {
let string = '';
let string: string = '';
string += `**Shard ${shard.shardId}** - Guilds: ${shard.guildCount.toLocaleString(
'en-US'
)} (${shard.guildMemberCount.toLocaleString('en-US')})\n`;
@@ -150,10 +151,10 @@ const command: CustomSlashCommandInteraction = {
return string;
}
const evenShardIndexesString = evenShardIndexes.map(shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ';
const oddShardIndexesString = oddShardIndexes.map(shardInfoToString).join('\n');
const evenShardIndexesString: string = evenShardIndexes.map(shardInfoToString).join('\n') + 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ';
const oddShardIndexesString: string = oddShardIndexes.map(shardInfoToString).join('\n');
const embedFields = [];
const embedFields: EmbedField[] = [];
if (currentPageShards.length === 1) {
embedFields.push({
@@ -1,7 +1,6 @@
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import osu from 'node-os-utils';
// @ts-ignore
import { dependencies, version } from '../../../../package.json';
import loggerModule from '../../../services/logger';
@@ -9,6 +8,7 @@ import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
@@ -22,7 +22,7 @@ const command: CustomSlashCommandInteraction = {
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'systemstatus.js',
module: 'slashCommand',
name: '/systemstatus',
@@ -36,28 +36,28 @@ const command: CustomSlashCommandInteraction = {
}
// from normal /status command
const uptimeString = await getUptimeFormatted({ executionId });
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;
const uptimeString: string = await getUptimeFormatted({ executionId });
const usedMemoryInMB: string = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
const cpuUsage: number = await osu.cpu.usage();
const releaseVersion: string = version;
let guildCount: number = 0;
let memberCount: number = 0;
let activeVoiceConnections: number = 0;
let totalTracks: number = 0;
let totalListeners: number = 0;
// specific to /systemstatus command
const totalMemoryInMb = Math.ceil((await osu.mem.info()).totalMemMb).toLocaleString('en-US');
const cpuCores = await osu.cpu.count();
const platform = await osu.os.platform();
const discordJsVersion = dependencies['discord.js'];
const opusVersion = dependencies['@discord-player/opus'];
const restVersion = dependencies['@discordjs/rest'];
const voiceVersion = dependencies['discord-voip'];
const discordPlayerVersion = dependencies['discord-player'];
const extractorVersion = dependencies['@discord-player/extractor'];
const mediaplexVersion = dependencies['mediaplex'];
const distubeYtdlVersion = dependencies['@distube/ytdl-core'];
const totalMemoryInMb: string = Math.ceil((await osu.mem.info()).totalMemMb).toLocaleString('en-US');
const cpuCores: number = await osu.cpu.count();
const platform: string = await osu.os.platform();
const discordJsVersion: string = dependencies['discord.js'];
const opusVersion: string = dependencies['@discord-player/opus'];
const restVersion: string = dependencies['@discordjs/rest'];
const voiceVersion: string = dependencies['discord-voip'];
const discordPlayerVersion: string = dependencies['discord-player'];
const extractorVersion: string = dependencies['@discord-player/extractor'];
const mediaplexVersion: string = dependencies['mediaplex'];
const distubeYtdlVersion: string = dependencies['@distube/ytdl-core'];
logger.debug('Fetching player statistics from all shards.');
@@ -85,7 +85,7 @@ const command: CustomSlashCommandInteraction = {
await client!
.shard!.fetchClientValues('guilds.cache')
.then((results) => {
const guildCaches = results as Guild[][];
const guildCaches: Guild[][] = results as Guild[][];
guildCaches.map((guildCache: Guild[]) => {
if (guildCache) {
guildCount += guildCache.length;
@@ -124,7 +124,7 @@ const command: CustomSlashCommandInteraction = {
`**${mediaplexVersion}** mediaplex\n` +
`**${distubeYtdlVersion}** @distube/ytdl-core`;
const discordStatusString = `**${client!.ws.ping} ms** Discord API latency`;
const discordStatusString: string = `**${client!.ws.ping} ms** Discord API latency`;
logger.debug('Transformed system status into embed description.');
@@ -1,17 +1,17 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { CustomComponentInteraction } from '../../types/interactionTypes';
import { GuildQueue, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember } from 'discord.js';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import { queueDoesNotExist } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const component: CustomComponentInteraction = {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'filters-disable-button.js',
module: 'componentInteraction',
name: 'filters-disable-button',
@@ -1,18 +1,18 @@
import config from 'config';
import loggerModule from '../../services/logger';
import { EmbedOptions, FFmpegFilterOptions } from '../../types/configTypes';
import { CustomComponentInteraction } from '../../types/interactionTypes';
import { GuildQueue, QueueFilters, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, StringSelectMenuInteraction } from 'discord.js';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes';
import { CustomComponentInteraction } from '../../types/interactionTypes';
import { queueDoesNotExist } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions');
const component: CustomComponentInteraction = {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'filters-select-menu.js',
module: 'componentInteraction',
name: 'filters-select-menu',
@@ -23,7 +23,7 @@ const component: CustomComponentInteraction = {
logger.debug('Received select menu confirmation.');
const selectMenuInteraction = interaction as StringSelectMenuInteraction;
const selectMenuInteraction: StringSelectMenuInteraction = interaction as StringSelectMenuInteraction;
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
const validators = [
@@ -90,9 +90,10 @@ const component: CustomComponentInteraction = {
embedOptions.icons.success
} Filters toggled**\nNow using these filters:\n${selectMenuInteraction.values
.map((enabledFilter: string) => {
const filter = ffmpegFilterOptions.availableFilters.find(
(filter) => enabledFilter == filter.value
);
const filter: FFmpegFilterOption | undefined =
ffmpegFilterOptions.availableFilters.find(
(filter) => enabledFilter == filter.value
);
if (!filter) {
return enabledFilter;
@@ -1,5 +1,5 @@
import config from 'config';
import { GuildQueue, useQueue } from 'discord-player';
import { GuildQueue, Track, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember } from 'discord.js';
import loggerModule from '../../services/logger';
@@ -7,11 +7,12 @@ import { EmbedOptions } from '../../types/configTypes';
import { CustomComponentInteraction } from '../../types/interactionTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
const component: CustomComponentInteraction = {
execute: async ({ interaction, referenceId, executionId }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'nowplaying-skip.js',
module: 'componentInteraction',
name: 'nowplaying-skip',
@@ -69,7 +70,7 @@ const component: CustomComponentInteraction = {
});
}
const skippedTrack = queue.currentTrack!;
const skippedTrack: Track = queue.currentTrack!;
let durationFormat =
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
@@ -81,14 +82,14 @@ const component: CustomComponentInteraction = {
queue.node.skip();
logger.debug('Skipped the track.');
const loopModesFormatted = new Map([
const loopModesFormatted: Map<number, string> = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
const repeatModeUserString: string = loopModesFormatted.get(queue.repeatMode)!;
let authorName: string;
+7 -7
View File
@@ -1,11 +1,11 @@
import config from 'config';
import pino from 'pino';
import pino, { DestinationStream, Logger, LoggerOptions } from 'pino';
import { LoggerOptions } from '../types/configTypes';
import { CustomLoggerOptions } from '../types/configTypes';
import { TargetOptions } from '../types/serviceTypes';
// Retrieve logger options from config
const loggerOptions: LoggerOptions = config.get('loggerOptions');
const loggerOptions: CustomLoggerOptions = config.get('loggerOptions');
const targets: TargetOptions[] = [
{
@@ -59,18 +59,18 @@ if (process.env.LOKI_AUTH_PASSWORD && process.env.LOKI_AUTH_USERNAME) {
});
}
const transport = pino.transport({ targets });
const transport: DestinationStream = pino.transport({ targets });
// Default properties for the logger, these will be added to every log entry
const defaultProperties = {
const defaultProperties: object = {
environment: process.env.NODE_ENV || 'development'
};
const logLevelConfig = {
const logLevelConfig: LoggerOptions = {
level: loggerOptions.minimumLogLevel,
timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`,
base: defaultProperties
};
const logger = pino(logLevelConfig, transport);
const logger: Logger = pino(logLevelConfig, transport);
export default logger;
+1 -2
View File
@@ -1,5 +1,4 @@
import { ActivityType, ColorResolvable, PresenceUpdateStatus, ShardingManagerOptions } from 'discord.js';
import { LogLevel } from './serviceTypes';
export interface BotOptions {
@@ -10,7 +9,7 @@ export interface BotOptions {
export interface ShardingOptions extends ShardingManagerOptions {}
export interface LoggerOptions {
export interface CustomLoggerOptions {
minimumLogLevel: LogLevel;
minimumLogLevelConsole: LogLevel;
discordPlayerDebug: boolean;
+8 -6
View File
@@ -8,12 +8,13 @@ import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../services/logger';
import { SystemOptions } from '../types/configTypes';
import { Logger } from 'pino';
const systemOptions: SystemOptions = config.get('systemOptions');
const executionId = uuidv4();
const executionId: string = uuidv4();
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'deploySlashCommands.js',
module: 'deploy',
name: 'deploySlashCommands',
@@ -24,7 +25,7 @@ const logger = loggerModule.child({
const slashCommands: SlashCommandBuilder[] = [];
const systemCommands: SlashCommandBuilder[] = [];
const commandFolders = fs.readdirSync(path.resolve('./dist/interactions/commands'));
const commandFolders: string[] = fs.readdirSync(path.resolve('./dist/interactions/commands'));
if (!process.env.DISCORD_BOT_TOKEN) {
throw new Error('DISCORD_BOT_TOKEN environment variable is not set.');
@@ -34,7 +35,7 @@ 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);
const rest: REST = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN);
(async () => {
if (!process.env.DISCORD_APPLICATION_ID || !process.env.DISCORD_BOT_TOKEN) {
@@ -45,11 +46,12 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN)
}
for (const folder of commandFolders) {
const commandFiles = fs
const commandFiles: string[] = fs
.readdirSync(path.resolve(`./dist/interactions/commands/${folder}`))
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
// TODO: create commandModule type
const commandModule = await import(`../interactions/commands/${folder}/${file}`);
const command = commandModule.default;
command.isSystemCommand
@@ -76,7 +78,7 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN)
);
logger.info('Started refreshing system slash commands.');
const systemGuildIds = systemOptions.systemGuildIds;
const systemGuildIds: string[] = systemOptions.systemGuildIds;
await Promise.all(
systemGuildIds.map((systemGuildId: string) => {
logger.debug(`Refreshing system slash command for guild id '${systemGuildId}'.`);
+2 -1
View File
@@ -1,9 +1,10 @@
import Discord, { Client } from 'discord.js';
import loggerModule from '../../services/logger';
import { Logger } from 'pino';
export const createClient = async ({ executionId }: { executionId: string }) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'createClient.js',
module: 'utilFactory',
name: 'createClient',
+3 -2
View File
@@ -2,9 +2,10 @@ import { Player } from 'discord-player';
import loggerModule from '../../services/logger';
import { CreatePlayerParams } from '../../types/playerTypes';
import { Logger } from 'pino';
export const createPlayer = async ({ client, executionId }: CreatePlayerParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'createPlayer.js',
module: 'utilFactory',
name: 'createPlayer',
@@ -15,7 +16,7 @@ export const createPlayer = async ({ client, executionId }: CreatePlayerParams)
try {
logger.debug('Creating discord-player player...');
const player = new Player(client, {
const player: Player = new Player(client, {
useLegacyFFmpeg: false,
ytdlOptions: {
quality: 'highestaudio',
+2 -2
View File
@@ -2,10 +2,10 @@ import fs from 'node:fs';
import path from 'node:path';
/* eslint-disable @typescript-eslint/no-var-requires */
const cookies = require(path.resolve('./cookies.json'));
const cookies: { name: string; value: string }[] = require(path.resolve('./cookies.json'));
try {
const cookieString = cookies
const cookieString: string = cookies
.map(({ name, value }: { name: string; value: string }) => {
return `${name}=${value}`;
})
+10 -8
View File
@@ -3,9 +3,11 @@ import https from 'node:https';
import loggerModule from '../../services/logger';
import { PostBotStatsParams, PostBotStatsSite } from '../../types/utilTypes';
import { Logger } from 'pino';
import { ClientRequest, ClientRequestArgs } from 'node:http';
export const postBotStats = async ({ client, executionId }: PostBotStatsParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'postBotStats.js',
module: 'utilOther',
name: 'postBotStats',
@@ -18,16 +20,16 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams)
return;
}
let guildCount = 0;
let memberCount = 0;
const shardCount = client.shard.count;
const shardId = client.shard.ids[0];
let guildCount: number = 0;
let memberCount: number = 0;
const shardCount: number = client.shard.count;
const shardId: number = client.shard.ids[0];
logger.debug('Gathering data about guild and member count from shards...');
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
const guildCaches = results as Collection<string, Guild>[];
const guildCaches: Collection<string, Guild>[] = results as Collection<string, Guild>[];
guildCaches.map((guildCache) => {
if (guildCache) {
guildCount += guildCache.size;
@@ -132,7 +134,7 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams)
return;
}
const options = {
const options: ClientRequestArgs = {
protocol: 'https:',
hostname: site.hostname,
port: 443,
@@ -144,7 +146,7 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams)
}
};
const request = https.request(options, (res) => {
const request: ClientRequest = https.request(options, (res) => {
if (typeof res.statusCode === 'number') {
res.statusCode === 200
? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`)
+6 -5
View File
@@ -1,6 +1,7 @@
import config from 'config';
import { Client } from 'discord.js';
import { Channel, Client } from 'discord.js';
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { LoadTestOptions } from '../../types/configTypes';
import { StartLoadTestParams } from '../../types/utilTypes';
@@ -8,7 +9,7 @@ import { StartLoadTestParams } from '../../types/utilTypes';
const loadTestOptions: LoadTestOptions = config.get('loadTestOptions');
export const startLoadTest = async ({ client, executionId }: StartLoadTestParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'startLoadTest.js',
module: 'utilOther',
name: 'startLoadTest',
@@ -21,15 +22,15 @@ export const startLoadTest = async ({ client, executionId }: StartLoadTestParams
return;
}
const channelIds = loadTestOptions.channelIdsToJoin;
const track = loadTestOptions.trackUrl;
const channelIds: string[] = loadTestOptions.channelIdsToJoin;
const track: string = loadTestOptions.trackUrl;
logger.info(`Starting load test in ${channelIds.length} specified channels.`);
channelIds.forEach((each) => {
client.shard?.broadcastEval(
async (shardClient: Client, { channelId, track }: { channelId: string; track: string }) => {
const channel = shardClient.channels.cache.get(channelId);
const channel: Channel | undefined = shardClient.channels.cache.get(channelId);
if (channel) {
/* eslint-disable no-undef */
// @ts-ignore
+4 -3
View File
@@ -4,9 +4,10 @@ import path from 'node:path';
import loggerModule from '../services/logger';
import { RegisterClientCommandsParams } from '../types/utilTypes';
import { Logger } from 'pino';
export const registerClientCommands = async ({ client, executionId }: RegisterClientCommandsParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'registerClientCommands.js',
module: 'register',
name: 'registerClientCommands',
@@ -17,10 +18,10 @@ export const registerClientCommands = async ({ client, executionId }: RegisterCl
logger.debug('Registering client commands...');
client.commands = new Collection();
const commandFolders = fs.readdirSync(path.resolve('./dist/interactions/commands'));
const commandFolders: string[] = fs.readdirSync(path.resolve('./dist/interactions/commands'));
for (const folder of commandFolders) {
logger.trace(`Registering client commands for folder '${folder}'...`);
const commandFiles = fs
const commandFiles: string[] = fs
.readdirSync(path.resolve(`./dist/interactions/commands/${folder}`))
.filter((file) => file.endsWith('.js'));
+7 -6
View File
@@ -5,11 +5,12 @@ import path from 'node:path';
import { GuildQueueEvents, Player, PlayerEvents } from 'discord-player';
import { Client } from 'discord.js';
import loggerModule from '../services/logger';
import { LoggerOptions } from '../types/configTypes';
import { CustomLoggerOptions } from '../types/configTypes';
import { ClientEventArguments, PlayerEventArguments, ProcessEventArguments } from '../types/eventTypes';
import { CustomEvent, RegisterEventListenersParams } from '../types/utilTypes';
import { Logger } from 'pino';
const loggerOptions: LoggerOptions = config.get('loggerOptions');
const loggerOptions: CustomLoggerOptions = config.get('loggerOptions');
const registerClientEventListeners = (client: Client, event: CustomEvent) => {
if (event.once) {
@@ -29,7 +30,7 @@ const registerProcessEventListeners = (event: CustomEvent) => {
process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args));
};
const registerPlayerEventListeners = (player: Player, event: CustomEvent, loggerOptions: LoggerOptions) => {
const registerPlayerEventListeners = (player: Player, event: CustomEvent, loggerOptions: CustomLoggerOptions) => {
if (!event.isDebug || (loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug)) {
if (event.isPlayerEvent) {
player.events.on(event.name as keyof GuildQueueEvents, (...args: PlayerEventArguments) =>
@@ -42,7 +43,7 @@ const registerPlayerEventListeners = (player: Player, event: CustomEvent, logger
};
export const registerEventListeners = async ({ client, player, executionId }: RegisterEventListenersParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'registerEventListeners.js',
module: 'register',
name: 'registerEventListeners',
@@ -52,11 +53,11 @@ export const registerEventListeners = async ({ client, player, executionId }: Re
logger.debug('Registering event listeners...');
const eventFolders = fs.readdirSync(path.resolve('./dist/events'));
const eventFolders: string[] = fs.readdirSync(path.resolve('./dist/events'));
for (const folder of eventFolders) {
logger.trace(`Registering event listener for folder '${folder}'...`);
const eventFiles = fs
const eventFiles: string[] = fs
.readdirSync(path.resolve(`./dist/events/${folder}`))
.filter((file) => file.endsWith('.js'));
+5 -4
View File
@@ -1,8 +1,9 @@
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { GetUptimeFormattedParams } from '../../types/utilTypes';
export const getUptimeFormatted = async ({ executionId }: GetUptimeFormattedParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'getUptimeFormatted.js',
module: 'utilSystem',
name: 'getUptimeFormatted',
@@ -10,10 +11,10 @@ export const getUptimeFormatted = async ({ executionId }: GetUptimeFormattedPara
});
try {
let uptimeFormattedString = '';
let uptimeFormattedString: string = '';
const uptimeInSeconds = parseFloat(process.uptime().toFixed(0));
const uptimeDate = new Date(0);
const uptimeInSeconds: number = parseFloat(process.uptime().toFixed(0));
const uptimeDate: Date = new Date(0);
uptimeDate.setSeconds(uptimeInSeconds);
uptimeFormattedString = `${
uptimeDate.getUTCDate() - 1
+15 -5
View File
@@ -1,13 +1,22 @@
import config from 'config';
import { EmbedBuilder, GuildMember, InteractionType, TextChannel, VoiceChannel } from 'discord.js';
import {
EmbedBuilder,
GuildMember,
InteractionType,
TextBasedChannel,
TextChannel,
VoiceBasedChannel,
VoiceChannel
} from 'discord.js';
import { Logger } from 'pino';
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({
const logger: Logger = loggerModule.child({
source: 'permissionValidator.js',
module: 'utilValidation',
name: 'cannotJoinVoiceOrTalk',
@@ -16,7 +25,8 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: Cannot
guildId: interaction.guild?.id
});
const channel = interaction.member instanceof GuildMember ? interaction.member.voice.channel : null;
const channel: VoiceBasedChannel | null =
interaction.member instanceof GuildMember ? interaction.member.voice.channel : null;
const interactionIdentifier =
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
@@ -41,7 +51,7 @@ export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: Cannot
};
export const cannotSendMessageInChannel = async ({ interaction, executionId }: CannotSendMessageInChannelParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'permissionValidator.js',
module: 'utilValidation',
name: 'cannotSendMessageInChannel',
@@ -50,7 +60,7 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C
guildId: interaction.guild?.id
});
const channel = interaction.channel;
const channel: TextBasedChannel | null = interaction.channel;
const interactionIdentifier =
interaction.type === InteractionType.ApplicationCommand ? interaction.commandName : interaction.customId;
+4 -3
View File
@@ -4,10 +4,11 @@ import { EmbedBuilder, InteractionType } from 'discord.js';
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { QueueDoesNotExistParams, QueueIsEmptyParams, QueueNoCurrentTrackParams } from '../../types/utilTypes';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const queueDoesNotExist = async ({ interaction, queue, executionId }: QueueDoesNotExistParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueDoesNotExist',
@@ -38,7 +39,7 @@ export const queueDoesNotExist = async ({ interaction, queue, executionId }: Que
};
export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: QueueNoCurrentTrackParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueNoCurrentTrack',
@@ -69,7 +70,7 @@ export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: Q
};
export const queueIsEmpty = async ({ interaction, queue, executionId }: QueueIsEmptyParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueIsEmpty',
+6 -5
View File
@@ -1,8 +1,9 @@
import { Logger } from 'pino';
import loggerModule from '../../services/logger';
import { TransformQueryParams } from '../../types/utilTypes';
export const transformQuery = async ({ query, executionId }: TransformQueryParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'searchQueryValidator.js',
module: 'utilValidation',
name: 'transformQuery',
@@ -15,15 +16,15 @@ export const transformQuery = async ({ query, executionId }: TransformQueryParam
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);
const isCountryBased: boolean = regex.test(query);
// 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 matches = query.match(regex);
const matches: RegExpMatchArray | null = query.match(regex);
if (matches) {
const type = matches[2];
const trackId = matches[3];
const type: string = matches[2];
const trackId: string = matches[3];
query = `https://open.spotify.com/${type}/${trackId}`;
}
}
@@ -4,11 +4,12 @@ import { EmbedBuilder, InteractionType } from 'discord.js';
import loggerModule from '../../services/logger';
import { EmbedOptions, SystemOptions } from '../../types/configTypes';
import { NotValidGuildIdParams } from '../../types/utilTypes';
import { Logger } from 'pino';
const embedOptions: EmbedOptions = config.get('embedOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
export const notValidGuildId = async ({ interaction, executionId }: NotValidGuildIdParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'systemCommandValidator.js',
module: 'utilValidation',
name: 'notValidGuildId',
@@ -1,13 +1,14 @@
import config from 'config';
import { EmbedBuilder, GuildMember, InteractionType } from 'discord.js';
import { Logger } from 'pino';
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({
const logger: Logger = loggerModule.child({
source: 'voiceChannelValidator.js',
module: 'validator',
name: 'notInVoiceChannel',
@@ -38,7 +39,7 @@ export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoice
};
export const notInSameVoiceChannel = async ({ interaction, queue, executionId }: NotInSameVoiceChannelParams) => {
const logger = loggerModule.child({
const logger: Logger = loggerModule.child({
source: 'voiceChannelValidator.js',
module: 'utilValidation',
name: 'notInSameVoiceChannel',