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

Discord.js v13实现点击按钮后隐藏原消息按钮功能

修改Discord Slash命令实现点击按钮后隐藏原消息按钮

核心修改点

  • 保存机器人回复的原消息对象,用于后续编辑移除按钮
  • 限制收集器仅响应目标按钮与发起命令的用户,避免误触发
  • 点击按钮后优先编辑原消息移除组件,再发送新事实内容

修改后的完整代码

if(commandName === 'facts'){
      try{
        const factsRow = new MessageActionRow()
          .addComponents(
            new MessageButton()
              .setLabel('More Facts')
              .setStyle('PRIMARY')
              .setCustomId('facts1')
            )
            .addComponents(
              new MessageButton()
              .setURL('https://top.gg/bot/874488895037911041/vote')
              .setLabel('Vote Us')
              .setStyle('LINK')
            )
         
        const mavlina = new Mavlina()
        const factsd = await mavlina.facts()
         // 初始事实Embed
         const factsEmbed = new MessageEmbed()
         .setColor('#111133')
         .setTitle("Facts")
         .setDescription(`${factsd.data}`)

       // 发送初始回复并获取消息对象
       const replyMsg = await interaction.reply({
        components: [factsRow],
        embeds: [ factsEmbed ],
        fetchReply: true // 必须开启才能拿到回复的消息实例
       })
       
       // 创建仅针对当前消息的按钮收集器
       const collector = replyMsg.createMessageComponentCollector({
         filter: i => i.customId === 'facts1' && i.user.id === interaction.user.id,
         time: 60000 // 可选:1分钟后收集器自动失效
       })

       collector.on('collect', async (i) => { 
        // 编辑原消息,移除所有按钮组件
        await replyMsg.edit({ components: [] })
        
        // 获取新事实并生成Embed
        const mavlina = new Mavlina()
        const factbtn = await mavlina.facts()
        const factsbtnEmbed = new MessageEmbed()
         .setColor('#111133')
         .setTitle("Facts")
         .setDescription(`${factbtn.data}`)
        
        // 发送新的事实内容
        await i.reply({ embeds: [factsbtnEmbed] })
       })

       // 收集器超时后的处理(可选)
       collector.on('end', () => {
         if (replyMsg.components.length > 0) {
           replyMsg.edit({
             components: [
               new MessageActionRow().addComponents(
                 factsRow.components.map(btn => btn.setDisabled(true))
               )
             ]
           })
         }
       })
      }catch(err){
        console.log(err.message)
      }
   }

关键逻辑说明

  1. 获取原消息对象:通过interaction.reply的fetchReply: true参数,拿到机器人发送的初始消息实例,这是修改原消息组件的前提。
  2. 精准收集按钮事件:使用replyMsg.createMessageComponentCollector创建消息专属收集器,配合过滤器确保只有目标按钮和命令发起者的操作会被响应。
  3. 隐藏原按钮:在按钮点击事件中,调用replyMsg.edit({ components: [] })清空原消息的组件,实现按钮隐藏效果。
  4. 超时优化:添加收集器超时时间,超时后自动禁用按钮,避免无效按钮长期存在。

内容的提问来源于stack exchange,提问作者AlpHa Coder

相关产品推荐
方舟 Agent Plan

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

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