【问题标题】:why are aliases not getting executed?为什么别名没有被执行?
【发布时间】:2021-09-30 06:48:32
【问题描述】:

您好,我在 discord.js 中遇到了别名问题,别名不起作用,我不知道为什么?

client.on('message', message =>{
    // Exit when the message from the bot
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const commandName = args.shift().toLowerCase();

    if (!client.commands.has(commandName)) return;

    const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

    try {
        command.execute(message, args, commandName, client, Discord);
    } catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
    }
});

【问题讨论】:

  • 如何分配别名?我个人的做法与 discord.js 的“推荐”方式不同

标签: javascript discord.js


【解决方案1】:

你不能使用别名,因为你放了

if(!client.commands.has(commandName)) return;

如果您尝试使用别名或其他任何不在您的 client.commands 键中的东西,这将返回 false。删除此行并改用此行:

const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases?.includes(commandName));
if(!command) return;
//...

这会查找命令首先,然后如果没有找到命令、名称或别名,则返回

【讨论】:

    【解决方案2】:

    您检查输入的命令是否存在,如下所示:

    if (!client.commands.has(commandName)) return;

    所以如果输入的命令是别名,它会返回。你会想做这样的事情:

    client.on('message', message => { // Setup the event listener
        // Exit when the message from the bot or is not a command
        if (!message.content.startsWith(prefix) || message.author.bot) return;
    
        const args = message.content.slice(prefix.length).trim().split(/ +/); // Define args
        const commandName = args.shift().toLowerCase(); // Get the command name
    
        let command = client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)); // Try to find the command by alias
    
        if (!command && !client.commands.has(commandName)) return; // The command doesn't exist
    
        command = client.commands.get(commandName); // If the command is not an alias, find it by name
    
        try {
            command.execute(message, args, commandName, client, Discord); // Attempt to execute the command
        } catch (error) {
            console.error(error);
            message.reply('there was an error trying to execute that command!');
        }
    });
    

    首先检查是否有任何别名与输入的命令匹配。如果没有,它将返回未定义。然后我们有一个 if 语句来检查是否没有找到别名或命令,如果找到则返回。否则使用正常的命令名来查找命令。

    【讨论】:

      【解决方案3】:

      if (!client.commands.has(commandName)) return; 此行应在const command = ... 之后 因为client.commands 是一个包含命令的集合,所有的键都是命令的名称而不是别名。

      【讨论】:

        猜你喜欢
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 2016-05-16
        • 1970-01-01
        相关资源
        最近更新 更多