Discord.js v14 TypeError求助:无法读取undefined的get属性
解决Discord.js中InteractionCreate事件的TypeError问题
问题原因
你遇到的TypeError: Cannot read properties of undefined (reading 'get')是因为Discord.js的interaction对象并没有commands属性。当前代码仅将命令的JSON数据存入数组用于注册,但未在客户端实例上保存包含执行逻辑的完整命令对象,导致无法通过interaction.commands获取命令。
修复步骤
- 给客户端实例添加
commands集合,用于存储包含execute方法的完整命令对象 - 调整命令读取逻辑,同时保存命令对象和收集注册用的JSON数据
- 在
InteractionCreate事件中从客户端的commands集合获取命令
修改后的代码
index.js
const { token, clientId, guildId, ownerId } = require("./Config.json"); // 引入Collection用于存储命令 const { Client, Events, GatewayIntentBits, REST, Routes, Collection } = require("discord.js"); const fs = require("fs"); const path = require("path"); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, ] }); // 初始化客户端的commands集合 client.commands = new Collection(); const commandDataArray = []; // 用于注册命令的JSON数据数组 const commandsPath = path.join(__dirname, "Utils"); const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith(".js")); for (const file of commandFiles) { const command = require(`./Utils/${file}`); // 将完整命令对象存入client.commands,以命令名为键 client.commands.set(command.data.name, command); // 收集命令的JSON数据用于注册 commandDataArray.push(command.data.toJSON()); } const rest = new REST().setToken(token); async function Main() { try { console.log(`Started refreshing ${commandDataArray.length} Slash commands.`); const data = await rest.put( Routes.applicationCommands(clientId, guildId), { body: commandDataArray } ); console.log(`Successfully reloaded ${data.length} Slash commands.`); client.login(token); } catch (err) { console.log(err.message); } } client.once(Events.ClientReady, (client) => { console.log(`Ready! Logged in as ${client.user.tag}`); }); client.on(Events.InteractionCreate, async (interaction) => { if (!interaction.isChatInputCommand()) { return; } // 从client.commands中获取命令,而非interaction.commands const command = client.commands.get(interaction.commandName); if (!command) { return console.log(`No command matching ${interaction.commandName} was found.`); } try { await command.execute(interaction); } catch (err) { console.log(err.message); } }); Main();
Utils/hi.js(无需修改)
const { SlashCommandBuilder } = require("discord.js"); module.exports = { data: new SlashCommandBuilder() .setName("hi") .setDescription("replies with Hello"), async execute(interaction) { await interaction.reply({ content: "Hello" }); } }
内容的提问来源于stack exchange,提问作者Charlzk
相关产品推荐
相关产品推荐

