Discord.js 14.4.0 TypeError求助:无法读取undefined的'hello'属性
排查discord.js 14.4.0中/hello命令的TypeError问题
报错TypeError: Cannot read properties of undefined (reading 'hello')的核心是:你代码中某个被期望包含hello属性的对象实际为undefined,以下是针对核心文件的排查方向:
1. 检查命令集合的初始化与命令加载逻辑
确保index.js中正确初始化命令集合,并成功加载hello命令:
- 确认
client.commands是discord.js的Collection实例:// index.js 顶部代码 const { Client, Collection, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // 必须初始化commands集合 client.commands = new Collection(); - 检查命令加载逻辑,确保
hello命令被正确添加到集合:
若加载逻辑错误,// 示例命令加载逻辑(根据你的实际代码调整) const fs = require('fs'); const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); for (const file of commandFiles) { const command = require(`./commands/${file}`); // 验证命令文件结构后添加到集合 if ('data' in command && 'execute' in command) { client.commands.set(command.data.name, command); } else { console.log(`[警告] ${file} 缺少必要的data或execute属性`); } }client.commands中将不存在hello命令,后续访问会触发对象未定义的报错。
2. 检查interactionCreate事件中的命令获取逻辑
报错大概率是因为直接访问commands.hello而非通过集合方法正确获取命令,正确写法如下:
- 错误示例(会触发报错):
// interactionCreate事件中错误写法 client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand()) return; // 若commands为undefined,访问commands.hello会报错 const command = commands.hello; // ... }); - 正确写法:
client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand()) return; const command = client.commands.get(interaction.commandName); if (!command) return; // 确保命令存在 try { await command.execute(interaction); } catch (error) { console.error(error); await interaction.reply({ content: '执行命令时出错!', ephemeral: true }); } });
3. 检查hello命令文件的导出结构
确保hello命令文件正确导出符合discord.js v14要求的对象:
// commands/hello.js 示例代码 const { SlashCommandBuilder } = require('@discordjs/builders'); module.exports = { data: new SlashCommandBuilder() .setName('hello') // 名称必须与Discord中注册的命令一致 .setDescription('发送问候消息'), async execute(interaction) { await interaction.reply('Hello!'); }, };
若导出对象缺少data/execute属性,或data.name不是hello,会导致集合无法正确存储或找到该命令。
4. 检查SlashCommand部署脚本的正确性
确保部署脚本将hello命令正确注册到Discord API,且名称与代码一致:
// deploy-commands.js 示例代码 const { REST, Routes } = require('discord.js'); const { clientId, guildId, token } = require('./config.json'); const fs = require('fs'); const commands = []; const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); for (const file of commandFiles) { const command = require(`./commands/${file}`); commands.push(command.data.toJSON()); } const rest = new REST({ version: '10' }).setToken(token); (async () => { try { console.log(`正在重新加载 ${commands.length} 个应用命令`); const data = await rest.put( Routes.applicationGuildCommands(clientId, guildId), { body: commands }, ); console.log(`成功重新加载 ${data.length} 个应用命令`); } catch (error) { console.error(error); } })();
部署后需确认Discord服务器中存在/hello命令,且名称无误。
内容的提问来源于stack exchange,提问作者user20006553
相关产品推荐
相关产品推荐

