【问题标题】:Update ALL bot commands without reloading it (without "node ." or nodemon)更新所有机器人命令而不重新加载它(没有“node.”或nodemon)
【发布时间】:2021-12-08 04:38:28
【问题描述】:

我想在不完全使用 nodemon 或 node . 重新启动机器人的情况下更新我的命令代码这是我尝试使用的代码:

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);
}
})

结果显示我的代码有效,但命令没有更新,我该如何解决? 以防万一:我的 djs 版本是 v13.2.0

【问题讨论】:

  • NodeJS 正在缓存来自require() 的脚本执行结果(也称为要求缓存)。您应该清除此缓存。也许这个答案会对你有所帮助:node.js require() cache - possible to invalidate?
  • 这对您的情况有用吗? stackoverflow.com/q/24666696/15325967
  • @insyri 他想重新加载命令而不重新加载应用程序。所以他应该在这种情况下清除缓存并再次使用require重新加载命令。
  • 啊,我明白了,我认为具体目标是远程更新命令。
  • @koloml 有帮助,但是有没有办法从client.commands 获取命令并一一更新,或者使用 fs 获取命令? (我不知道如何使用 fs 来做到这一点,因为我在 commands 文件夹中有类别文件夹)

标签: javascript node.js discord discord.js bots


【解决方案1】:

使用该函数删除模块/文件对应的缓存并获取更新版本:

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

现在,要获取文件,只需将 require 替换为 requireUncached

但是,您可能需要更新每个事件,以防止它被延迟更新

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)
    }
  }
})

可能有更有效的方法来做到这一点,确保您不必更新每个事件

【讨论】:

    猜你喜欢
    • 2014-02-14
    • 2019-09-13
    • 2018-05-26
    • 1970-01-01
    • 2022-06-28
    • 2019-04-11
    • 1970-01-01
    • 2021-08-10
    • 2015-12-22
    相关资源
    最近更新 更多