使用discord.js v14开发按钮遇Interaction已确认报错求示例代码
问题原因及解决方案
核心错误
- 重复注册事件监听器:你把
interactionCreate事件监听写在了messageCreate回调内部,每收到一条消息就会新增一个监听器。按钮点击时,多个监听器会同时响应,导致交互被多次确认,触发Interaction has already been acknowledged错误。 - 方法调用错误:
interaction.isButton是方法,需要加括号调用interaction.isButton()。
修正后的示例代码(使用组件收集器,无需全局事件处理器)
import { Client, GatewayIntentBits, Partials, ActionRowBuilder, ButtonBuilder, ButtonStyle } from "discord.js"; const client = new Client({ intents: [ GatewayIntentBits.DirectMessages, GatewayIntentBits.Guilds, GatewayIntentBits.GuildBans, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ], partials: [Partials.Channel] }); client.once('ready', () =>{ console.log(`${client.user.username} 已上线!`); client.user.setActivity(`>>rank`, { type: "WATCHING" }); }); client.on("messageCreate", async (message) => { if (message.content !== 'hi') return; const btn1 = new ButtonBuilder() .setCustomId('btn1') .setLabel('点击我!') .setStyle(ButtonStyle.Primary); const row = new ActionRowBuilder().addComponents(btn1); const sentMessage = await message.channel.send({ content: 'HI', components: [row] }); // 创建组件收集器,监听按钮点击 const collector = sentMessage.createMessageComponentCollector({ time: 60000, // 60秒后自动停止监听 filter: i => i.customId === 'btn1' && i.user.id === message.author.id // 只允许发送消息的用户点击 }); collector.on('collect', async (interaction) => { // 确认交互并回复 await interaction.reply({ content: 'Um Hello' }); }); collector.on('end', () => { // 收集器停止后禁用按钮,避免无效点击 btn1.setDisabled(true); sentMessage.edit({ components: [new ActionRowBuilder().addComponents(btn1)] }); }); }); client.login('你的TOKEN');
关键说明
- 用
createMessageComponentCollector创建专属收集器,替代全局interactionCreate事件,彻底避免重复监听问题。 - 收集器可设置监听时长、过滤条件,精准控制哪些交互会被处理。
- 按钮点击后直接用
interaction.reply回复,无需额外的deferUpdate(若需更新原消息内容可替换为interaction.update)。 - 收集器结束后禁用按钮,提升用户体验。
内容的提问来源于stack exchange,提问作者Gaming HMS
相关产品推荐
相关产品推荐

