mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-04 14:38:49 +00:00
feat!: better handling and error handling for interaction events
This commit is contained in:
1 parent
1ec1281e98
commit
f231c53fe8
6 files changed
+270
-361
No files matched your search
@@ -14,6 +14,7 @@ import loggerModule from '../../services/logger';
|
|||||||
import { Command, ExtendedClient } from '../../types/clientTypes';
|
import { Command, ExtendedClient } from '../../types/clientTypes';
|
||||||
import { BotOptions, EmbedOptions } from '../../types/configTypes';
|
import { BotOptions, EmbedOptions } from '../../types/configTypes';
|
||||||
import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator';
|
import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator';
|
||||||
|
import { CustomError } from '../../types/interactionTypes';
|
||||||
|
|
||||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||||
const botOptions: BotOptions = config.get('botOptions');
|
const botOptions: BotOptions = config.get('botOptions');
|
||||||
@@ -21,6 +22,7 @@ module.exports = {
|
|||||||
name: Events.InteractionCreate,
|
name: Events.InteractionCreate,
|
||||||
isDebug: false,
|
isDebug: false,
|
||||||
execute: async (interaction: Interaction, { client }: { client: ExtendedClient }) => {
|
execute: async (interaction: Interaction, { client }: { client: ExtendedClient }) => {
|
||||||
|
const inputTime: number = new Date().getTime();
|
||||||
const executionId = uuidv4();
|
const executionId = uuidv4();
|
||||||
const logger = loggerModule.child({
|
const logger = loggerModule.child({
|
||||||
source: 'interactionCreate.js',
|
source: 'interactionCreate.js',
|
||||||
@@ -31,25 +33,39 @@ module.exports = {
|
|||||||
guildId: interaction.guild?.id
|
guildId: interaction.guild?.id
|
||||||
});
|
});
|
||||||
|
|
||||||
let interactionString: string = '';
|
logger.debug('Interaction received.');
|
||||||
const interactionType: InteractionType = interaction.type;
|
|
||||||
|
|
||||||
|
let interactionString: string = '';
|
||||||
|
|
||||||
|
// Todo: Extract to own file
|
||||||
const handleComponent = async (interaction: MessageComponentInteraction) => {
|
const handleComponent = async (interaction: MessageComponentInteraction) => {
|
||||||
await interaction.deferReply();
|
await interaction.deferReply();
|
||||||
|
logger.debug('Interaction deferred.');
|
||||||
|
|
||||||
const componentId = interaction.customId.split('_')[0];
|
const componentId = interaction.customId.split('_')[0];
|
||||||
const trackId = interaction.customId.split('_')[1];
|
const referenceId = interaction.customId.split('_')[1];
|
||||||
|
|
||||||
|
logger.debug(`Parsed componentId: ${componentId}`);
|
||||||
|
|
||||||
const componentModule = await import(`../../interactions/components/${componentId}.js`);
|
const componentModule = await import(`../../interactions/components/${componentId}.js`);
|
||||||
await componentModule.execute({ interaction, trackId, executionId });
|
const { default: component } = componentModule;
|
||||||
|
|
||||||
|
logger.debug('Executing component interaction.');
|
||||||
|
await component.execute({ interaction, referenceId, executionId });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAutocomplete = async (interaction: AutocompleteInteraction) => {
|
const handleAutocomplete = async (interaction: AutocompleteInteraction) => {
|
||||||
//const command = client.commands?.get(interaction.commandName) as Command;
|
|
||||||
const autocompleteModule = await import(`../../interactions/autocomplete/${interaction.commandName}.js`);
|
const autocompleteModule = await import(`../../interactions/autocomplete/${interaction.commandName}.js`);
|
||||||
const { default: autocomplete } = autocompleteModule;
|
const { default: autocomplete } = autocompleteModule;
|
||||||
|
|
||||||
|
logger.debug('Executing autocomplete interaction.');
|
||||||
await autocomplete.execute({ interaction, executionId });
|
await autocomplete.execute({ interaction, executionId });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCommand = async (interaction: ChatInputCommandInteraction) => {
|
const handleCommand = async (interaction: ChatInputCommandInteraction) => {
|
||||||
|
await interaction.deferReply();
|
||||||
|
logger.debug('Interaction deferred.');
|
||||||
|
|
||||||
const command = client.commands?.get(interaction.commandName) as Command;
|
const command = client.commands?.get(interaction.commandName) as Command;
|
||||||
if (!command) {
|
if (!command) {
|
||||||
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
|
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
|
||||||
@@ -57,258 +73,113 @@ module.exports = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`);
|
logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`);
|
||||||
//try {
|
|
||||||
await interaction.deferReply();
|
|
||||||
|
|
||||||
if (await cannotSendMessageInChannel({ interaction, executionId })) {
|
if (await cannotSendMessageInChannel({ interaction, executionId })) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const inputTime: number = new Date().getTime();
|
logger.debug('Executing command interaction.');
|
||||||
|
|
||||||
await command.execute({ interaction, client, executionId });
|
await command.execute({ interaction, client, executionId });
|
||||||
|
};
|
||||||
|
|
||||||
/* doesnt work because need to find subfolder
|
// TODO: Extract the text to a config file?
|
||||||
/* Update registerClientCommands to registerClientInteractions
|
const errorReply = {
|
||||||
/* Add client.interactions with { commandInteractions, componentInteractions, autocompleteInteractions
|
embeds: [
|
||||||
const commandModule = await import(`../../interactions/commands/SUBFOLDER/${interaction.commandName}.js`);
|
new EmbedBuilder()
|
||||||
const { default: command } = commandModule;
|
.setDescription(
|
||||||
await command.execute({ interaction, client, executionId });
|
`**${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}` })
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
const outputTime: number = new Date().getTime();
|
// TODO: extract handlError to own file (create errorHandler and export handleInteractionError?)
|
||||||
const executionTime: number = outputTime - inputTime;
|
const handleError = async (interaction: Interaction, error: CustomError) => {
|
||||||
|
logger.error(error, `Error handling interaction of type '${interactionString}'`);
|
||||||
|
|
||||||
logger.info(`Command '${interaction}' executed in ${executionTime} ms.`);
|
if (interaction instanceof ChatInputCommandInteraction && interaction.deferred) {
|
||||||
/*
|
switch (interaction.replied) {
|
||||||
} catch (error) {
|
case true:
|
||||||
if (error instanceof Error) {
|
// This means interaction has received a reply already.
|
||||||
logger.warn(
|
// Most likely command executed successfully or error is already handled.
|
||||||
error,
|
logger.warn(
|
||||||
`Command '${interaction}' throwed an unhandled error and might have failed to execute properly.`
|
error,
|
||||||
);
|
`Interaction '${interaction.id}' threw an error but has already been replied to.`
|
||||||
|
);
|
||||||
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;
|
return;
|
||||||
} else {
|
case false:
|
||||||
if (!interaction.deferred || !interaction.replied) {
|
// If the interaction has not been replied to, most likely command execution failed.
|
||||||
logger.warn('Interaction was not deferred or replied to, and an error was thrown.');
|
logger.debug('Responding with error embed');
|
||||||
return;
|
return await interaction.editReply(errorReply);
|
||||||
}
|
|
||||||
|
|
||||||
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 instanceof MessageComponentInteraction && interaction.deferred) {
|
||||||
|
switch (interaction.replied) {
|
||||||
|
case true:
|
||||||
|
// This means interaction has received a reply already.
|
||||||
|
// Most likely command executed successfully or error is already handled.
|
||||||
|
logger.warn(
|
||||||
|
error,
|
||||||
|
`Interaction '${interaction.id}' threw an error but has already been replied to.`
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
case false:
|
||||||
|
// If the interaction has not been replied to, most likely command execution failed.
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If this code is reached there is an error that is not handled at all.
|
||||||
|
// This should not happen, but if it does, we log it with 'fatal' level to investigate.
|
||||||
|
// This is to prevent the bot from crashing or doing something very unexpected.
|
||||||
|
logger.fatal(error, 'Unhandled error while awaiting or handling component interaction.');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
switch (interactionType) {
|
logger.debug('Started handling interaction.');
|
||||||
|
switch (interaction.type as InteractionType) {
|
||||||
case InteractionType.ApplicationCommand:
|
case InteractionType.ApplicationCommand:
|
||||||
interactionString = 'ApplicationCommand';
|
interactionString = 'ApplicationCommand';
|
||||||
handleCommand(interaction as ChatInputCommandInteraction);
|
await handleCommand(interaction as ChatInputCommandInteraction);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case InteractionType.ApplicationCommandAutocomplete:
|
case InteractionType.ApplicationCommandAutocomplete:
|
||||||
interactionString = 'ApplicationCommandAutocomplete';
|
interactionString = 'ApplicationCommandAutocomplete';
|
||||||
handleAutocomplete(interaction as AutocompleteInteraction);
|
await handleAutocomplete(interaction as AutocompleteInteraction);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case InteractionType.MessageComponent:
|
case InteractionType.MessageComponent:
|
||||||
interactionString = 'MessageComponent';
|
interactionString = 'MessageComponent';
|
||||||
handleComponent(interaction as MessageComponentInteraction);
|
await handleComponent(interaction as MessageComponentInteraction);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
interactionString = 'Unknown';
|
interactionString = 'Unknown';
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug(`Interaction of type '${interactionString}' created.`);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(error, `Error handling interaction of type '${interactionString}'`);
|
logger.debug('Error while handling received interaction.');
|
||||||
|
await handleError(interaction, error as CustomError);
|
||||||
const errorReply = {
|
|
||||||
embeds: [
|
|
||||||
new EmbedBuilder()
|
|
||||||
.setDescription(
|
|
||||||
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
|
|
||||||
)
|
|
||||||
.setColor(embedOptions.colors.error)
|
|
||||||
.setFooter({ text: `Execution ID: ${executionId}` })
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleErrorWithReplyToUser = async (interaction: Interaction, error: Error) => {
|
|
||||||
logger.error(error, `Error handling interaction of type '${interactionString}'`);
|
|
||||||
if (interaction.channel) {
|
|
||||||
// Send message to user in channel where interaction was made
|
|
||||||
logger.debug(`Sending error reply to channel '${interaction.channel.id}'.`);
|
|
||||||
await interaction.channel.send(errorReply);
|
|
||||||
} else {
|
|
||||||
// Send message to user in DMs
|
|
||||||
logger.debug(`Sending error reply to user '${interaction.user.id}'.`);
|
|
||||||
await interaction.user.send(errorReply);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
switch (true) {
|
|
||||||
case interaction instanceof ChatInputCommandInteraction:
|
|
||||||
await handleErrorWithReplyToUser(interaction, error as Error);
|
|
||||||
break;
|
|
||||||
case interaction instanceof AutocompleteInteraction:
|
|
||||||
await handleErrorWithReplyToUser(interaction, error as Error);
|
|
||||||
break;
|
|
||||||
case interaction instanceof MessageComponentInteraction:
|
|
||||||
await handleErrorWithReplyToUser(interaction, error as Error);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
// Something else went wrong
|
|
||||||
logger.error(error, 'Unhandled error while handling unkown interaction.');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
const outputTime: number = new Date().getTime();
|
||||||
if (interaction.isAutocomplete()) {
|
const executionTime: number = outputTime - inputTime;
|
||||||
|
|
||||||
try {
|
logger.info(`Interaction of type '${interactionString}' handled in ${executionTime} ms.`);
|
||||||
command?.autocomplete && (await command?.autocomplete({ interaction, executionId }));
|
return;
|
||||||
} 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
/*
|
|
||||||
if (interaction.isChatInputCommand()) {
|
|
||||||
const command = client.commands?.get(interaction.commandName) as Command;
|
|
||||||
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();
|
|
||||||
|
|
||||||
if (await cannotSendMessageInChannel({ interaction, executionId })) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -7,15 +7,13 @@ import {
|
|||||||
ButtonStyle,
|
ButtonStyle,
|
||||||
ComponentType,
|
ComponentType,
|
||||||
EmbedBuilder,
|
EmbedBuilder,
|
||||||
GuildMember,
|
|
||||||
Interaction,
|
|
||||||
SlashCommandBuilder,
|
SlashCommandBuilder,
|
||||||
StringSelectMenuBuilder,
|
StringSelectMenuBuilder,
|
||||||
StringSelectMenuOptionBuilder
|
StringSelectMenuOptionBuilder
|
||||||
} from 'discord.js';
|
} from 'discord.js';
|
||||||
|
|
||||||
import loggerModule from '../../../services/logger';
|
import loggerModule from '../../../services/logger';
|
||||||
import { CustomError, CustomSlashCommandInteraction } from '../../../types/interactionTypes';
|
import { CustomSlashCommandInteraction } from '../../../types/interactionTypes';
|
||||||
import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes';
|
import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../../types/configTypes';
|
||||||
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
|
import { queueDoesNotExist, queueNoCurrentTrack } from '../../../utils/validation/queueValidator';
|
||||||
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
|
import { notInSameVoiceChannel, notInVoiceChannel } from '../../../utils/validation/voiceChannelValidator';
|
||||||
@@ -79,7 +77,7 @@ const command: CustomSlashCommandInteraction = {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const filterSelect = new StringSelectMenuBuilder()
|
const filterSelect = new StringSelectMenuBuilder()
|
||||||
.setCustomId('filters')
|
.setCustomId('filters-select-menu')
|
||||||
.setPlaceholder('Select multiple options.')
|
.setPlaceholder('Select multiple options.')
|
||||||
.setMinValues(0)
|
.setMinValues(0)
|
||||||
.setMaxValues(filterOptions.length)
|
.setMaxValues(filterOptions.length)
|
||||||
@@ -92,7 +90,7 @@ const command: CustomSlashCommandInteraction = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const disableButton = new ButtonBuilder()
|
const disableButton = new ButtonBuilder()
|
||||||
.setCustomId('disable-filters')
|
.setCustomId('filters-disable-button')
|
||||||
.setLabel('Disable all filters')
|
.setLabel('Disable all filters')
|
||||||
.setStyle(ButtonStyle.Secondary)
|
.setStyle(ButtonStyle.Secondary)
|
||||||
.setEmoji(embedOptions.icons.disable)
|
.setEmoji(embedOptions.icons.disable)
|
||||||
@@ -104,7 +102,7 @@ const command: CustomSlashCommandInteraction = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
logger.debug('Sending info embed with action row components.');
|
logger.debug('Sending info embed with action row components.');
|
||||||
const response = await interaction.editReply({
|
return await interaction.editReply({
|
||||||
embeds: [
|
embeds: [
|
||||||
new EmbedBuilder()
|
new EmbedBuilder()
|
||||||
.setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.')
|
.setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.')
|
||||||
@@ -112,130 +110,6 @@ const command: CustomSlashCommandInteraction = {
|
|||||||
],
|
],
|
||||||
components: [filterActionRow, disableFiltersActionRow]
|
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -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.info('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,100 @@
|
|||||||
|
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.info('Received select menu confirmation.');
|
||||||
|
|
||||||
|
const queue = useQueue(interaction.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 (!(interaction instanceof StringSelectMenuInteraction)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion
|
||||||
|
if (
|
||||||
|
(interaction.values.includes('bassboost_low') || interaction.values.includes('bassboost')) &&
|
||||||
|
!interaction.values.includes('normalizer')
|
||||||
|
) {
|
||||||
|
interaction.values.push('normalizer');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enable provided filters
|
||||||
|
queue.filters.ffmpeg.toggle(interaction.values as (keyof QueueFilters)[]);
|
||||||
|
logger.debug(`Enabled filters ${interaction.values.join(', ')}.`);
|
||||||
|
|
||||||
|
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
|
||||||
|
} Filters toggled**\nNow using these filters:\n${interaction.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;
|
||||||
@@ -8,7 +8,7 @@ import { CustomComponentInteraction } from '../../types/interactionTypes';
|
|||||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||||
|
|
||||||
const component: CustomComponentInteraction = {
|
const component: CustomComponentInteraction = {
|
||||||
execute: async ({ interaction, trackId, executionId }) => {
|
execute: async ({ interaction, referenceId, executionId }) => {
|
||||||
const logger = loggerModule.child({
|
const logger = loggerModule.child({
|
||||||
source: 'nowplaying-skip.js',
|
source: 'nowplaying-skip.js',
|
||||||
module: 'componentInteraction',
|
module: 'componentInteraction',
|
||||||
@@ -20,7 +20,7 @@ const component: CustomComponentInteraction = {
|
|||||||
|
|
||||||
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
|
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
|
||||||
|
|
||||||
logger.debug(`Received skip confirmation for track id ${trackId}.`);
|
logger.debug(`Received skip confirmation for track id ${referenceId}.`);
|
||||||
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
|
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
|
||||||
logger.debug('Tried skipping track but there was no queue.');
|
logger.debug('Tried skipping track but there was no queue.');
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ const component: CustomComponentInteraction = {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (queue.currentTrack!.id !== trackId) {
|
if (queue.currentTrack!.id !== referenceId) {
|
||||||
logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.');
|
logger.debug('Tried skipping track but it is not the current track and therefore already skipped/removed.');
|
||||||
|
|
||||||
logger.debug('Responding with warning embed.');
|
logger.debug('Responding with warning embed.');
|
||||||
|
|||||||
@@ -1,4 +1,11 @@
|
|||||||
import { AutocompleteInteraction, ChatInputCommandInteraction, Message, MessageComponentInteraction, SlashCommandBuilder } from 'discord.js';
|
import {
|
||||||
|
ApplicationCommandOptionChoiceData,
|
||||||
|
AutocompleteInteraction,
|
||||||
|
ChatInputCommandInteraction,
|
||||||
|
Message,
|
||||||
|
MessageComponentInteraction,
|
||||||
|
SlashCommandBuilder
|
||||||
|
} from 'discord.js';
|
||||||
import { ExtendedClient } from './clientTypes';
|
import { ExtendedClient } from './clientTypes';
|
||||||
|
|
||||||
// Local types
|
// Local types
|
||||||
@@ -15,7 +22,7 @@ interface AutocompleteParams {
|
|||||||
|
|
||||||
interface ComponentParams {
|
interface ComponentParams {
|
||||||
interaction: MessageComponentInteraction;
|
interaction: MessageComponentInteraction;
|
||||||
trackId?: string;
|
referenceId?: string;
|
||||||
executionId: string;
|
executionId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,15 +32,15 @@ export interface CustomSlashCommandInteraction {
|
|||||||
isBeta: boolean;
|
isBeta: boolean;
|
||||||
isSystemCommand?: boolean;
|
isSystemCommand?: boolean;
|
||||||
data: Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;
|
data: Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>;
|
||||||
execute(params: CommandParams): Promise<Message<boolean> | undefined>;
|
execute(params: CommandParams): Promise<Message<boolean> | void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CustomAutocompleteInteraction {
|
export interface CustomAutocompleteInteraction {
|
||||||
execute(params: AutocompleteParams): Promise<void>;
|
execute(params: AutocompleteParams): Promise<ApplicationCommandOptionChoiceData | void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CustomComponentInteraction {
|
export interface CustomComponentInteraction {
|
||||||
execute(params: ComponentParams): Promise<Message<boolean> | undefined>;
|
execute(params: ComponentParams): Promise<Message<boolean> | void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Command specific types
|
// Command specific types
|
||||||
|
|||||||
Reference in new issue
Block a user