mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-03 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 { BotOptions, EmbedOptions } from '../../types/configTypes';
|
||||
import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator';
|
||||
import { CustomError } from '../../types/interactionTypes';
|
||||
|
||||
const embedOptions: EmbedOptions = config.get('embedOptions');
|
||||
const botOptions: BotOptions = config.get('botOptions');
|
||||
@@ -21,6 +22,7 @@ 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',
|
||||
@@ -31,25 +33,39 @@ module.exports = {
|
||||
guildId: interaction.guild?.id
|
||||
});
|
||||
|
||||
let interactionString: string = '';
|
||||
const interactionType: InteractionType = interaction.type;
|
||||
logger.debug('Interaction received.');
|
||||
|
||||
let interactionString: string = '';
|
||||
|
||||
// Todo: Extract to own file
|
||||
const handleComponent = async (interaction: MessageComponentInteraction) => {
|
||||
await interaction.deferReply();
|
||||
logger.debug('Interaction deferred.');
|
||||
|
||||
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`);
|
||||
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 command = client.commands?.get(interaction.commandName) as Command;
|
||||
const autocompleteModule = await import(`../../interactions/autocomplete/${interaction.commandName}.js`);
|
||||
const { default: autocomplete } = autocompleteModule;
|
||||
|
||||
logger.debug('Executing autocomplete interaction.');
|
||||
await autocomplete.execute({ interaction, executionId });
|
||||
};
|
||||
|
||||
const handleCommand = async (interaction: ChatInputCommandInteraction) => {
|
||||
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.`);
|
||||
@@ -57,258 +73,113 @@ module.exports = {
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
logger.debug('Executing command interaction.');
|
||||
await command.execute({ interaction, client, executionId });
|
||||
};
|
||||
|
||||
/* doesnt work because need to find subfolder
|
||||
/* Update registerClientCommands to registerClientInteractions
|
||||
/* Add client.interactions with { commandInteractions, componentInteractions, autocompleteInteractions
|
||||
const commandModule = await import(`../../interactions/commands/SUBFOLDER/${interaction.commandName}.js`);
|
||||
const { default: command } = commandModule;
|
||||
await command.execute({ interaction, client, executionId });
|
||||
*/
|
||||
// TODO: Extract the text to a config file?
|
||||
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}` })
|
||||
]
|
||||
};
|
||||
|
||||
const outputTime: number = new Date().getTime();
|
||||
const executionTime: number = outputTime - inputTime;
|
||||
// TODO: extract handlError to own file (create errorHandler and export handleInteractionError?)
|
||||
const handleError = async (interaction: Interaction, error: CustomError) => {
|
||||
logger.error(error, `Error handling interaction of type '${interactionString}'`);
|
||||
|
||||
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.');
|
||||
if (interaction instanceof ChatInputCommandInteraction && 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;
|
||||
} 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;
|
||||
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 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 {
|
||||
switch (interactionType) {
|
||||
logger.debug('Started handling interaction.');
|
||||
switch (interaction.type as InteractionType) {
|
||||
case InteractionType.ApplicationCommand:
|
||||
interactionString = 'ApplicationCommand';
|
||||
handleCommand(interaction as ChatInputCommandInteraction);
|
||||
await handleCommand(interaction as ChatInputCommandInteraction);
|
||||
break;
|
||||
|
||||
case InteractionType.ApplicationCommandAutocomplete:
|
||||
interactionString = 'ApplicationCommandAutocomplete';
|
||||
handleAutocomplete(interaction as AutocompleteInteraction);
|
||||
await handleAutocomplete(interaction as AutocompleteInteraction);
|
||||
break;
|
||||
|
||||
case InteractionType.MessageComponent:
|
||||
interactionString = 'MessageComponent';
|
||||
handleComponent(interaction as MessageComponentInteraction);
|
||||
await handleComponent(interaction as MessageComponentInteraction);
|
||||
break;
|
||||
|
||||
default:
|
||||
interactionString = 'Unknown';
|
||||
break;
|
||||
}
|
||||
|
||||
logger.debug(`Interaction of type '${interactionString}' created.`);
|
||||
} catch (error) {
|
||||
logger.error(error, `Error handling interaction of type '${interactionString}'`);
|
||||
|
||||
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;
|
||||
}
|
||||
logger.debug('Error while handling received interaction.');
|
||||
await handleError(interaction, error as CustomError);
|
||||
}
|
||||
|
||||
/*
|
||||
if (interaction.isAutocomplete()) {
|
||||
const outputTime: number = new Date().getTime();
|
||||
const executionTime: number = outputTime - inputTime;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
logger.info(`Interaction of type '${interactionString}' handled in ${executionTime} ms.`);
|
||||
return;
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user