javascript - 为什么此文件注册脚本中未定义“交互”参数?
问题描述
我正在(半成功地)学习如何在 Discord.js 中使用新的斜杠命令,这是一个用于与 Discord 的机器人 API 交互的 node.js 模块。据我所知,这完全是基本 Javascript 代码的问题,不需要 Discord.js 知识来解决我相当烦人的小问题!
该代码用于检索事件文件并执行它们。问题是每当interactionCreate.js
执行文件时,interaction
参数似乎是未定义的。
如果需要,文件结构如下:
project-folder/
├── index.js
├── events/
└── interactionCreate.js
这是index.js
:
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
...这是interactionCreate.js
:
module.exports = {
name: 'interactionCreate',
async execute(client, interaction) {
if (!interaction.isCommand()) 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: 'There was an error while executing this command.', ephemeral: true });
}
},
};
我不完全确定这是否相关,但这是代码不在单独模块中时的样子。当然,这里不需要事件文件检索。
index.js (before modularisation)
:
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) 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: 'There was an error while executing this command.', ephemeral: true });
}
});
同样,我不确定是否需要这样做,但这是我收到的错误消息之一。
C:\path\to\files\project-folder\events\interactionCreate.js:4
if (!interaction.isCommand()) return;
^
TypeError: Cannot read properties of undefined (reading 'isCommand')
我在这里提问的经验不是很丰富,所以如果您还有其他需要,请告诉我!我很乐意回复您的回复或更新问题。非常感谢!
解决方案
你的声明是这样的:
async execute(client, interaction) {
//...
}
并且该interactionCreate
事件仅提供1个参数(interaction
)。如果您的所有事件都按client, rest, of, the, args
参数顺序排列,则方法如下:
if (event.once) {
client.once(event.name, (...args) => event.execute(client, ...args));
} else {
client.on(event.name, (...args) => event.execute(client, ...args));
}
推荐阅读
- postgresql - Docker 没有获取 Postgres 环境变量
- javascript - 创建元素,然后删除元素
- coldfusion - Coldfusion 11 更新 16 - 计划任务已消失
- function - 实时更新batchsize
- java - SQLite 数据库表未连接
- regex - NGINX 仅为特定目录和索引文件指定变量
- typescript - 打字稿数组发现可能未定义
- node.js - Electronjs 和 Nodejs(Crypto) crypto.scryptSync 不是函数
- python - HTML中的变量被擦除了吗?
- java - Java:正则表达式查找子字符串集合