【发布时间】:2022-04-15 22:37:58
【问题描述】:
我创建了一个函数来发送带有按钮的嵌入消息,现在我想创建一个事件处理程序来检测按钮何时被单击并执行一个函数作为响应。
我想在同一个文件夹中创建按钮处理程序,然后是事件的处理程序文件夹。
【问题讨论】:
标签: javascript node.js button discord.js event-handling
我创建了一个函数来发送带有按钮的嵌入消息,现在我想创建一个事件处理程序来检测按钮何时被单击并执行一个函数作为响应。
我想在同一个文件夹中创建按钮处理程序,然后是事件的处理程序文件夹。
【问题讨论】:
标签: javascript node.js button discord.js event-handling
button 是交互。所以你可以在interactionCreate handler 中创建你的button handler。您可以像这样使用 if 语句检查交互类型;
client.on("interactionCreate", async (interaction) => {
if (interaction.isButton()) {
// ** Buttons handler
}
if (interaction.isCommand()) {
// ** Slash commands handler
}
});
【讨论】:
我终于编写了这段代码,并且成功了:
// Button Handler
client.buttons = new Collection();
const buttonFolders = fs.readdirSync('./buttons');
for (const folder of buttonFolders) {
const buttonFiles = fs.readdirSync(`./buttons/${folder}`).filter(file => file.endsWith('.js'));
for (const file of buttonFiles) {
const button = require(`./buttons/${folder}/${file}`);
client.buttons.set(button.data.name, button);
}
}
client.on('interactionCreate', async interaction => {
if(interaction.isButton()) {
const button = client.buttons.get(interaction.customId);
if(!button) return;
try {
await button.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing the button script !', ephemeral: true});
}
} else {
return;
}
})
【讨论】: