Discord.js执行命令时报TypeError: Cannot read properties of undefined (reading 'get')
Discord.js 命令处理报错
TypeError: Cannot read properties of undefined (reading 'get') 解决方法 错误根源
报错行const command = interaction.client.commands.get(interaction.commandName)里,interaction.client.commands是undefined,说明机器人客户端实例(client)未初始化commands集合,或命令加载逻辑未将命令正确存入该集合。
分步排查修复
1. 正确初始化commands集合
创建Client实例时,必须显式给client添加commands属性并赋值为Discord.js的Collection类型:
const { Client, Collection, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // 核心:初始化命令集合 client.commands = new Collection();
2. 检查命令加载逻辑
确保加载命令的代码将每个命令文件的内容存入client.commands,且命令文件包含data(命令结构定义)和execute(执行逻辑)两个必填属性:
const fs = require('node:fs'); const path = require('node:path'); // 命令文件夹路径(根据你的项目结构调整) const commandsPath = path.join(__dirname, 'commands'); // 筛选出所有.js命令文件 const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); // 校验命令文件完整性 if ('data' in command && 'execute' in command) { // 以命令名称为键存入集合 client.commands.set(command.data.name, command); } else { console.log(`[警告] 命令文件 ${filePath} 缺少data或execute属性,已跳过`); } }
3. 调整代码执行顺序
必须先初始化commands集合、加载完所有命令,再调用client.login(token)登录机器人。若登录逻辑在命令加载前执行,机器人上线时commands集合为空,自然无法获取命令。
4. 过滤非命令交互
在interactionCreate事件中,先判断交互是否为聊天输入命令,避免处理按钮、选择菜单等其他类型交互时出错:
client.on('interactionCreate', async interaction => { // 仅处理命令交互 if (!interaction.isChatInputCommand()) return; const command = interaction.client.commands.get(interaction.commandName); if (!command) { console.error(`找不到名为 ${interaction.commandName} 的命令,请检查名称是否匹配`); await interaction.reply({ content: '该命令不存在!', ephemeral: true }); return; } try { await command.execute(interaction); } catch (error) { console.error(error); await interaction.reply({ content: '执行命令时发生错误!', ephemeral: true }); } });
5. 校验命令名称一致性
确保:
- 本地命令文件中
command.data.name的名称,与注册到Discord API的命令名称完全一致(大小写敏感) - 命令文件名不影响调用,关键是
data.name的值
内容的提问来源于stack exchange,提问作者And then I said Meow
相关产品推荐
相关产品推荐

