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

Discord.js v12报command.execute is not a function错误且冷却功能失效如何解决

问题根因与修复方案

核心错误点

  • 变量混淆:command是从消息中解析出来的字符串类型的命令名,你后续冷却判断、调用execute时错误使用了这个字符串,而非实际存储了命令配置的cmd对象
  • 命令执行逻辑顺序错误:你在冷却判断之前就已经执行了cmd.execute,冷却逻辑完全不生效,还重复执行了两次命令
  • 命令属性读取路径错误:你定义的命令配置都存在info字段下,直接读取cmd.name/cmd.cooldown会拿到undefined,必须从cmd.info中读取
  • 别名匹配逻辑错误:查找别名时使用了未赋值的cmd变量,导致别名功能完全失效

修复后代码

require('dotenv').config();
const Discord = require('discord.js');
const cooldowns = new Map();

module.exports = async (Discord, client, message) => {
    if (message.author.bot) return;
  
    const prefix = message.content.includes("nabe ") ? "nabe " : "n!"
  
    if (message.content.indexOf(prefix) !== 0) return;
  
    const args = message.content.slice(prefix.length).trim().split(/ +/g);
    const commandName = args.shift().toLowerCase(); // 重命名避免变量混淆
  
    // 修复别名匹配逻辑
    const cmd = client.commands.get(commandName) || client.commands.find(a => a.aliases && a.aliases.includes(commandName));
  
    if(message.channel.type === "dm")return message.channel.send("you can't use commands on dm")
  
    if(!cmd) return; // 没有匹配到命令直接返回

    // 冷却逻辑前置,先判断冷却再执行命令
    if(!cooldowns.has(cmd.info.name)){
        cooldowns.set(cmd.info.name, new Discord.Collection());
    }

    const current_time = Date.now();
    const time_stamps = cooldowns.get(cmd.info.name);
    const cooldown_amount = (cmd.info.cooldown || 3) * 1000; // 加默认冷却,避免无配置时报错

    if(time_stamps.has(message.author.id)){
        const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;

        if(current_time < expiration_time){
            const time_left = (expiration_time - current_time) / 1000;
            return message.reply(`wait **${time_left.toFixed(1)}** more seconds to do ${cmd.info.name} again.`).then(msg => { msg.delete({ timeout: 7000 }) });
        }
    }

    time_stamps.set(message.author.id, current_time);
    setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);
    
    // 只执行一次命令,参数顺序和命令定义保持一致
    try{
        cmd.execute(client, message, args, Discord);
    } catch (err){
        message.reply("There was an error trying to execute this command.");
        console.log(err);
    }
}

验证说明

修改后两个问题会同时解决:

  1. 调用execute的报错会消失,现在调用的是实际命令对象的execute方法,参数顺序也和你定义的命令格式匹配
  2. 冷却功能正常生效,现在会先判断用户是否在冷却期,冷却期内直接拦截返回提示,冷却期通过才会执行命令逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:06:09