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

discord.js机器人client.commands.get读取execute未定义错误如何解决

问题修复方案

报错本质是client.commands.get('ping')返回了undefined,调用undefined.execute()触发了类型错误,按以下步骤逐一修复即可:

  • 修正ping.js的模块导出语法
    Node.js 规范下模块导出的正确写法为module.exports,你当前代码少写了末尾的s,会导致引入命令文件时无法获取正确的配置对象,将ping.js修改为:
module.exports = {
    name: 'ping',
    description: "This is a ping command!",
    execute(message, args){
        message.channel.send('pong!')
    }
}
  • 移除ping.js中多余的判断逻辑
    你已经在主文件中匹配到ping命令才会调用对应execute方法,不需要在命令执行逻辑中重复判断command === 'ping',同时你也没有将command变量传入execute函数,保留该判断会导致命令执行无返回。
  • 确认主文件已完成命令集合初始化和注册
    检查主文件前置代码是否包含以下逻辑,缺失的话补充即可:
  1. 引入依赖并初始化命令集合:
const { Client, Collection } = require('discord.js');
const client = new Client();
client.commands = new Collection();
  1. 读取命令文件并注册到集合(示例逻辑,对应命令存放在commands文件夹的场景):
const fs = require('fs');
// 读取commands文件夹下所有js后缀的命令文件
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    // 将命令注册到commands集合,key为命令名,value为命令配置对象
    client.commands.set(command.name, command);
}

额外提示:discord.js v13及以上版本已废弃message事件,若后续出现命令不触发的情况,可将主文件的client.on('message', message =>{修改为client.on('messageCreate', message =>{。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:18:03