为什么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
相关产品推荐
相关产品推荐

