【问题标题】:Uncaught ReferenceError: command is not defined未捕获的 ReferenceError:未定义命令
【发布时间】:2022-01-08 03:12:14
【问题描述】:

我正在尝试在 discord 机器人(使用 discord.js)上执行命令处理程序,但是当我启动机器人时出现错误:

ReferenceError: 命令未定义

This is the error I get

const discord = require('discord.js');
const intents = new discord.Intents();
const client = new discord.Client({ intents: 32767 });

const fs = require('fs');
const { readdirSync } = require('fs');

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

let cmd = client.commands.find((c) => c.name === command || c.alias && c.alias.includes(command));
if(!cmd){
    cmd.execute(client, message, args);
} else {
    if(!cmd){
        return;
    }
}

const config = require('./config.js');
const prefix = config.prefix;

client.login(config.token);

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    这必须在messageCreate 事件中:

    client.on("messageCreate", message => {
      const [ command, ...args ] = message.content.split(/ +/g);
      let cmd = client.commands.get(command) || client.commands.find((c) => c.alias?.includes(command));
      if (cmd) { //you also made a mistake here, remove the "!"
        cmd.execute(client, message, args);
      }
    })
    

    【讨论】:

    • 我还要指出else 语句检查!cmd 的冗余
    • 解决了!谢谢,但我仍然有问题,你能帮我解决这些问题吗? cmd.execute(客户端,消息,参数); ^ TypeError:无法读取未定义的属性(读取“执行”)
    • 您是否删除了if (!cmd)!?此外,如果此答案有帮助,请考虑给它打勾和/或投票
    【解决方案2】:

    问题是您使用const 在循环内定义command。您需要用 var 替换它,它应该可以正常工作:

    const discord = require('discord.js');
    const intents = new discord.Intents();
    const client = new discord.Client({ intents: 32767 });
    
    const fs = require('fs');
    const { readdirSync } = require('fs');
    
    client.commands = new discord.Collection();
    const commandFiles = fs.readdirSync('./comandos').filter(file => file.endsWith('.js'));
    
    for(const file of commandFiles){
        var command = require(`./comandos/${file}`);
        client.commands.set(command.name, command);
    }
    
    let cmd = client.commands.find((c) => c.name === command || c.alias && c.alias.includes(command));
    if(!cmd){
        cmd.execute(client, message, args);
    } else {
        if(!cmd){
            return;
        }
    }
    
    const config = require('./config.js');
    const prefix = config.prefix;
    
    client.login(config.token);
    

    (使用“let”也不行,因为它不在全局范围内)。

    【讨论】:

    • 这不会修复代码 - 他们现在只会得到 message is not defined
    • @MrMythical 我想我没有注意到这个问题。希望 OP 能同时接受这两个答案并且它会起作用
    • 另外,现在使用var 被认为是不好的做法(或者我听说过),您现在应该使用letconst
    • @MrMythical 我从未听说过。但是var是全局作用域所以可以解决问题
    • command始终 是最后加载的命令,因为它位于 for 循环之后,这意味着您的答案将无法正常工作,而我的答案将
    猜你喜欢
    • 2023-01-23
    • 2016-11-03
    • 2011-01-05
    • 2016-01-02
    • 2013-10-06
    • 2016-12-17
    • 1970-01-01
    相关资源
    最近更新 更多