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

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获取命令。

修复步骤

  1. 给客户端实例添加commands集合,用于存储包含execute方法的完整命令对象
  2. 调整命令读取逻辑,同时保存命令对象和收集注册用的JSON数据
  3. 在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 02:37:42