Search code examples
discord.jshandler

Discord.js bot Outdated commands list


Even after calling handleCommands (which reloads commands) there remain phantom commands on discord commands poll. What am i doing wrong? is there something specific i need to do to reset the commands?

These are some files for reference:

handleCommands

const { Collection } = require('discord.js')
const { loadFiles }  = require('../functions/fileLoader');
const { REST }       = require('@discordjs/rest');
const { Routes }     = require('discord-api-types/v9')

module.exports = (client) => {
    client.handleCommands = async() => {

        const commandFiles = await loadFiles('commands');

        const {commands, commandsArray} = client;
        const commandsTable = []

        await commandFiles.forEach(async file => {
            try {
                const command = await require(file);
                commands.set(command.data.name, command);
                commandsArray.push(command.data.toJSON());

                commandsTable.push({ 'Command': command.data.name, 'Status': '✅'});
            } catch (e) {
                commandsTable.push({ 'Command': file.split('/').pop().slice(0,-3), 'Status': '❗️'});
                console.error(e);
            }
        })

        const rest = new REST({version:9}).setToken(process.env.BOT_TOKEN);
        try{
            await rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID), {
                body: client.commandsArray
            });
            // await client.application.commands.set(commandsArray);
        } catch(e) {
            console.error(new Error('Failed to load guildCommands', {cause:e}));
        }
        // }

        console.table(commandsTable);
    };
};

fileLoader

const { glob } = require('glob');
const path     = require('node:path');

async function deleteCachedFile(file) {
    const filePath = path.resolve(file);
    if(require.cache[filePath]) delete require.cache[filePath];
}

async function loadFiles(dirName) {
    try{
        const files = await glob(path.join(process.cwd(), 'src', dirName, '**/*.js').replace(/\\/g, '/'));
        const jsFiles = files.filter(file => path.extname(file) === '.js');
        await Promise.all(jsFiles.map(deleteCachedFile));
        return jsFiles;
    } catch (error) {
        throw new Error(`Failed to load files from dir ${dirName}: ${error}`, {cause: error})
    }
}

module.exports = { loadFiles };

Solution

  • The fix is in handleCommands.

    Apparently i have to empty the bot guildcommands before adding the new commands, the fixed file follows:

    const { loadFiles }  = require('../functions/fileLoader');
    const { REST }       = require('@discordjs/rest');
    const { Routes }     = require('discord-api-types/v9')
    
    module.exports = (client) => {
        client.handleCommands = async() => {
    
            const commandFiles = await loadFiles('commands');
    
            const {commands, commandsArray} = client;
            const commandsTable = [];
    
            commandFiles.forEach(async (file) => {
                try {
                    const command = await require(file);
    
                    commands.set(command.data.name, command);
                    commandsArray.push(command.data.toJSON());
    
                    commandsTable.push({ 'Command': command.data.name, 'Status': '✅' });
                } catch (e) {
                    commandsTable.push({ 'Command': file.split('/').pop().slice(0, -3), 'Status': '❗️' });
                    console.error(e);
                }
            })
            try{
                const rest = new REST({version:'10'}).setToken(process.env.BOT_TOKEN);
                await rest.put(
                    Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID), 
                    { body: [] }
                );
                await rest.put(
                    Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID), 
                    { body: client.commandsArray }
                );
                // await client.application.commands.set(commandsArray);
            } catch(e) {
                console.error(new Error('Failed to load guildCommands', {cause:e}));
            }
    
            console.table(commandsTable);
        };
    };