Merge pull request #185 from mariusbegby/interaction-update

Interaction update
This commit is contained in:
Marius Begby authored and GitHub committed 2023-08-28 18:26:44 +02:00
commit 2dfd675cbe
47 files changed
+1204 -986

No files matched your search

+1
View File
@@ -1 +1,2 @@
* text=auto eol=crlf
*.js linguist-language=TypeScript
+1 -1
View File
@@ -121,7 +121,7 @@ module.exports.playerOptions = {
maxQueueSize: 10_000,
maxHistorySize: 100,
bufferingTimeout: 3_000,
connectionTimeout: 30_000,
connectionTimeout: 20_000,
progressBar: {
length: 14,
timecodes: false,
+2 -2
View File
@@ -20,10 +20,10 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./dist/index.js",
"start-pretty": "node ./dist/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId",
"start-pretty": "node ./dist/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,executionTime,shardId,guildId,interactionType",
"start-pretty-no-ignore": "node ./dist/index.js | pino-pretty",
"deploy": "node ./dist/utils/deploySlashCommands.js",
"deploy-pretty": "node ./dist/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId",
"deploy-pretty": "node ./dist/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,executionTime,shardId,guildId,interactionType",
"eslint": "eslint ./src",
"build": "tsc"
},
+16 -14
View File
@@ -20,17 +20,19 @@ const logger = loggerModule.child({
});
(async () => {
const client: ExtendedClient = await createClient({ executionId });
const player = await createPlayer({ client, executionId });
client.on('allShardsReady', async () => {
client.registerClientCommands = registerClientCommands;
registerEventListeners({ client, player, executionId });
registerClientCommands({ client, executionId });
client.emit('ready', client as Client);
});
client.login(process.env.DISCORD_BOT_TOKEN);
})().catch((error) => {
logger.error(error);
});
try {
const client: ExtendedClient = await createClient({ executionId });
const player = await createPlayer({ client, executionId });
client.on('allShardsReady', async () => {
client.registerClientCommands = registerClientCommands;
await registerEventListeners({ client, player, executionId });
await registerClientCommands({ client, executionId });
client.emit('ready', client as Client);
});
client.login(process.env.DISCORD_BOT_TOKEN);
} catch (error) {
logger.error(error);
}
})();
-239
View File
@@ -1,239 +0,0 @@
import config from 'config';
import { NodeResolvable, QueueFilters, useQueue } from 'discord-player';
import {
APIActionRowComponent,
APIMessageActionRowComponent,
ButtonBuilder,
ButtonStyle,
ComponentType,
EmbedBuilder,
GuildMember,
Interaction,
SlashCommandBuilder,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder
} from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams, CustomError } from '../../types/commandTypes';
import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('filters')
.setDescription('Toggle various audio filters during playback.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'filters.js',
module: 'slashCommand',
name: '/filters',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
const filterOptions: StringSelectMenuOptionBuilder[] = [];
ffmpegFilterOptions.availableFilters.forEach((filter: FFmpegFilterOption) => {
let isEnabled = false;
if (queue.filters.ffmpeg.filters.includes(filter.value as keyof QueueFilters)) {
isEnabled = true;
}
filterOptions.push(
new StringSelectMenuOptionBuilder()
.setLabel(filter.label)
.setDescription(filter.description)
.setValue(filter.value)
.setEmoji(filter.emoji)
.setDefault(isEnabled)
);
});
const filterSelect = new StringSelectMenuBuilder()
.setCustomId('filters')
.setPlaceholder('Select multiple options.')
.setMinValues(0)
.setMaxValues(filterOptions.length)
.addOptions(filterOptions)
.toJSON();
const filterActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [filterSelect]
};
const disableButton = new ButtonBuilder()
.setCustomId('disable-filters')
.setLabel('Disable all filters')
.setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.disable)
.toJSON();
const disableFiltersActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [disableButton]
};
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.')
.setColor(embedOptions.colors.info)
],
components: [filterActionRow, disableFiltersActionRow]
});
const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id;
try {
const confirmation = await response.awaitMessageComponent({
filter: collectorFilter,
time: 300_000
});
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
queue.filters.ffmpeg.setInputArgs([
'-threads',
ffmpegFilterOptions.threadAmount,
'-reconnect',
'1',
'-reconnect_streamed',
'1',
'-reconnect_delay_max',
'10',
'-vn'
]);
// Reset filters before enabling provided filters
if (queue.filters.ffmpeg.filters.length > 0) {
queue.filters.ffmpeg.setFilters(false);
logger.debug('Reset queue filters.');
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
if ('values' in confirmation) {
// if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion
if (
(confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) &&
!confirmation.values.includes('normalizer')
) {
confirmation.values.push('normalizer');
}
// Enable provided filters
queue.filters.ffmpeg.toggle(confirmation.values as (keyof QueueFilters)[]);
logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${
embedOptions.icons.success
} Filters toggled**\nNow using these filters:\n${confirmation.values
.map((enabledFilter: string) => {
const filter = ffmpegFilterOptions.availableFilters.find(
(filter) => enabledFilter == filter.value
);
if (!filter) {
return enabledFilter;
}
return `- **${filter.emoji} ${filter.label}**`;
})
.join('\n')}`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} else if (confirmation.customId === 'disable-filters') {
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} else {
logger.warn('Unhandled component interaction response.');
}
} catch (error) {
if (error instanceof CustomError) {
if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.');
return;
}
if (error.message === 'Collector received no interactions before ending with reason: time') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
} else {
if (
error instanceof Error &&
error.message === 'Collector received no interactions before ending with reason: time'
) {
logger.debug('Interaction response timed out.');
return;
}
throw error;
}
}
}
};
+66 -117
View File
@@ -1,18 +1,26 @@
import config from 'config';
import { EmbedBuilder, Events, Interaction, StringSelectMenuInteraction } from 'discord.js';
import {
AutocompleteInteraction,
ChatInputCommandInteraction,
Events,
Interaction,
InteractionType,
MessageComponentInteraction
} from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import { handleAutocomplete } from '../../handlers/interactionAutocompleteHandler';
import { handleCommand } from '../../handlers/interactionCommandHandler';
import { handleComponent } from '../../handlers/interactionComponentHandler';
import { handleError } from '../../handlers/interactionErrorHandler';
import loggerModule from '../../services/logger';
import { Command, ExtendedClient } from '../../types/clientTypes';
import { BotOptions, EmbedOptions } from '../../types/configTypes';
import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator';
import { ExtendedClient } from '../../types/clientTypes';
import { CustomError } from '../../types/interactionTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
module.exports = {
name: Events.InteractionCreate,
isDebug: false,
execute: async (interaction: Interaction, { client }: { client: ExtendedClient }) => {
const inputTime: number = new Date().getTime();
const executionId = uuidv4();
const logger = loggerModule.child({
source: 'interactionCreate.js',
@@ -23,123 +31,64 @@ module.exports = {
guildId: interaction.guild?.id
});
if (interaction.isMessageComponent()) {
if (interaction instanceof StringSelectMenuInteraction) {
logger.debug(
`Message component interaction created for id ${interaction.customId}${
interaction.values ? ' and values ' + interaction.values : ''
}.`
);
}
logger.debug('Interaction received.');
return;
let interactionIdentifier = 'Unknown';
if (
interaction.type === InteractionType.ApplicationCommand ||
interaction.type === InteractionType.ApplicationCommandAutocomplete
) {
interactionIdentifier = (interaction as ChatInputCommandInteraction).commandName;
} else if (interaction.type === InteractionType.MessageComponent) {
interactionIdentifier = (interaction as MessageComponentInteraction).customId;
}
if (interaction.isChatInputCommand() || interaction.isAutocomplete()) {
const command = client.commands?.get(interaction.commandName) as Command;
try {
logger.debug('Started handling interaction.');
switch (interaction.type) {
case InteractionType.ApplicationCommand:
await handleCommand(interaction as ChatInputCommandInteraction, client, executionId);
break;
if (interaction.isChatInputCommand()) {
if (!command) {
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
return;
}
logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`);
try {
await interaction.deferReply();
case InteractionType.ApplicationCommandAutocomplete:
await handleAutocomplete(interaction as AutocompleteInteraction, executionId);
break;
if (await cannotSendMessageInChannel({ interaction, executionId })) {
return;
}
case InteractionType.MessageComponent:
await handleComponent(interaction as MessageComponentInteraction, executionId);
break;
const inputTime: number = new Date().getTime();
await command.execute({ interaction, client, executionId });
const outputTime: number = new Date().getTime();
const executionTime: number = outputTime - inputTime;
logger.info(`Command '${interaction}' executed in ${executionTime} ms.`);
} catch (error) {
if (error instanceof Error) {
logger.warn(
error,
`Command '${interaction}' throwed an unhandled error and might have failed to execute properly.`
);
if (
error.message === 'Unknown interaction' ||
error.message === 'Interaction has already been acknowledged.'
) {
logger.debug(
'Command failed to be responded to, unknown interaction or already acknowledged.'
);
return;
} else {
if (!interaction.deferred || !interaction.replied) {
logger.warn('Interaction was not deferred or replied to, and an error was thrown.');
return;
}
if (interaction.replied) {
// If the interaction has already been replied to, most likely command executed successfully or error is already handled.
return;
} else if (interaction.deferred) {
logger.info('Interaction was deferred, editing reply and sending Uh-oh message.');
await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
} else {
logger.info(
'Interaction was not deferred or replied, sending new reply with Uh-oh message.'
);
await interaction.reply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
}
} else {
throw error;
}
}
} else if (interaction.isAutocomplete()) {
logger.debug('Autocomplete interaction created.');
try {
command?.autocomplete && (await command?.autocomplete({ interaction, executionId }));
} catch (error) {
if (error instanceof Error) {
if (
error.message === 'Unknown interaction' ||
error.message === 'Interaction has already been acknowledged.'
) {
logger.debug(
'Autocomplete failed to be responded to, unknown interaction or already acknowledged.'
);
return;
} else {
logger.warn(error, 'Autocomplete failed to execute.');
}
return;
} else {
throw error;
}
}
default:
logger.error(
interaction,
`Interaction of type '${interaction.type}' was not handled, interaction attached as object.`
);
break;
}
} else {
logger.warn(interaction, 'Interaction created but was not a chat input or autocomplete interaction.');
} catch (error) {
logger.debug('Error while handling received interaction.');
await handleError(interaction, error as CustomError, interactionIdentifier, executionId);
}
const outputTime: number = new Date().getTime();
const executionTime: number = outputTime - inputTime;
const interactionType = InteractionType[interaction.type];
logger.info(
{
executionTime: executionTime,
interactionType: interactionType
},
`${interactionType} interaction '${interactionIdentifier}' successfully handled in ${executionTime} ms.`
);
if (executionTime > 10000) {
logger.warn(
`${interactionType} interaction '${interactionIdentifier}' took ${executionTime} ms to execute.`
);
}
return;
}
};
@@ -0,0 +1,16 @@
import { AutocompleteInteraction } from 'discord.js';
import loggerModule from '../services/logger';
const logger = loggerModule.child({
source: 'interactionCutocompleteHandler.ts',
module: 'handler',
name: 'interactionAutocompleteHandler'
});
export const handleAutocomplete = async (interaction: AutocompleteInteraction, executionId: string) => {
const autocompleteModule = await import(`../interactions/autocomplete/${interaction.commandName}.js`);
const { default: autocomplete } = autocompleteModule;
logger.debug('Executing autocomplete interaction.');
await autocomplete.execute({ interaction, executionId });
};
+32
View File
@@ -0,0 +1,32 @@
import { ChatInputCommandInteraction } from 'discord.js';
import { Command, ExtendedClient } from '../types/clientTypes';
import { cannotSendMessageInChannel } from '../utils/validation/permissionValidator';
import loggerModule from '../services/logger';
const logger = loggerModule.child({
source: 'interactionCommandHandler.ts',
module: 'handler',
name: 'interactionCommandHandler'
});
export const handleCommand = async (
interaction: ChatInputCommandInteraction,
client: ExtendedClient,
executionId: string
) => {
await interaction.deferReply();
logger.debug('Interaction deferred.');
const command = client.commands?.get(interaction.commandName) as Command;
if (!command) {
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
return;
}
if (await cannotSendMessageInChannel({ interaction, executionId })) {
return Promise.resolve();
}
logger.debug('Executing command interaction.');
await command.execute({ interaction, client, executionId });
};
@@ -0,0 +1,24 @@
import { MessageComponentInteraction } from 'discord.js';
import loggerModule from '../services/logger';
const logger = loggerModule.child({
source: 'interactionComponentHandler.js',
module: 'handler',
name: 'interactionComponentHandler'
});
export const handleComponent = async (interaction: MessageComponentInteraction, executionId: string) => {
await interaction.deferReply();
logger.debug('Interaction deferred.');
const componentId = interaction.customId.split('_')[0];
const referenceId = interaction.customId.split('_')[1];
logger.debug(`Parsed componentId: ${componentId}`);
const componentModule = await import(`../interactions/components/${componentId}.js`);
const { default: component } = componentModule;
logger.debug('Executing component interaction.');
await component.execute({ interaction, referenceId, executionId });
};
+69
View File
@@ -0,0 +1,69 @@
import config from 'config';
import { ChatInputCommandInteraction, EmbedBuilder, Interaction, MessageComponentInteraction } from 'discord.js';
import { BotOptions, EmbedOptions } from '../types/configTypes';
import loggerModule from '../services/logger';
import { CustomError } from '../types/interactionTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
const logger = loggerModule.child({
source: 'interactionErrorHandler.ts',
module: 'handler',
name: 'interactionErrorHandler'
});
export const handleError = async (
interaction: Interaction,
error: CustomError,
interactionIdentifier: string,
executionId: string
) => {
const errorReply = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to perform this action. You can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
};
logger.error(error, `Error handling interaction '${interactionIdentifier}'`);
if (interaction instanceof ChatInputCommandInteraction && interaction.deferred) {
switch (interaction.replied) {
case true:
logger.warn(error, `Interaction '${interaction.id}' threw an error but has already been replied to.`);
return;
case false:
logger.debug('Responding with error embed');
return await interaction.editReply(errorReply);
}
} else if (interaction instanceof MessageComponentInteraction && interaction.deferred) {
switch (interaction.replied) {
case true:
logger.warn(error, `Interaction '${interaction.id}' threw an error but has already been replied to.`);
return;
case false:
logger.debug('Responding with error embed');
return await interaction.editReply(errorReply);
}
} else {
logger.warn(
'Interaction threw an error but was not deferred or replied to, or was an autocomplete interaction. Cannot send error reply.'
);
if (
error.code === 'InteractionCollectorError' ||
error.message === 'Collector received no interactions before ending with reason: time'
) {
logger.debug('Interaction response timed out.');
return;
}
logger.fatal(error, 'Unhandled error while awaiting or handling component interaction.');
return;
}
};
+16
View File
@@ -37,6 +37,22 @@ manager.on('shardCreate', (shard: Shard) => {
logger.info('All shards ready, bot is now online.');
}
});
shard.on(ShardEvents.Death, (event) => {
logger.fatal(event, 'SHARD CLOSED UNEXPECTEDLY.');
});
shard.on(ShardEvents.Error, (error) => {
logger.error(error, 'Shard experienced an error, most likely related to websocket connection error.');
});
shard.on(ShardEvents.Disconnect, () => {
logger.warn('Shard disconnected.');
});
shard.on(ShardEvents.Reconnecting, () => {
logger.warn('Shard reconnecting.');
});
});
manager.spawn();
+78
View File
@@ -0,0 +1,78 @@
import { useMainPlayer } from 'discord-player';
import loggerModule from '../../services/logger';
import { CustomAutocompleteInteraction } from '../../types/interactionTypes';
import { lyricsExtractor } from '@discord-player/extractor';
const loggerTemplate = loggerModule.child({
source: 'lyrics.js',
module: 'autocompleteInteraction',
name: '/lyrics'
});
const recentQueries = new Map();
const autocomplete: CustomAutocompleteInteraction = {
execute: async ({ interaction, executionId }) => {
// TODO: Extract autocomplete logic
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const query = interaction.options.getString('query', true);
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}'`);
return interaction.respond(result);
}
if (query.length < 3) {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const genius = lyricsExtractor();
const lyricsResult = await genius.search(query).catch(() => null);
let response = [];
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);
response = searchResults.tracks.slice(0, 1).map((track) => ({
name:
`${track.title} [Artist: ${track.author}]`.length > 100
? `${track.title}`.slice(0, 100)
: `${track.title} [Artist: ${track.author}]`,
value: track.title.slice(0, 100)
}));
} else {
logger.debug(`Found Genius lyrics for query '${query}'.`);
response = [
{
name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100),
value: lyricsResult.title.slice(0, 100)
}
];
}
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
recentQueries.set(interaction.user.id, {
lastQuery: query,
result: response,
timestamp: Date.now()
});
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
}
};
export default autocomplete;
+68
View File
@@ -0,0 +1,68 @@
import { useMainPlayer } from 'discord-player';
import loggerModule from '../../services/logger';
import { CustomAutocompleteInteraction } from '../../types/interactionTypes';
const loggerTemplate = loggerModule.child({
source: 'play.js',
module: 'autocompleteInteraction',
name: '/play'
});
const recentQueries = new Map();
const autocomplete: CustomAutocompleteInteraction = {
execute: async ({ interaction, executionId }) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const player = useMainPlayer()!;
const query = interaction.options.getString('query', true);
const { lastQuery, results, 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}'`);
return interaction.respond(results);
}
if (query.length < 3) {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const searchResults = await player.search(query);
let response = [];
response = searchResults.tracks.slice(0, 5).map((track) => {
if (track.url.length > 100) {
track.url = track.title.slice(0, 100);
}
return {
name:
`${track.title} [Author: ${track.author}]`.length > 100
? `${track.title}`.slice(0, 100)
: `${track.title} [Author: ${track.author}]`,
value: track.url
};
});
recentQueries.set(interaction.user.id, {
lastQuery: query,
results: response,
timestamp: Date.now()
});
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
}
};
export default autocomplete;
@@ -1,13 +1,14 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { BotOptions, EmbedOptions } from '../../types/configTypes';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { BotOptions, EmbedOptions } from '../../../types/configTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -15,7 +16,7 @@ module.exports = {
.setDescription('Show a list of commands and their usage.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
source: 'help.js',
module: 'slashCommand',
@@ -25,12 +26,7 @@ module.exports = {
guildId: interaction.guild?.id
});
if (!client || !client.commands) {
logger.error('Client is undefined or does not have commands property.');
return;
}
const commandList = client.commands
const commandList = client!.commands!
.filter((command) => {
// don't include system commands
if (command.isSystemCommand) {
@@ -69,3 +65,5 @@ module.exports = {
});
}
};
export default command;
@@ -3,14 +3,15 @@ import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import osu from 'node-os-utils';
// @ts-ignore
import { version } from '../../../package.json';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted';
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';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -18,7 +19,7 @@ module.exports = {
.setDescription('Show the bot and system status.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
source: 'status.js',
module: 'slashCommand',
@@ -38,12 +39,7 @@ module.exports = {
let totalTracks: number = 0;
let totalListeners: number = 0;
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
await client.shard
await client!.shard!
.broadcastEval(() => {
/* eslint-disable no-undef */
return player.generateStatistics();
@@ -72,7 +68,7 @@ module.exports = {
logger.error(error, 'Failed to fetch player statistics from shards.');
});
await client.shard
await client!.shard!
.fetchClientValues('guilds.cache')
.then((results) => {
const guildCaches = results as Guild[][];
@@ -102,7 +98,7 @@ module.exports = {
const systemStatusString =
`**${uptimeString}** Uptime\n` + `**${cpuUsage}%** CPU usage\n` + `**${usedMemoryInMB} MB** Memory usage`;
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
const discordStatusString = `**${client!.ws.ping} ms** Discord API latency`;
logger.debug('Transformed status into into embed description.');
@@ -133,3 +129,5 @@ module.exports = {
});
}
};
export default command;
+116
View File
@@ -0,0 +1,116 @@
import config from 'config';
import { NodeResolvable, QueueFilters, useQueue } from 'discord-player';
import {
APIActionRowComponent,
APIMessageActionRowComponent,
ButtonBuilder,
ButtonStyle,
ComponentType,
EmbedBuilder,
SlashCommandBuilder,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder
} from 'discord.js';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions');
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('filters')
.setDescription('Toggle various audio filters during playback.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'filters.js',
module: 'slashCommand',
name: '/filters',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return Promise.resolve();
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return Promise.resolve();
}
const filterOptions: StringSelectMenuOptionBuilder[] = [];
ffmpegFilterOptions.availableFilters.forEach((filter: FFmpegFilterOption) => {
let isEnabled = false;
if (queue.filters.ffmpeg.filters.includes(filter.value as keyof QueueFilters)) {
isEnabled = true;
}
filterOptions.push(
new StringSelectMenuOptionBuilder()
.setLabel(filter.label)
.setDescription(filter.description)
.setValue(filter.value)
.setEmoji(filter.emoji)
.setDefault(isEnabled)
);
});
const filterSelect = new StringSelectMenuBuilder()
.setCustomId('filters-select-menu')
.setPlaceholder('Select multiple options.')
.setMinValues(0)
.setMaxValues(filterOptions.length)
.addOptions(filterOptions)
.toJSON();
const filterActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [filterSelect]
};
const disableButton = new ButtonBuilder()
.setCustomId('filters-disable-button')
.setLabel('Disable all filters')
.setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.disable)
.toJSON();
const disableFiltersActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [disableButton]
};
logger.debug('Sending info embed with action row components.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.')
.setColor(embedOptions.colors.info)
],
components: [filterActionRow, disableFiltersActionRow]
});
}
};
export default command;
@@ -2,13 +2,14 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -16,7 +17,7 @@ module.exports = {
.setDescription('Clear the track queue and remove the bot from voice channel.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'leave.js',
module: 'slashCommand',
@@ -27,7 +28,7 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
@@ -48,7 +49,7 @@ module.exports = {
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (!queue.deleted) {
@@ -80,3 +81,5 @@ module.exports = {
});
}
};
export default command;
@@ -1,16 +1,17 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import { EmbedBuilder, GuildMember, SlashCommandBuilder, SlashCommandStringOption } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { BotOptions, EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { BotOptions, EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -18,8 +19,8 @@ module.exports = {
.setDescription('Toggle looping a track, the whole queue or autoplay.')
.setDMPermission(false)
.setNSFW(false)
.addStringOption((option) =>
option
.addStringOption(() =>
new SlashCommandStringOption()
.setName('mode')
.setDescription('Mode to set for looping.')
.setRequired(false)
@@ -30,7 +31,7 @@ module.exports = {
{ name: 'Disabled', value: '0' }
)
),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'loop.js',
module: 'slashCommand',
@@ -41,17 +42,17 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
const loopModesFormatted = new Map([
@@ -184,3 +185,5 @@ module.exports = {
});
}
};
export default command;
@@ -4,14 +4,13 @@ import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { lyricsExtractor } from '@discord-player/extractor';
import loggerModule from '../../services/logger';
import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
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';
const embedOptions: EmbedOptions = config.get('embedOptions');
const recentQueries = new Map();
const loggerTemplate = loggerModule.child({
source: 'lyrics.js',
@@ -19,7 +18,7 @@ const loggerTemplate = loggerModule.child({
name: '/lyrics'
});
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -36,67 +35,7 @@ module.exports = {
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const query = interaction.options.getString('query', true);
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}'`);
return interaction.respond(result);
}
if (query.length < 3) {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const genius = lyricsExtractor();
const lyricsResult = await genius.search(query).catch(() => null);
let response = [];
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);
response = searchResults.tracks.slice(0, 1).map((track) => ({
name:
`${track.title} [Artist: ${track.author}]`.length > 100
? `${track.title}`.slice(0, 100)
: `${track.title} [Artist: ${track.author}]`,
value: track.title.slice(0, 100)
}));
} else {
logger.debug(`Found Genius lyrics for query '${query}'.`);
response = [
{
name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100),
value: lyricsResult.title.slice(0, 100)
}
];
}
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
recentQueries.set(interaction.user.id, {
lastQuery: query,
result: response,
timestamp: Date.now()
});
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
@@ -109,19 +48,19 @@ module.exports = {
if (!query) {
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
geniusSearchQuery = queue.currentTrack!.title.slice(0, 50);
@@ -249,7 +188,7 @@ module.exports = {
}
}
return;
return Promise.resolve();
}
logger.debug('Responding with info embed.');
@@ -267,3 +206,5 @@ module.exports = {
});
}
};
export default command;
@@ -7,20 +7,19 @@ import {
ButtonStyle,
ComponentType,
EmbedBuilder,
GuildMember,
Interaction,
SlashCommandBuilder
} from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams, TrackMetadata, CustomError } from '../../types/commandTypes';
import { EmbedOptions, PlayerOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction, TrackMetadata } from '../../../types/interactionTypes';
import { EmbedOptions, PlayerOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -28,7 +27,7 @@ module.exports = {
.setDescription('Show information about the track currently playing.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'nowplaying.js',
module: 'slashCommand',
@@ -39,21 +38,21 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
const sourceStringsFormatted = new Map([
@@ -110,15 +109,18 @@ module.exports = {
bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
}
const customId = `nowplaying-skip-button_${currentTrack.id}`;
logger.debug(`Generated custom id for skip button: ${customId}`);
const nowPlayingButton = new ButtonBuilder()
.setCustomId('nowplaying-skip')
.setCustomId(customId)
.setLabel('Skip track')
.setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.nextTrack)
.toJSON(); // Convert the builder to a raw object
.toJSON();
const nowPlayingActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow, // This might vary based on your discord.js version
type: ComponentType.ActionRow,
components: [nowPlayingButton]
};
@@ -134,7 +136,7 @@ module.exports = {
logger.debug('Successfully retrieved information about the current track.');
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
@@ -153,7 +155,7 @@ module.exports = {
? ''
: `**${
queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop
} Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.`
} Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.`
}`
)
.addFields(
@@ -183,130 +185,7 @@ module.exports = {
],
components: [nowPlayingActionRow as APIActionRowComponent<APIMessageActionRowComponent>]
});
logger.debug('Finished sending response.');
const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id;
try {
const confirmation = await response.awaitMessageComponent({
filter: collectorFilter,
time: 300_000
});
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
if (confirmation.customId === 'nowplaying-skip') {
logger.debug('Received skip confirmation.');
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
logger.debug('Tried skipping track but there was no queue.');
logger.debug('Responding with warning embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!`
)
.setColor(embedOptions.colors.warning)
],
components: []
});
}
if (queue.currentTrack !== currentTrack) {
logger.debug(
'Tried skipping track but it is not the current track and therefore already skipped/removed.'
);
logger.debug('Responding with warning embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.`
)
.setColor(embedOptions.colors.warning)
],
components: []
});
}
const skippedTrack = queue.currentTrack;
let durationFormat =
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
if (skippedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skip();
logger.debug('Skipped the track.');
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**` +
`${
queue.repeatMode === 0
? ''
: `\n\n**${
queue.repeatMode === 3
? embedOptions.icons.autoplaying
: embedOptions.icons.looping
} Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.`
}`
)
.setThumbnail(skippedTrack.thumbnail)
.setColor(embedOptions.colors.success)
],
components: []
});
}
} catch (error) {
if (error instanceof CustomError) {
if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.');
return;
}
if (error.message === 'Collector received no interactions before ending with reason: time') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
} else {
if (
error instanceof Error &&
error.message === 'Collector received no interactions before ending with reason: time'
) {
logger.debug('Interaction response timed out.');
return;
}
throw error;
}
}
}
};
export default command;
@@ -2,14 +2,15 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
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';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -17,7 +18,7 @@ module.exports = {
.setDescription('Pause or resume the current track.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'pause.js',
module: 'slashCommand',
@@ -28,21 +29,21 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
const currentTrack = queue.currentTrack!;
@@ -87,3 +88,5 @@ module.exports = {
});
}
};
export default command;
@@ -2,17 +2,16 @@ import config from 'config';
import { useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes';
import { BotOptions, EmbedOptions, PlayerOptions } from '../../types/configTypes';
import { cannotJoinVoiceOrTalk } from '../../utils/validation/permissionValidator';
import { transformQuery } from '../../utils/validation/searchQueryValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomError, CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { BotOptions, EmbedOptions, PlayerOptions } from '../../../types/configTypes';
import { cannotJoinVoiceOrTalk } from '../../../utils/validation/permissionValidator';
import { transformQuery } from '../../../utils/validation/searchQueryValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
const recentQueries = new Map();
const loggerTemplate = loggerModule.child({
source: 'play.js',
@@ -20,7 +19,7 @@ const loggerTemplate = loggerModule.child({
name: '/play'
});
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -37,59 +36,7 @@ module.exports = {
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const player = useMainPlayer()!;
const query = interaction.options.getString('query', true);
const { lastQuery, results, 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}'`);
return interaction.respond(results);
}
if (query.length < 3) {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const searchResults = await player.search(query);
let response = [];
response = searchResults.tracks.slice(0, 5).map((track) => {
if (track.url.length > 100) {
track.url = track.title.slice(0, 100);
}
return {
name:
`${track.title} [Author: ${track.author}]`.length > 100
? `${track.title}`.slice(0, 100)
: `${track.title} [Author: ${track.author}]`,
value: track.url
};
});
recentQueries.set(interaction.user.id, {
lastQuery: query,
results: response,
timestamp: Date.now()
});
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild?.shardId,
@@ -97,16 +44,16 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
if (await cannotJoinVoiceOrTalk({ interaction, executionId })) {
return;
return Promise.resolve();
}
let queue = useQueue(interaction.guild!.id);
if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) {
return;
return Promise.resolve();
}
const player = useMainPlayer()!;
@@ -185,7 +132,7 @@ module.exports = {
}
}));
} catch (error) {
if (error instanceof Error) {
if (error instanceof CustomError) {
if (error.message.includes('Sign in to confirm your age')) {
logger.debug('Found track but failed to retrieve audio due to age confirmation warning.');
@@ -219,12 +166,14 @@ module.exports = {
}
if (
error.message.includes("Cannot read properties of null (reading 'createStream')") ||
error.message === "Cannot read properties of null (reading 'createStream')" ||
error.message.includes('Failed to fetch resources for ytdl streaming') ||
error.message.includes('Could not extract stream for this track')
) {
logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`);
// note: reading 'createStream' error can happen if queue is destroyed before track starts playing, e.g. /leave quickly after /play
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
@@ -254,26 +203,6 @@ module.exports = {
});
}
if (error.message === "Cannot read properties of null (reading 'createStream')") {
// Can happen if /play then /leave before track starts playing
logger.warn(
error,
'Found track but failed to play back audio. Voice connection might be unavailable.'
);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and it was not possible to start playing the track. This could happen if the voice connection is lost or queue is destroyed while adding the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
logger.error(error, 'Failed to play track with player.play(), unhandled error.');
} else {
throw error;
@@ -352,7 +281,7 @@ module.exports = {
});
}
if (queue.currentTrack === track && queue.tracks.data.length === 0) {
if (queue && queue.currentTrack === track && queue.tracks.data.length === 0) {
logger.debug(`Track found and added with player.play(), started playing. Query: '${query}'.`);
let authorName: string;
@@ -411,3 +340,5 @@ module.exports = {
});
}
};
export default command;
@@ -2,14 +2,15 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions, PlayerOptions } from '../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions, PlayerOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -18,7 +19,7 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false)
.addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'queue.js',
module: 'slashCommand',
@@ -29,13 +30,13 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
const pageIndex = (interaction.options.getNumber('page') || 1) - 1;
@@ -136,7 +137,7 @@ module.exports = {
? ''
: `**${
queue.repeatMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop
} Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.\n\n`
} Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.\n\n`
}`;
if (!currentTrack) {
@@ -207,3 +208,5 @@ module.exports = {
}
}
};
export default command;
@@ -2,14 +2,15 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -24,7 +25,7 @@ module.exports = {
.setMinValue(1)
.setRequired(true)
),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'remove.js',
module: 'slashCommand',
@@ -35,17 +36,17 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
const removeTrackNumber = interaction.options.getNumber('tracknumber')!;
@@ -104,3 +105,5 @@ module.exports = {
});
}
};
export default command;
@@ -2,14 +2,15 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
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';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -23,7 +24,7 @@ module.exports = {
.setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.')
.setRequired(true)
),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'seek.js',
module: 'slashCommand',
@@ -34,21 +35,21 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
const durationInput = interaction.options.getString('duration');
@@ -186,3 +187,5 @@ module.exports = {
});
}
};
export default command;
@@ -2,14 +2,15 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueIsEmpty } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist, queueIsEmpty } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -17,7 +18,7 @@ module.exports = {
.setDescription('Shuffle tracks in the queue randomly.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'shuffle.js',
module: 'slashCommand',
@@ -28,21 +29,21 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await queueIsEmpty({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
queue.tracks.shuffle();
@@ -72,3 +73,5 @@ module.exports = {
});
}
};
export default command;
@@ -2,14 +2,15 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
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';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -20,7 +21,7 @@ module.exports = {
.addNumberOption((option) =>
option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1)
),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'skip.js',
module: 'slashCommand',
@@ -31,21 +32,21 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
const skipToTrack = interaction.options.getNumber('tracknumber');
@@ -171,7 +172,7 @@ module.exports = {
queue.repeatMode === 3
? embedOptions.icons.autoplaying
: embedOptions.icons.looping
} Looping**\nLoop mode is set to ${loopModeUserString}. You can change it with **\`/loop\`**.`
} Looping**\nLoop mode is set to **\`${loopModeUserString}\`**. You can change it with **\`/loop\`**.`
}`
)
.setThumbnail(skippedTrack.thumbnail)
@@ -181,3 +182,5 @@ module.exports = {
}
}
};
export default command;
@@ -2,13 +2,14 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -16,7 +17,7 @@ module.exports = {
.setDescription('Stop playing audio and clear the track queue.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'stop.js',
module: 'slashCommand',
@@ -27,7 +28,7 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
@@ -48,7 +49,7 @@ module.exports = {
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (!queue.deleted) {
@@ -82,3 +83,5 @@ module.exports = {
});
}
};
export default command;
@@ -2,14 +2,15 @@ import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { queueDoesNotExist } from '../../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
@@ -24,7 +25,7 @@ module.exports = {
.setMinValue(0)
.setMaxValue(100)
),
execute: async ({ interaction, executionId }: CommandParams) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'volume.js',
module: 'slashCommand',
@@ -35,17 +36,17 @@ module.exports = {
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
return Promise.resolve();
}
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
return Promise.resolve();
}
const volume = interaction.options.getNumber('percentage');
@@ -126,3 +127,5 @@ module.exports = {
}
}
};
export default command;
@@ -1,13 +1,14 @@
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notValidGuildId } from '../../utils/validation/systemCommandValidator';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isSystemCommand: true,
isNew: false,
isBeta: false,
@@ -16,7 +17,7 @@ module.exports = {
.setDescription('Show list of guilds where bot is added.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
source: 'guilds.js',
module: 'slashCommand',
@@ -27,19 +28,14 @@ module.exports = {
});
if (await notValidGuildId({ interaction, executionId })) {
return;
return Promise.resolve();
}
let shardGuilds: Guild[] = [];
let totalGuildCount = 0;
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
logger.debug('Fetching guilds from all shards.');
await client.shard
await client!.shard!
.broadcastEval((c) => {
return c.guilds.cache.map((guild) => {
return guild;
@@ -86,3 +82,5 @@ module.exports = {
});
}
};
export default command;
@@ -1,14 +1,15 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notValidGuildId } from '../../utils/validation/systemCommandValidator';
import loggerModule from '../../../services/logger';
import { ExtendedClient } from '../../../types/clientTypes';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isSystemCommand: true,
isNew: false,
isBeta: false,
@@ -17,7 +18,7 @@ module.exports = {
.setDescription('Reload the bot commands.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
source: 'reload.js',
module: 'slashCommand',
@@ -28,24 +29,15 @@ module.exports = {
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
return Promise.resolve();
}
try {
logger.debug('Reloading commands across all shards.');
await client.shard
.broadcastEval(
await client!
.shard!.broadcastEval(
async (shardClient: ExtendedClient, { executionId }) => {
if (!shardClient.registerClientCommands) {
return;
}
shardClient.registerClientCommands({ client: shardClient, executionId });
shardClient.registerClientCommands!({ client: shardClient, executionId });
},
{ context: { executionId: executionId } }
)
@@ -69,7 +61,7 @@ module.exports = {
});
}
const commands = client.commands?.map((command) => {
const commands = client!.commands?.map((command) => {
const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`;
});
@@ -82,3 +74,5 @@ module.exports = {
});
}
};
export default command;
@@ -1,14 +1,15 @@
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { CommandParams, ShardInfo } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notValidGuildId } from '../../utils/validation/systemCommandValidator';
import loggerModule from '../../../services/logger';
import { ExtendedClient } from '../../../types/clientTypes';
import { ShardInfo, CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isSystemCommand: true,
isNew: false,
isBeta: false,
@@ -34,7 +35,7 @@ module.exports = {
)
.addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)),
execute: async ({ interaction, client, executionId }: CommandParams) => {
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
source: 'shards.js',
module: 'slashCommand',
@@ -45,24 +46,15 @@ module.exports = {
});
if (await notValidGuildId({ interaction, executionId })) {
return;
return Promise.resolve();
}
let shardInfoList: ShardInfo[] = [];
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
logger.debug('Fetching player statistics and client values from each shard.');
try {
await client.shard
.broadcastEval((shardClient: ExtendedClient) => {
if (!shardClient.shard) {
return;
}
await client!
.shard!.broadcastEval((shardClient: ExtendedClient) => {
/* eslint-disable no-undef */
const playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = parseFloat(
@@ -70,7 +62,7 @@ module.exports = {
);
const shardInfo = {
shardId: shardClient.shard.ids[0],
shardId: shardClient.shard!.ids[0],
memUsage: nodeProcessMemUsageInMb,
guildCount: shardClient.guilds.cache.size,
guildMemberCount: shardClient.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0),
@@ -193,8 +185,10 @@ module.exports = {
.setDescription(`**${embedOptions.icons.server} Shard overview - ${shardCount} total shards**\n`)
.addFields(...embedFields)
.setColor(embedOptions.colors.info)
.setFooter({ text: `Shard id: ${client.shard.ids[0]}, page ${pageIndex + 1} of ${totalPages}` })
.setFooter({ text: `Shard id: ${client!.shard!.ids[0]}, page ${pageIndex + 1} of ${totalPages}` })
]
});
}
};
export default command;
@@ -3,16 +3,16 @@ 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';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted';
import { notValidGuildId } from '../../utils/validation/systemCommandValidator';
import { dependencies, version } from '../../../../package.json';
import loggerModule from '../../../services/logger';
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
import { EmbedOptions } from '../../../types/configTypes';
import { getUptimeFormatted } from '../../../utils/system/getUptimeFormatted';
import { notValidGuildId } from '../../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
const command: CustomSlashCommandInteraction = {
isSystemCommand: true,
isNew: false,
isBeta: false,
@@ -21,7 +21,7 @@ module.exports = {
.setDescription('Show the bot and system status.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }: CommandParams) => {
execute: async ({ interaction, client, executionId }) => {
const logger = loggerModule.child({
source: 'systemstatus.js',
module: 'slashCommand',
@@ -32,7 +32,7 @@ module.exports = {
});
if (await notValidGuildId({ interaction, executionId })) {
return;
return Promise.resolve();
}
// from normal /status command
@@ -61,13 +61,8 @@ module.exports = {
logger.debug('Fetching player statistics from all shards.');
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
await client.shard
.broadcastEval(() => {
await client!
.shard!.broadcastEval(() => {
/* eslint-disable no-undef */
return player.generateStatistics();
})
@@ -93,8 +88,8 @@ module.exports = {
});
logger.debug('Fetching client values from all shards.');
await client.shard
.fetchClientValues('guilds.cache')
await client!
.shard!.fetchClientValues('guilds.cache')
.then((results) => {
const guildCaches = results as Guild[][];
guildCaches.map((guildCache: Guild[]) => {
@@ -135,7 +130,7 @@ module.exports = {
`**${mediaplexVersion}** mediaplex\n` +
`**${distubeYtdlVersion}** @distube/ytdl-core`;
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
const discordStatusString = `**${client!.ws.ping} ms** Discord API latency`;
logger.debug('Transformed system status into embed description.');
@@ -171,3 +166,5 @@ module.exports = {
});
}
};
export default command;
@@ -0,0 +1,57 @@
import config from 'config';
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { CustomComponentInteraction } from '../../types/interactionTypes';
import { useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember } from 'discord.js';
const embedOptions: EmbedOptions = config.get('embedOptions');
const component: CustomComponentInteraction = {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'filters-disable-button.js',
module: 'componentInteraction',
name: 'filters-disable-button',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
logger.debug('Received disable confirmation.');
const queue = useQueue(interaction.guild!.id)!;
// Reset filters before enabling provided filters
if (queue.filters.ffmpeg.filters.length > 0) {
queue.filters.ffmpeg.setFilters(false);
logger.debug('Reset queue filters.');
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.`
)
.setColor(embedOptions.colors.success)
],
components: []
});
}
};
export default component;
@@ -0,0 +1,98 @@
import config from 'config';
import loggerModule from '../../services/logger';
import { EmbedOptions, FFmpegFilterOptions } from '../../types/configTypes';
import { CustomComponentInteraction } from '../../types/interactionTypes';
import { QueueFilters, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, StringSelectMenuInteraction } from 'discord.js';
const embedOptions: EmbedOptions = config.get('embedOptions');
const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions');
const component: CustomComponentInteraction = {
execute: async ({ interaction, executionId }) => {
const logger = loggerModule.child({
source: 'filters-select-menu.js',
module: 'componentInteraction',
name: 'filters-select-menu',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
logger.debug('Received select menu confirmation.');
const selectMenuInteraction = interaction as StringSelectMenuInteraction;
const queue = useQueue(selectMenuInteraction.guild!.id)!;
queue.filters.ffmpeg.setInputArgs([
'-threads',
ffmpegFilterOptions.threadAmount,
'-reconnect',
'1',
'-reconnect_streamed',
'1',
'-reconnect_delay_max',
'10',
'-vn'
]);
// Reset filters before enabling provided filters
if (queue.filters.ffmpeg.filters.length > 0) {
queue.filters.ffmpeg.setFilters(false);
logger.debug('Reset queue filters.');
}
// if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion
if (
(selectMenuInteraction.values.includes('bassboost_low') || selectMenuInteraction.values.includes('bassboost')) &&
!selectMenuInteraction.values.includes('normalizer')
) {
selectMenuInteraction.values.push('normalizer');
}
// Enable provided filters
queue.filters.ffmpeg.toggle(selectMenuInteraction.values as (keyof QueueFilters)[]);
logger.debug(`Enabled filters ${selectMenuInteraction.values.join(', ')}.`);
let authorName: string;
if (selectMenuInteraction.member instanceof GuildMember) {
authorName = selectMenuInteraction.member.nickname || selectMenuInteraction.user.username;
} else {
authorName = selectMenuInteraction.user.username;
}
logger.debug('Responding with success embed.');
return await selectMenuInteraction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: selectMenuInteraction.user.avatarURL() || ''
})
.setDescription(
`**${
embedOptions.icons.success
} Filters toggled**\nNow using these filters:\n${selectMenuInteraction.values
.map((enabledFilter: string) => {
const filter = ffmpegFilterOptions.availableFilters.find(
(filter) => enabledFilter == filter.value
);
if (!filter) {
return enabledFilter;
}
return `- **${filter.emoji} ${filter.label}**`;
})
.join('\n')}`
)
.setColor(embedOptions.colors.success)
],
components: []
});
}
};
export default component;
@@ -0,0 +1,116 @@
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember } from 'discord.js';
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { CustomComponentInteraction } from '../../types/interactionTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const component: CustomComponentInteraction = {
execute: async ({ interaction, referenceId, executionId }) => {
const logger = loggerModule.child({
source: 'nowplaying-skip.js',
module: 'componentInteraction',
name: 'nowplaying-skip',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
logger.debug(`Received skip confirmation for track id ${referenceId}.`);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
logger.debug('Tried skipping track but there was no queue.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!`
)
.setColor(embedOptions.colors.warning)
],
components: []
});
}
if (queue.currentTrack!.id !== referenceId) {
logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.`
)
.setColor(embedOptions.colors.warning)
],
components: []
});
}
const skippedTrack = queue.currentTrack!;
let durationFormat =
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
if (skippedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skip();
logger.debug('Skipped the track.');
const loopModesFormatted = new Map([
[0, 'disabled'],
[1, 'track'],
[2, 'queue'],
[3, 'autoplay']
]);
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${
skippedTrack.raw.url ?? skippedTrack.url
})**` +
`${
queue.repeatMode === 0
? ''
: `\n\n**${
queue.repeatMode === 3
? embedOptions.icons.autoplaying
: embedOptions.icons.looping
} Looping**\nLoop mode is set to ${repeatModeUserString}. You can change it with **\`/loop\`**.`
}`
)
.setThumbnail(skippedTrack.thumbnail)
.setColor(embedOptions.colors.success)
],
components: []
});
}
};
export default component;
+6 -13
View File
@@ -9,28 +9,19 @@ const loggerOptions: LoggerOptions = config.get('loggerOptions');
const targets: TargetOptions[] = [
{
// This target is used for logging everything above specified minimumLogLevel
target: 'pino/file',
level: loggerOptions.minimumLogLevel,
options: {
destination: './logs/app-all.log',
mkdir: true,
sync: false,
minLength: 4096
sync: false
}
},
{
// This target is used for logging errors separately
target: 'pino/file',
level: pino.levels.values.info.toString(),
options: {
destination: './logs/app-info.log',
mkdir: true,
sync: false,
minLength: 4096
}
},
{
target: 'pino/file',
level: pino.levels.values.error.toString(),
level: 'error',
options: {
destination: './logs/app-error.log',
mkdir: true,
@@ -38,6 +29,7 @@ const targets: TargetOptions[] = [
}
},
{
// This target is used for logging to the console
target: 'pino/file',
level: loggerOptions.minimumLogLevelConsole,
options: {
@@ -57,6 +49,7 @@ if (process.env.LOKI_AUTH_PASSWORD && process.env.LOKI_AUTH_USERNAME) {
batching: false,
interval: 5,
// Loki host and credentials are retrieved from environment variables
host: process.env.LOKI_HOST || 'http://localhost:3100',
basicAuth: {
username: process.env.LOKI_AUTH_USERNAME || '',
-38
View File
@@ -1,38 +0,0 @@
import { AutocompleteInteraction, ChatInputCommandInteraction } from 'discord.js';
import { ExtendedClient } from './clientTypes';
export interface CommandParams {
interaction: ChatInputCommandInteraction;
client: ExtendedClient | undefined;
executionId: string;
}
export interface CommandAutocompleteParams {
interaction: AutocompleteInteraction;
client: ExtendedClient | undefined;
executionId: string;
}
export interface ShardInfo {
shardId: number;
memUsage: number;
guildCount: number;
guildMemberCount: number;
playerStatistics: {
activeVoiceConnections: number;
totalTracks: number;
totalListeners: number;
};
}
export interface TrackMetadata {
bridge: {
views: number;
};
}
export class CustomError extends Error {
type?: string;
code?: string;
}
+5 -5
View File
@@ -1,6 +1,6 @@
import {
ActivityType, ColorResolvable, PresenceUpdateStatus, ShardingManagerOptions
} from 'discord.js';
import { ActivityType, ColorResolvable, PresenceUpdateStatus, ShardingManagerOptions } from 'discord.js';
import { LogLevel } from './serviceTypes';
export interface BotOptions {
name: string;
@@ -11,8 +11,8 @@ export interface BotOptions {
export interface ShardingOptions extends ShardingManagerOptions {}
export interface LoggerOptions {
minimumLogLevel: string;
minimumLogLevelConsole: string;
minimumLogLevel: LogLevel;
minimumLogLevelConsole: LogLevel;
discordPlayerDebug: boolean;
}
+68
View File
@@ -0,0 +1,68 @@
import {
ApplicationCommandOptionChoiceData,
AutocompleteInteraction,
ChatInputCommandInteraction,
Message,
MessageComponentInteraction,
SlashCommandBuilder
} from 'discord.js';
import { ExtendedClient } from './clientTypes';
// Local types
interface CommandParams {
client?: ExtendedClient;
executionId: string;
interaction: ChatInputCommandInteraction;
}
interface AutocompleteParams {
executionId: string;
interaction: AutocompleteInteraction;
}
interface ComponentParams {
interaction: MessageComponentInteraction;
referenceId?: string;
executionId: string;
}
// Interaction types
export interface CustomSlashCommandInteraction {
isNew: boolean;
isBeta: boolean;
isSystemCommand?: boolean;
data: Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;
execute(params: CommandParams): Promise<Message<boolean> | void>;
}
export interface CustomAutocompleteInteraction {
execute(params: AutocompleteParams): Promise<ApplicationCommandOptionChoiceData | void>;
}
export interface CustomComponentInteraction {
execute(params: ComponentParams): Promise<Message<boolean> | void>;
}
// Command specific types
export interface ShardInfo {
shardId: number;
memUsage: number;
guildCount: number;
guildMemberCount: number;
playerStatistics: {
activeVoiceConnections: number;
totalTracks: number;
totalListeners: number;
};
}
export interface TrackMetadata {
bridge: {
views: number;
};
}
export class CustomError extends Error {
type?: string;
code?: string;
}
+3 -1
View File
@@ -1,6 +1,8 @@
export type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent';
export type TargetOptions = {
target: string;
level: string;
level: LogLevel;
options: {
destination?: string;
mkdir?: boolean;
+9
View File
@@ -14,6 +14,15 @@ export interface RegisterClientCommandsParams {
executionId: string;
}
export interface CustomEvent {
name: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
execute: (...args: any) => void;
once?: boolean;
isDebug?: boolean;
isPlayerEvent?: boolean;
}
export interface NotInVoiceChannelParams {
interaction: ChatInputCommandInteraction;
executionId: string;
+3 -2
View File
@@ -15,7 +15,7 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams)
try {
if (client.shard?.ids[0] !== 0) {
return;
return Promise.resolve();
}
let guildCount = 0;
@@ -128,7 +128,8 @@ export const postBotStats = async ({ client, executionId }: PostBotStatsParams)
sites.map((site) => {
if (!site.enabled) {
return;
// return if site is disabled
return Promise.resolve();
}
const options = {
+1 -1
View File
@@ -18,7 +18,7 @@ export const startLoadTest = async ({ client, executionId }: StartLoadTestParams
if (!loadTestOptions.enabled) {
logger.debug('Load test is disabled in options, cancelling.');
return;
return Promise.resolve();
}
const channelIds = loadTestOptions.channelIdsToJoin;
+9 -8
View File
@@ -5,7 +5,7 @@ import path from 'node:path';
import loggerModule from '../services/logger';
import { RegisterClientCommandsParams } from '../types/utilTypes';
export const registerClientCommands = ({ client, executionId }: RegisterClientCommandsParams) => {
export const registerClientCommands = async ({ client, executionId }: RegisterClientCommandsParams) => {
const logger = loggerModule.child({
source: 'registerClientCommands.js',
module: 'register',
@@ -17,23 +17,24 @@ export const registerClientCommands = ({ client, executionId }: RegisterClientCo
logger.debug('Registering client commands...');
client.commands = new Collection();
const commandFolders = fs.readdirSync(path.resolve('./dist/commands'));
const commandFolders = fs.readdirSync(path.resolve('./dist/interactions/commands'));
for (const folder of commandFolders) {
logger.trace(`Registering client commands for folder '${folder}'...`);
const commandFiles = fs
.readdirSync(path.resolve(`./dist/commands/${folder}`))
.readdirSync(path.resolve(`./dist/interactions/commands/${folder}`))
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
try {
// delete command from require cache
delete require.cache[require.resolve(`../commands/${folder}/${file}`)];
delete require.cache[require.resolve(`../interactions/commands/${folder}/${file}`)];
// register command
/* eslint-disable @typescript-eslint/no-var-requires */
const command = require(`../commands/${folder}/${file}`);
client.commands.delete(command.data.name);
client.commands.set(command.data.name, command);
//const command = require(`../interactions/commands/${folder}/${file}`);
const commandModule = await import(`../interactions/commands/${folder}/${file}`);
client.commands.delete(commandModule.default.data.name);
client.commands.set(commandModule.default.data.name, commandModule.default);
} catch (error) {
if (error instanceof Error) {
logger.error(`Error registering command ${folder}/${file}: ${error.message}`);
+40 -27
View File
@@ -2,16 +2,46 @@ import config from 'config';
import fs from 'node:fs';
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 {
ClientEventArguments, PlayerEventArguments, ProcessEventArguments
} from '../types/eventTypes';
import { RegisterEventListenersParams } from '../types/utilTypes';
import { ClientEventArguments, PlayerEventArguments, ProcessEventArguments } from '../types/eventTypes';
import { CustomEvent, RegisterEventListenersParams } from '../types/utilTypes';
const loggerOptions: LoggerOptions = config.get('loggerOptions');
export const registerEventListeners = ({ client, player, executionId }: RegisterEventListenersParams) => {
const registerClientEventListeners = (client: Client, event: CustomEvent) => {
if (event.once) {
client.once(event.name, (...args: ClientEventArguments) => event.execute(...args));
} else {
if (!event.isDebug || process.env.MINIMUM_LOG_LEVEL === 'debug') {
client.on(event.name, (...args: ClientEventArguments) => event.execute(...args));
}
}
};
const registerInteractionEventListeners = (client: Client, event: CustomEvent) => {
client.on(event.name, (...args: ClientEventArguments) => event.execute(...args, { client }));
};
const registerProcessEventListeners = (event: CustomEvent) => {
process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args));
};
const registerPlayerEventListeners = (player: Player, event: CustomEvent, loggerOptions: LoggerOptions) => {
if (!event.isDebug || (loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug)) {
if (event.isPlayerEvent) {
player.events.on(event.name as keyof GuildQueueEvents, (...args: PlayerEventArguments) =>
event.execute(...args)
);
} else {
player.on(event.name as keyof PlayerEvents, (...args: PlayerEventArguments) => event.execute(...args));
}
}
};
export const registerEventListeners = async ({ client, player, executionId }: RegisterEventListenersParams) => {
const logger = loggerModule.child({
source: 'registerEventListeners.js',
module: 'register',
@@ -31,39 +61,22 @@ export const registerEventListeners = ({ client, player, executionId }: Register
.filter((file) => file.endsWith('.js'));
for (const file of eventFiles) {
/* eslint-disable @typescript-eslint/no-var-requires */
const event = require(`../events/${folder}/${file}`);
const event = await import(`../events/${folder}/${file}`);
switch (folder) {
case 'client':
if (event.once) {
client.once(event.name, (...args: ClientEventArguments) => event.execute(...args));
} else {
if (!event.isDebug || process.env.MINIMUM_LOG_LEVEL === 'debug') {
client.on(event.name, (...args: ClientEventArguments) => event.execute(...args));
}
}
registerClientEventListeners(client, event);
break;
case 'interactions':
client.on(event.name, (...args: ClientEventArguments) => event.execute(...args, { client }));
registerInteractionEventListeners(client, event);
break;
case 'process':
process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args));
registerProcessEventListeners(event);
break;
case 'player':
if (
!event.isDebug ||
(loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug)
) {
if (event.isPlayerEvent) {
player.events.on(event.name, (...args: PlayerEventArguments) => event.execute(...args));
break;
} else {
player.on(event.name, (...args: PlayerEventArguments) => event.execute(...args));
}
}
registerPlayerEventListeners(player, event, loggerOptions);
break;
default:
+18 -12
View File
@@ -3,9 +3,7 @@ import { EmbedBuilder, GuildMember, TextChannel, VoiceChannel } from 'discord.js
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import {
CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams
} from '../../types/utilTypes';
import { CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams } from '../../types/utilTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: CannotJoinVoiceOrTalkParams) => {
@@ -61,17 +59,24 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C
try {
// we can still send ephemeral replies in channels we can't view, so sending message to user instead
if (!interaction.deferred && !interaction.replied) {
logger.debug('Interaction was not deferred or replied to yet. Deferring reply as ephemeral.');
await interaction.deferReply({ ephemeral: true });
logger.debug(
'Sending ephemeral message in channel about insufficient permissions to send message in channel.'
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nI do not have permission to send message replies in the channel you are in.\n\nPlease make sure I have the **\`View Channel\`** permission in this text channel.`
)
.setColor(embedOptions.colors.warning)
]
});
} else {
return Promise.resolve();
}
await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nI do not have permission to send message replies in the channel you are in.\n\nPlease make sure I have the **\`View Channel\`** permission in this text channel.`
)
.setColor(embedOptions.colors.warning)
]
});
} catch (error) {
if (error instanceof Error) {
if (error.message == 'The reply to this interaction has already been sent or deferred.') {
@@ -86,6 +91,7 @@ export const cannotSendMessageInChannel = async ({ interaction, executionId }: C
);
}
} else {
logger.debug('Throwing error');
throw error;
}
}