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

使用Discord.js编写BlackJack代码时遇UnknownEnumValueError求助

Discord.js Blackjack游戏报错排查:UnknownEnumValueError

我在用Discord.js开发Blackjack游戏时,每次执行命令控制台都会弹出如下错误:

UnknownEnumValueError > PRIMARY Expected the value to be one of the
following enum values:

| Primary or 1 | Secondary or 2 | Success or 3 | Danger or 4

| Link or 5

以下是我的代码:

const { EmbedBuilder, ActionRowBuilder, ButtonBuilder } = require('discord.js');

module.exports = async (bot, message, args, argsF) => {
  let cards = [];
  let playerHand = [];
  let playerScore = 0;
  let gameOver = false;

  function createDeck() {
    for (let i = 2; i <= 11; i++) {
      cards.push(i);
    }
  }

  function drawCard() {
    const index = Math.floor(Math.random() * cards.length);
    const card = cards[index];
    cards.splice(index, 1);
    return card;
  }

  function updatePlayerHand() {
    const card = drawCard();
    playerHand.push(card);
  }

  function updatePlayerScore() {
    playerScore = playerHand.reduce((sum, card) => sum + card, 0);
  }

  async function playGame(msg) {
    createDeck();
    updatePlayerHand();
    updatePlayerScore();

    const row = new ActionRowBuilder().addComponents(
      new ButtonBuilder()
        .setCustomId('hit')
        .setLabel('Ещё')
        .setStyle('PRIMARY'),
      new ButtonBuilder()
        .setCustomId('stay')
        .setLabel('Стоп')
        .setStyle('SUCCESS')
    );

    const embed = new EmbedBuilder()
      .setTitle('BlackJack')
      .setColor('#FECB4E')
      .setDescription('Цель игры: набрать как можно больше очков, но не более 21.')
      .addField('Ваши карты:', playerHand.join(', '))
      .addField('Ваш счет:', playerScore.toString())
      .setFooter('🃏 Ещё или стоп? Выберите действие.');

    const gameMessage = await msg.channel.send({ embeds: [embed], components: [row] });

    const collector = gameMessage.createMessageComponentCollector({ componentType: 'BUTTON', time: 60000 });

    collector.on('collect', async (interaction) => {
      if (!gameOver) {
        if (interaction.user.id === msg.author.id) {
          await interaction.deferUpdate();

          if (interaction.customId === 'hit') {
            updatePlayerHand();
            updatePlayerScore();

            if (playerScore > 21) {
              gameOver = true;
              embed.setColor('#FF4B4B')
                .setDescription('😔 Вы проиграли! Ваш счет превысил 21.')
                .setFooter('');
              gameMessage.edit({ embeds: [embed], components: [] });
            } else {
              embed
                .spliceFields(0, 2)
                .addField('Ваши карты:', playerHand.join(', '))
                .addField('Ваш счет:', playerScore.toString());
              gameMessage.edit({ embeds: [embed] });
            }
          } else if (interaction.customId === 'stay') {
            gameOver = true;
            embed.setColor('#45F06A')
              .setDescription('🎉 Поздравляем! Вы завершили игру.')
              .setFooter('');
            gameMessage.edit({ embeds: [embed], components: [] });
          }
        }
      } else {
        interaction.deferUpdate();
      }
    });

    collector.on('end', () => {
      if (!gameOver) {
        gameOver = true;
        gameMessage.edit({ components: [] });
      }
    });
  }

  playGame(message);
};

module.exports.names = ['blackjack', 'блэкджек'];

问题原因与修复方案

错误根源是按钮样式的枚举值格式错误:Discord.js v14及以上版本中,按钮样式的字符串值要求首字母大写的驼峰格式,而非全大写。

修改代码中按钮的setStyle参数即可解决:

const row = new ActionRowBuilder().addComponents(
  new ButtonBuilder()
    .setCustomId('hit')
    .setLabel('Ещё')
    .setStyle('Primary'), // 将'PRIMARY'改为'Primary'
  new ButtonBuilder()
    .setCustomId('stay')
    .setLabel('Стоп')
    .setStyle('Success')  // 将'SUCCESS'改为'Success'
);

补充说明

Discord.js v14的ButtonStyle枚举可选值为:

  • Primary(或数字1)
  • Secondary(或数字2)
  • Success(或数字3)
  • Danger(或数字4)
  • Link(或数字5)
    使用全大写字符串不符合枚举类型要求,因此触发了UnknownEnumValueError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:12:06