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

discord.js按钮点击一次后失效,如何实现无限点击?

解决Discord.js按钮只能点击一次的问题

问题根源

  1. 组件收集器设置了time: 15000,15秒后收集器会自动停止工作,超时后无法再触发按钮交互。
  2. 计数逻辑错误:你通过button.data.label + 1计算新数值,但button.data.label是字符串类型,直接拼接会得到"01"这类无效结果;同时你没有更新原始计数变量,导致每次计算都基于初始值0,无法实现递增。

修正后的代码

初始化部分

// 用独立变量存储计数,不依赖按钮label
let cookieCount = 0;

const button = new ButtonBuilder()
    .setCustomId('cookie')
    .setLabel(cookieCount.toString())
    .setStyle(ButtonStyle.Primary);

const clicker = new ActionRowBuilder().addComponents(button);

// 发送初始消息(需补充你的embed逻辑)
await interaction.reply({ embeds: [embed], components: [clicker] });

交互监听逻辑

const filter = i => i.customId === 'cookie' && i.user.id === interaction.user.id;
// 移除time参数,让收集器持续监听(或设置极大超时值)
const collector = interaction.createMessageComponentCollector({ filter });

collector.on('collect', async i => {
    if (i.customId === 'cookie') {
        // 递增计数
        cookieCount++;
        // 创建更新后的按钮
        const updatedButton = new ButtonBuilder()
            .setCustomId('cookie')
            .setLabel(cookieCount.toString())
            .setStyle(ButtonStyle.Primary);
        
        const updatedRow = new ActionRowBuilder().addComponents(updatedButton);
        
        // 更新消息内容
        await i.update({ embeds: [embed], components: [updatedRow] });
    }
});

// 可选:需要停止监听时手动调用
// collector.stop();

关键优化点

  • 使用独立变量cookieCount存储计数,避免依赖按钮的label属性,逻辑更稳定。
  • 改用interaction.createMessageComponentCollector,仅监听当前消息的组件交互,不会干扰频道内其他消息。
  • 移除time参数,让收集器持续运行,直到手动停止或消息被删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:27:26