import { DebugBuilder } from "../../modules/debugger.mjs"; const log = new DebugBuilder("server", "discordBot.modules.registerCommands"); import { REST, Routes } from "discord.js"; import dotenv from "dotenv"; dotenv.config(); const discordToken = process.env.DISCORD_TOKEN; export const registerActiveCommands = async (serverClient) => { const guildIDs = serverClient.guilds.cache; const clientId = serverClient.user.id; const commands = await serverClient.commands.map( (command) => (command = command.data.toJSON()), ); // Construct and prepare an instance of the REST module const rest = new REST({ version: "10" }).setToken(discordToken); // and deploy your commands! guildIDs.forEach((guild) => { log.INFO("Deploying commands for: ", guild.id); log.DEBUG("Commands", commands); (async () => { try { log.DEBUG( `Started refreshing application (/) commands for guild ID: ${guild.id}.`, ); // The put method is used to fully refresh all commands in the guild with the current set const data = await rest.put( Routes.applicationGuildCommands(clientId, guild.id), { body: commands }, ); log.DEBUG( `Successfully reloaded ${data.length} application (/) commands for guild ID: ${guild.id}.`, ); } catch (error) { // And of course, make sure you catch and log any errors! log.ERROR( "ERROR Deploying commands: ", error, "Body from error: ", commands, ); } })(); }); }; /** * Remove all commands for a given bot in a given guild * * @param {any} serverClient The discord bot client */ export const unregisterAllCommands = async (serverClient) => { const guildIDs = serverClient.guilds.cache; const clientId = serverClient.user.id; commands = []; const rest = new REST({ version: "10" }).setToken(discordToken); guildIDs.forEach((guild) => { log.INFO("Removing commands for: ", clientId, guild.id); (async () => { try { log.DEBUG( `Started removal of ${commands.length} application (/) commands for guild ID: ${guild.id}.`, ); // The put method is used to fully refresh all commands in the guild with the current set const data = await rest.put( Routes.applicationGuildCommands(clientId, guild.id), { body: commands }, ); log.DEBUG( `Successfully removed ${data.length} application (/) commands for guild ID: ${guild.id}.`, ); } catch (error) { // And of course, make sure you catch and log any errors! log.ERROR( "ERROR removing commands: ", error, "Body from error: ", commands, ); } })(); }); }; /** * This named wrapper will remove all commands and then re-add the commands back, effectively refreshing them * @param {any} serverClient The discord bot client object * @returns {any} */ export const refreshActiveCommandsWrapper = async (serverClient) => { // Remove all commands log.INFO( "Removing/Unregistering all commands from all connected servers/guilds", ); await unregisterAllCommands(serverClient); // Deploy the active commands log.INFO("Adding commands to all connected servers/guilds"); await registerActiveCommands(serverClient); return; };