使用discord.js开发Discord机器人命令处理器时出现command未定义报错
问题根因
- 触发
ReferenceError: command is not defined的直接原因是:client.commands.find方法中使用的command变量仅在之前加载命令的for循环内部作为局部变量声明,循环结束后该变量作用域销毁,全局作用域不存在该变量,因此启动时直接报错。 - 代码还存在其他逻辑问题:
- 命令匹配、执行逻辑直接写在全局作用域,机器人启动时就会执行,此时既没有收到消息事件,也没有定义
message、args变量,修复command问题后还会触发新的未定义错误。 - 命令执行逻辑写反:当前代码判断
!cmd(未匹配到命令)时调用cmd.execute,此时cmd为null会直接抛错。 - 缺少消息事件监听,无法响应Discord频道内的用户命令。
- 命令匹配、执行逻辑直接写在全局作用域,机器人启动时就会执行,此时既没有收到消息事件,也没有定义
修复方案
将命令处理逻辑放入messageCreate事件监听器中,完整修复后代码如下:
const discord = require('discord.js'); const client = new discord.Client({ intents: 32767 }); const fs = require('fs'); const config = require('./config.js'); const prefix = config.prefix; client.commands = new discord.Collection(); const commandFiles = fs.readdirSync('./comandos').filter(file => file.endsWith('.js')); for(const file of commandFiles){ const command = require(`./comandos/${file}`); client.commands.set(command.name, command); } // 监听消息事件处理命令 client.on('messageCreate', message => { // 忽略机器人消息、无前缀的消息 if(!message.content.startsWith(prefix) || message.author.bot) return; // 拆分命令和参数 const args = message.content.slice(prefix.length).trim().split(/ +/); const command = args.shift().toLowerCase(); // 匹配命令 let cmd = client.commands.find((c) => c.name === command || c.alias?.includes(command)); if(cmd){ cmd.execute(client, message, args); } }) client.login(config.token);
补充说明
- 代码中使用可选链操作符
?.处理部分命令没有alias属性的情况,避免触发undefined读取错误。 - 新增了过滤机器人消息、判断前缀的逻辑,避免命令误触发。
- 调整了命令判断逻辑,只有匹配到对应命令时才执行
execute方法。
内容的提问来源于stack exchange,提问作者MillionDreamer
相关产品推荐
相关产品推荐

