Sunday, November 14, 2021

[SOLVED] I made a reload command for a Discord bot and I want to be able to reload commands that are a new command instead of pre existing commands

Issue

So I made a reload command that reloads pre existing commands without pulling the bot offline. But now I want to be able to do an update with new commands I have added. Here is my code I have now

module.exports = {
    name: 'reload',
    aliasses: ['restart', 'rl'],
    cooldown: 0,
    usage: `reload <category> <command>`,
    description: 'Reloads a command',
    async execute(client, message, args, Discord, user, text){
        if(message.author.id !== `DevID`) return message.channel.send('You are not a Dev');     
        if(!args[0]) return message.channel.send('You need to include the name of the command!');

        let command = args[0].toLowerCase();
        try {
            delete require.cache[require.resolve(`../commands/${command}.js`)]
            client.commands.delete(command);
            const pull = require(`../commands/${command}.js`);
            client.commands.set(command, pull);

            return message.channel.send(`**${command}** was reloaded succesfully!`);
        } catch (error) {
            return message.channel.send(`There was an error trying to reload **${command}**: \`${error.message}\``);
        }
    }
} 

In the end i want to reload pre existing commands and load new commands without taking the bot offline.


Solution

Maybe this would work:

const Discord = require('discord.js');
const client = new Discord.Client();
var commands;
function requireUncached(module) {
delete require.cache[require.resolve(module)];
return require(module);
}

setInterval(() => {
commands = requireUncached(`whatever your file name is`);
}, 500)

So I’ve never tried module.exports but I know you can access the commands with the variable “commands” in this code, if you put in the correct file for requireUncached()



Answered By - MrMythical