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

如何实现Discord机器人中可关闭临时消息的交互按钮?

实现Discord临时确认消息的取消关闭功能

需求:创建一条仅触发用户可见的临时(ephemeral)确认消息,点击「取消」按钮时关闭该消息。

完整实现代码

// 确保导入Discord.js所需模块(根据你的版本调整)
const { ButtonBuilder, ButtonStyle, ActionRowBuilder, EmbedBuilder } = require('discord.js');

// 发送临时确认消息的核心逻辑
await interaction.deferReply({ ephemeral: true });

const cancelButton = new ButtonBuilder()
  .setStyle(ButtonStyle.Danger)
  .setEmoji("✖️")
  .setCustomId("cancelclose");

const confirmButton = new ButtonBuilder()
  .setStyle(ButtonStyle.Primary)
  .setEmoji("✔️")
  .setCustomId("close");

const row = new ActionRowBuilder().addComponents(cancelButton, confirmButton);

const embed = new EmbedBuilder()
  .setTitle(`确定要执行此操作吗?`)
  .setColor('#653386')
  .setFooter({ text: `${config.sendPanel.footerText}`, iconURL: `${guild.iconURL()}` });

await interaction.editReply({ embeds: [embed], components: [row], ephemeral: true });

// 监听按钮点击事件
const collector = interaction.channel.createMessageComponentCollector({ time: 60000 });

collector.on('collect', async i => {
  if (i.customId === 'cancelclose') {
    // 点击取消按钮,直接删除临时消息
    await interaction.deleteReply();
    collector.stop();
  } else if (i.customId === 'close') {
    // 这里添加确认后的业务逻辑
    await i.reply({ content: "操作已确认执行", ephemeral: true });
    collector.stop();
  }
});

collector.on('end', () => {
  // 超时后禁用按钮,避免无效点击
  row.components.forEach(btn => btn.setDisabled(true));
  interaction.editReply({ components: [row] }).catch(() => {});
});

关键说明

  • 临时消息配置:通过ephemeral: true参数确保消息仅触发交互的用户可见
  • 取消按钮逻辑:监听cancelclose自定义ID的按钮点击,调用interaction.deleteReply()直接删除临时消息
  • 超时处理:设置60秒的交互收集器超时,超时后自动禁用按钮,避免用户后续点击无响应
  • 注意事项:确保机器人已正确注册组件交互监听逻辑,或使用上述收集器方式处理按钮点击

内容的提问来源于stack exchange,提问作者Ahmed Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:52:49