import Discord from 'discord.js'; import fs from 'fs'; import path from 'path'; import { pathToFileURL } from 'url'; import chalk from 'chalk'; const InteractionHandler = class { commands = {}; async init(token) { try { this.rest = new Discord.REST({ version: '10' }).setToken(token); const commandsPath = path.resolve('src/commands'); const folders = fs.readdirSync(commandsPath); for (const folder of folders) { const curPath = path.join(commandsPath, folder, 'index.js'); await import(pathToFileURL(curPath).toString()).then(res => { this.commands[res.default.data.name] = { cmd: res.default.data.toJSON(), execute: res.default.execute }; }); } return this; } catch(err) { throw err; } } async handle(interaction, api) { if (!interaction.isCommand()) return; if (interaction.commandName in this.commands) { await this.commands[interaction.commandName].execute(interaction, api); } } async registerCommandsDev(clientId, devGuildId) { this.rest.put(Discord.Routes.applicationGuildCommands(clientId, devGuildId), { body: Object.values(this.commands).map(cmdObj => cmdObj.cmd) }) .then(() => { console.log(`${chalk.green('Done:')} all commands are registered at the dev guild`); }) .catch((err) => { console.log(`${chalk.red('Error:')} ${err}`); }); } async unregisterCommandsDev(clientId, devGuildId) { this.rest.put(Discord.Routes.applicationGuildCommands(clientId, devGuildId), { body: [] }) .then(() => { console.log(`${chalk.green('Done:')} all commands are unregistered at the dev guild`); }) .catch((err) => { console.log(`${chalk.red('Error:')} ${err}`); }); } async unregisterCommandDev(clientId, devGuildId, commandId) { this.rest.delete(Discord.Routes.applicationGuildCommand(clientId, guildId, commandId)) .then(() => { console.log(`${chalk.green('Done:')} command '${commandId}' has been unregistered at the dev guild`); }) .catch((err) => { console.log(`${chalk.red('Error:')} ${err}`); }); } async registerCommands(clientId) { this.rest.put(Discord.Routes.applicationCommands(clientId), { body: Object.values(this.commands).map(cmdObj => cmdObj.cmd) }) .then(() => { console.log(`${chalk.green('Done:')} all commands are registered globally`); }) .catch((err) => { console.log(`${chalk.red('Error:')} ${err}`); }); } async unregisterCommands(clientId) { this.rest.put(Discord.Routes.applicationCommands(clientId), { body: [] }) .then(() => { console.log(`${chalk.green('Done:')} all commands are unregistered globally`); }) .catch((err) => { console.log(`${chalk.red('Error:')} ${err}`); }); } async unregisterCommand(clientId, commandId) { this.rest.delete(Discord.Routes.applicationCommand(clientId, commandId)) .then(() => { console.log(`${chalk.green('Done:')} command '${commandId}' has been unregistered globally`); }) .catch((err) => { console.log(`${chalk.red('Error:')} ${err}`); }); } }; export default InteractionHandler;