import { Interaction, Client as DiscordClient } from "discord.js"; import requireDirectory from "require-directory"; import Command from "./command"; export default class CommandManager { readonly commands: Command[] = []; constructor(directory = "./commands") { const files = requireDirectory(module, directory); for (const i in files ) { try { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this.commands.push(new (files[i].default as Command)()); } catch (e) { console.error(`Failed to construct command ${i} (${typeof e}):`); console.error(e); } } } onInteraction(interaction: Interaction) { if ( interaction.isChatInputCommand() || interaction.isMessageContextMenuCommand() || interaction.isUserContextMenuCommand() ) { const foundCommand = this.commands.find((command) => command.name === interaction.commandName ); if (!foundCommand) throw new Error(`Unknown command received (${interaction.commandName}). Did you forgot to push updated commands?`); foundCommand.execute(interaction).catch(e => { interaction.reply({ embeds: [{ color: 0xff0000, description: `Failed to perform interaction:\n\`\`${e}\`\``, }], ephemeral: true, }).catch(() => {/* NOTE: We're still logging the issue that happened to the console */}); console.error(`Failed to perform interaction: ${interaction.commandName}`); console.error(e); }); return; } if (interaction.isAutocomplete()) { const foundCommand = this.commands.find((command) => command.name === interaction.commandName ); if (!foundCommand) throw new Error(`Unknown command received (${interaction.commandName}). Did you forgot to push updated commands?`); if (!foundCommand.autocomplete) return; foundCommand.autocomplete(interaction).catch(e => { console.error(`Failed to perform autocomplete interaction: ${interaction.commandName}`); console.error(e); }); return; } } bindClient(client: DiscordClient) { client.on("interactionCreate", (e) => this.onInteraction(e)); } }