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

Discord.js v14显示模态框报错:ValidationError: Expected a string primitive

Discord.js v14模态框命令ValidationError: Expected a string primitive错误排查

错误原因

Discord.js v14中,TextInputBuilder必须设置标签(Label),这是Discord交互组件的强制要求。你的代码里仅给文本输入框设置了placeholder、customId等属性,但缺少setLabel()方法调用,导致组件验证时触发字符串类型校验错误(label字段为undefined)。

另外,代码中同时调用interaction.showModal(modal)和interaction.reply(...)会触发交互冲突——Discord不允许同一交互中既显示模态框又发送普通回复,必须二选一或在模态框提交后再回复。

解决办法

  1. 给TextInputBuilder添加setLabel()方法,传入非空字符串作为输入框的标签文本。
  2. 移除interaction.reply(...)调用,或者将回复逻辑移到模态框的提交事件处理中。

修改后的完整代码

import {
  SlashCommandBuilder,
  PermissionFlagsBits,
  TextInputStyle,
} from 'discord.js'
import { SlashCommand } from '../types/discord'
import {
  ActionRowBuilder,
  ModalBuilder,
  TextInputBuilder,
} from '@discordjs/builders'

const TestCommand: SlashCommand = {
  command: new SlashCommandBuilder()
    .setName('modaltest')
    .setDescription('Shows a test modal')
    .setDefaultMemberPermissions(PermissionFlagsBits.SendMessages),

  execute: async (interaction) => {
    const modal = new ModalBuilder()
      .setTitle('Test modal')
      .setCustomId('test_modal')

    const input = new TextInputBuilder()
      .setCustomId('test_input')
      .setLabel('Your Input') // 新增:设置必填标签
      .setPlaceholder('Test input')
      .setRequired(true)
      .setStyle(TextInputStyle.Short)

    modal.addComponents(
      new ActionRowBuilder<TextInputBuilder>().addComponents(input),
    )

    // 仅显示模态框,移除冲突的reply
    await interaction.showModal(modal)
    
    // 可选:监听模态框提交事件并回复用户
    // const submitted = await interaction.awaitModalSubmit({ time: 60000 })
    // await submitted.reply({ content: `You entered: ${submitted.fields.getTextInputValue('test_input')}` })
  },
  cooldown: 10,
}

export default TestCommand

关键修改说明

  • 新增.setLabel('Your Input'):满足Discord对文本输入组件的必填要求,直接解决ValidationError。
  • 移除冲突的interaction.reply():避免与showModal的交互冲突。如果需要给用户反馈,可以通过awaitModalSubmit监听模态框提交事件,在用户输入完成后再发送回复(代码中已提供注释示例)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 12:57:28