Home > Software design >  Update ALL bot commands without reloading it (without "node ." or nodemon)
Update ALL bot commands without reloading it (without "node ." or nodemon)

Time:10-22

I want to update my commands code without restarting bot fully using nodemon or just node . I wanted to make a command I can send to update all commands in my bot (basically commands collection where they are and their code stored). Here is the code I tried to use:

const { glob } = require('glob')
const { promisify } = require('util')
const globPromise = promisify(glob);

await client.commands.clear()

const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
commandFiles.map((value) => {
const file = require(value);
const splitted = value.split("/");
const directory = splitted[splitted.length - 2];
    
if (file.name) {
const properties = { directory, ...file };
client.commands.set(file.name, properties);
}
})

Result says my code worked but commands are not updating, how can I fix it? Just in case: my djs version is v13.2.0

CodePudding user response:

Using this function deletes the cache corresponding to the module/file and gets the updated version:

function requireUncached(module) {
    delete require.cache[require.resolve(module)];
    return require(module);
}

Now, to require the files, just replace require with requireUncached.

You might however need to update on each event, to prevent it being updated late

client.on("messageCreate", msg => {
  client.commands.clear();
  const files = fs.readdirSync("./commands") //read commands folder
  const folders = files.filter(f => !f.includes(".")) //get category folders
  for (const folder of folders) {
    const cmdFiles = fs.readdirSync(`./commands/${folder}`).filter(f => f.endsWith(".js")) //get cmd files in each folder
    for (const file of cmdFiles) {
      const f = requireUncached(`./commands/${folder}/${file}`) //require the file "uncached"
      client.commands.set(f.name, f)
    }
  }
})

There might be more efficient ways to do this, making sure that you don't have to update on each event

  • Related