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

Discord.js v14:公告命令点击按钮后等待频道提及输入的实现

Discord.js v14 实现点击按钮后选择公告发送频道的功能

核心逻辑

点击「发送」按钮后,机器人向发起操作的用户发送频道选择提示,通过消息收集器监听用户的回复内容,提取有效频道对象后,将之前生成的公告嵌入发送到目标频道。

具体实现代码

  1. 按钮交互处理
    在你的机器人交互监听逻辑中,添加按钮点击的处理代码:
client.on('interactionCreate', async interaction => {
  if (!interaction.isButton()) return;

  // 匹配你的「发送」按钮自定义ID
  if (interaction.customId === 'submit_announcement') {
    // 发送仅用户可见的频道选择提示
    await interaction.reply({
      content: '请发送要发布公告的频道(直接@频道即可)',
      ephemeral: true
    });

    // 创建消息收集器,仅监听发起操作的用户的消息
    const filter = msg => msg.author.id === interaction.user.id;
    const collector = interaction.channel.createMessageCollector({
      filter,
      max: 1, // 只收集一条回复
      time: 60000 // 超时时间60秒
    });

    // 收集到有效回复后的处理流程
    collector.on('collect', async msg => {
      // 提取消息中提及的第一个频道
      const targetChannel = msg.mentions.channels.first();

      if (!targetChannel) {
        await interaction.followUp({
          content: '未识别到有效频道,请重新@目标频道!',
          ephemeral: true
        });
        return;
      }

      // 验证机器人是否有权限在目标频道发送消息
      if (!targetChannel.permissionsFor(client.user).has('SendMessages')) {
        await interaction.followUp({
          content: `我没有权限在${targetChannel}发送消息,请检查频道权限设置!`,
          ephemeral: true
        });
        return;
      }

      // 获取之前发送的公告预览嵌入
      const announcementEmbed = interaction.message.embeds[0];

      // 发送公告到目标频道
      await targetChannel.send({ embeds: [announcementEmbed] });

      // 告知用户操作成功
      await interaction.followUp({
        content: `公告已成功发布到${targetChannel}!`,
        ephemeral: true
      });

      // 可选:删除用户发送的频道提及消息,保持频道整洁
      await msg.delete().catch(err => console.error(err));
    });

    // 收集器超时处理
    collector.on('end', collected => {
      if (collected.size === 0) {
        interaction.followUp({
          content: '超时未回复,公告发布操作已取消!',
          ephemeral: true
        });
      }
    });
  }
});
  1. 关键细节说明
  • 使用ephemeral: true确保交互消息仅操作用户可见,避免干扰频道内其他成员
  • 消息收集器的filter严格限制仅接收发起按钮点击的用户的消息,防止其他人误操作
  • 增加频道权限验证,提前规避机器人发送失败的情况
  • 通过interaction.message.embeds[0]直接复用之前的预览嵌入,无需重新生成

必备前提

  • 在Discord开发者面板的Bot设置中,开启Message Content Intent权限,否则机器人无法读取用户发送的频道提及内容
  • 确保你的按钮自定义ID与代码中的submit_announcement一致

内容的提问来源于stack exchange,提问作者Mohammad Zohaib Ur Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:15:44