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函数,保留该判断会导致命令执行无返回。 - 确认主文件已完成命令集合初始化和注册
检查主文件前置代码是否包含以下逻辑,缺失的话补充即可:
- 引入依赖并初始化命令集合:
const { Client, Collection } = require('discord.js'); const client = new Client(); client.commands = new Collection();
- 读取命令文件并注册到集合(示例逻辑,对应命令存放在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
相关产品推荐
相关产品推荐

