You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Discord机器人开发的ReferenceError: command is not defined错误

错误修复说明

直接报错原因

在命令加载的forEach循环中,引入的命令对象被赋值给了变量commands(复数形式),但后续打印日志、存入集合时调用的变量是command(单数形式),变量名不一致导致未定义报错。

其他需要修复的潜在问题

  • 代码同时引入了discord.js自带Client和自定义的./Structures/Client.js,二者逻辑无关联,如果你是基于自定义Client结构开发,原有实例化逻辑无效。
  • messageCreate事件中匹配到对应命令后,没有调用执行逻辑,匹配成功后不会有任何响应。
  • 新增了message.author.bot过滤逻辑,避免机器人自己发的消息触发命令导致死循环。
  • 如果你使用discord.js v14及以上版本,Intent枚举值需要从GatewayIntentBits导出,原有字符串写法会触发额外报错。

修复后完整代码

console.clear();
    
const Discord = require('discord.js');
// 如果要使用自定义Client,删掉上一行和下面的自带Client实例化,改用以下两行:
// const Client = require("./Structures/Client.js");
// const client = new Client({ intents: ['GUILDS', 'GUILD_MESSAGES']});
    
const client = new Discord.Client({ intents: ['GUILDS', 'GUILD_MESSAGES']});
const config = require("./Data/config.json");
client.commands = new Discord.Collection();
const fs = require("fs");

fs.readdirSync("./src/Commands")
  .filter((file) => file.endsWith(".js"))
  .forEach((file) => {
    /**
     * @type {Command}
     */
    // 统一变量名为单数command
    const command = require(`./Commands/${file}`);
    console.log(`Command ${command.name} loaded`);
    client.commands.set(command.name, command);
  });

client.on("ready", () => console.log("SpidBot is online!"));

client.on("messageCreate", (message) => {
  // 过滤无前缀消息、机器人自身消息
  if (!message.content.startsWith(config.prefix) || message.author.bot) return;

  const args = message.content.substring(config.prefix.length).split(/ +/);
  const commandName = args.shift().toLowerCase();
  const command = client.commands.get(commandName);
  // 匹配到命令后调用执行逻辑
  if (command) {
    command.run(client, message, args);
  }
});

client.login(config.token);

内容的提问来源于stack exchange,提问作者Spademin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:18:03