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

为什么Discord.js模块化事件脚本中'interaction'参数为undefined?

问题原因

你参数的传递顺序不匹配:
Discord.js的interactionCreate事件触发时,回调函数默认只会接收interaction这一个参数。你拆分代码后在interactionCreate.js的execute方法里把client放在了第一个参数位,第二个才是interaction,但调用execute时你只传了事件本身的参数,所以第二个参数interaction自然就是undefined,调用isCommand方法就会报错。

修复方案

你可以任选以下一种方式修复:

方案1:修改事件调用逻辑,主动传入client

修改index.js中注册事件的代码,调用execute时把client作为第一个参数传入:

for (const file of eventFiles) {
    const event = require(`./events/${file}`);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(client, ...args));
    } else {
        client.on(event.name, (...args) => event.execute(client, ...args));
    }
}

改完后interactionCreate.js的代码不需要调整,参数顺序保持原样即可正常运行。

方案2:直接从interaction对象获取client

Discord.js的所有交互对象本身都挂载了client属性,你可以直接修改interactionCreate.js的execute参数,去掉多余的client参数,直接从interaction上取即可:

module.exports = {
    name: 'interactionCreate',
    async execute(interaction) {
        if (!interaction.isCommand()) return;

        const command = interaction.client.commands.get(interaction.commandName);

        if (!command) return;

        try {
            await command.execute(interaction);
        } catch (error) {
            console.error(error);
            await interaction.reply({ content: 'There was an error while executing this command.', ephemeral: true });
        }
    },
};

这个方案不需要修改index.js的代码,同样可以解决问题。

内容的提问来源于stack exchange,提问作者Michael O'Connell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:57:05