discord.js 前缀在没有命令的情况下抛出错误

时间:2021-06-27 17:52:28

标签: discord.js

所以我的机器人前缀是 .,每当用户发送 . 时,机器人都会回复 there was an error trying to execute that command!,这很烦人。我不知道如何让它不响应带有错误的 .

这一行应该阻止这种情况发生,但它不是 const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)); if (!command) return;

client.on("message", message => {
    const prefixes = ['.'];
    const prefix = prefixes.find(p => message.content.startsWith(p));
    if (!prefix) return;
 
    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 && cmd.aliases.includes(commandName));
    
    if (!command) return;

    if (command.guildOnly && message.channel.type === 'dm') {
        return message.reply('I can\'t execute that command inside DMs!');
    }

    if (command.permissions) {
        const authorPerms = message.channel.permissionsFor(message.author);
        if (!authorPerms || !authorPerms.has(command.permissions)) {
            return message.reply('You can not do this!');
        }
    }

    if (command.args && !args.length) {
        let reply = `You didn't provide any arguments, ${message.author}!`;

        if (command.usage) {
            reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
        }

        return message.channel.send(reply);
    }

    const { cooldowns } = client;

    if (!cooldowns.has(command.name)) {
        cooldowns.set(command.name, new Discord.Collection());
    }
    
    const now = Date.now();
    const timestamps = cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 0) * 1000;
    
    if (timestamps.has(message.guild.id)) {
        const expirationTime = timestamps.get(message.guild.id) + cooldownAmount;
    
        if (now < expirationTime) {
            const timeLeft = (expirationTime - now) / 1000;
            return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
        }
    }

    timestamps.set(message.guild.id, now);
    setTimeout(() => timestamps.delete(message.guild.id), cooldownAmount);

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

1 个答案:

答案 0 :(得分:0)

您应该尝试检查,如果消息比前缀本身长,请尝试将 const prefix 更改为:

const prefix = prefixes.find(p => message.content.startsWith(p) && message.content.length>p.length);
相关问题