Discord.js v13无需重启更新bot指令 现有热更代码不生效如何修复
问题根因
Node.js 默认会对所有已require的模块做缓存,你首次启动机器人时已经加载过所有指令文件,后续执行更新逻辑时再次调用require(value)拿到的是缓存里的旧代码,并不是你修改后的新内容,所以虽然client.commands集合重新写入成功,但实际运行的还是旧逻辑。
修复方案
核心是在重新加载指令前,先清除对应文件的模块缓存,修改后的代码如下:
const { glob } = require('glob') const { promisify } = require('util') const path = require('path') // 新增,处理多系统路径兼容性 const globPromise = promisify(glob); await client.commands.clear() const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`); commandFiles.map((value) => { // 新增:清除对应文件的模块缓存 const filePath = path.resolve(value); delete require.cache[filePath]; const file = require(value); const splitted = value.split(path.sep); // 改用path.sep兼容Windows系统反斜杠路径格式 const directory = splitted[splitted.length - 2]; if (file.name) { const properties = { directory, ...file }; client.commands.set(file.name, properties); } }) // 如果你使用的是斜杠(/)指令,还需要追加注册逻辑同步到Discord API // 单服务器测试指令(即时生效)示例: // await client.guilds.cache.get('你的服务器ID')?.commands.set(client.commands.map(cmd => cmd.data.toJSON())); // 全局指令示例(最长需要1小时缓存期才会生效): // await client.application?.commands.set(client.commands.map(cmd => cmd.data.toJSON()));
注意事项
- 如果你的指令文件依赖了其他自定义公共模块,公共模块修改后也需要同步清除对应模块的缓存才能生效
- Djs v13 的斜杠指令注册逻辑需要在机器人触发
ready事件后执行,否则client.application会为undefined导致报错
内容的提问来源于stack exchange,提问作者MegaMix_Craft
相关产品推荐
相关产品推荐

