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

Discord.JS v14:点击按钮将标签从0改为1的代码故障排查

问题修复方案

你的代码存在三个核心问题,导致按钮标签无法正常更新:

  1. 语法与结构错误:多余的},};直接终止了交互处理函数,后续修改按钮的代码块不仅不会执行,还因位于函数外部无法访问pol等关键变量。
  2. v14组件不可变特性:Discord.js v14中所有组件都是不可变对象,直接修改v.label不会生效,必须通过组件构建器的方法修改属性。
  3. 数据同步问题:未确保数据库更新完成后再修改按钮标签,可能导致读取的投票数不是最新值。

修复后的完整代码

// 确保这段代码在按钮交互处理事件的回调函数内部
if (!interaction.isButton()) return;

const pol = await polls.findOne({ message: interaction.message.id });
if (!pol) return;

await interaction.deferReply({ ephemeral: true });

// 检查用户是否已投票
if (pol.voters.includes(interaction.user.id)) {
  return interaction.editReply({
    embeds: [{ color: 0xff0000, title: "❌ Already Voted!" }]
  });
}

// 初始化投票对象并更新计数
pol.votes = pol.votes || {};
pol.votes[interaction.customId] = (pol.votes[interaction.customId] || 0) + 1;
pol.voters.push(interaction.user.id);

// 更新数据库,获取最新投票数据
await polls.findOneAndUpdate({ message: pol.message }, pol, { new: true });

// 更新消息中的按钮标签
await interaction.message.edit({
  components: interaction.message.components.map(row => {
    // 从现有行创建新的ActionRowBuilder
    const updatedRow = ActionRowBuilder.from(row);
    // 更新行内每个按钮的标签
    updatedRow.components = updatedRow.components.map(btn => {
      const updatedBtn = ButtonBuilder.from(btn);
      updatedBtn.setLabel(`${pol.votes[btn.customId] || 0}`);
      return updatedBtn;
    });
    return updatedRow;
  })
});

// 回复投票成功提示
interaction.editReply({
  embeds: [{ color: 0x008000, title: "✅ Voted Successfully" }]
});

关键修改说明

  • 移除多余的语法错误代码,将按钮更新逻辑整合到交互处理函数内部,确保投票完成后自动执行。
  • 使用ButtonBuilder.from(btn)创建新按钮实例,通过setLabel()方法修改标签,适配v14的组件不可变规则。
  • 用ActionRowBuilder.from(row)处理行组件,保证结构符合v14的组件要求。
  • 在findOneAndUpdate中添加{ new: true }参数,确保获取数据库中更新后的最新投票数据,避免显示旧值。
  • 简化投票计数写法,提升代码可读性与可靠性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 23:37:45