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

Discord NodeJS:验证失败时调用showModal报函数不存在错误

问题描述

尝试在模态框输入验证失败后,重新弹出相同的模态框要求用户输入数字,为此新建了结构完全一致的Modal,但始终出现 interaction.showModal is not a function 错误。

错误原因
  1. 交互类型不支持:ModalSubmitInteraction(模态框提交交互)对象没有 showModal 方法,该方法仅存在于可触发模态框的交互类型中(如按钮交互 ButtonInteraction、选择菜单交互 SelectMenuInteraction)。
  2. 逻辑分支错误:代码中无论验证是否通过,都会执行最后的 interaction.reply,会导致重复回复的报错。
  3. 冗余代码:无需创建两个结构完全一致的模态框,复用同一个实例即可。
修复方案

核心思路

验证失败时,先回复临时错误提示,并附带可重新打开模态框的按钮;修正逻辑分支,确保代码按验证结果执行对应流程;复用模态框实例减少冗余。

修改后的代码示例

1. 模态框与按钮定义

const { ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');

// 定义唯一的数字输入模态框
const numberInputModal = new ModalBuilder()
    .setCustomId('number_input_modal')
    .setTitle('数字输入表单');
const keywordCountInput = new TextInputBuilder()
    .setCustomId('keywordCount')
    .setLabel('你需要多少个关键词?')
    .setStyle(TextInputStyle.Short);

const inputActionRow = new ActionRowBuilder().addComponents(keywordCountInput);
numberInputModal.addComponents(inputActionRow);

// 用于重新打开模态框的按钮
const reopenModalButton = new ButtonBuilder()
    .setCustomId('reopen_number_modal')
    .setLabel('重新输入')
    .setStyle(ButtonStyle.Primary);
const buttonActionRow = new ActionRowBuilder().addComponents(reopenModalButton);

2. 交互事件监听

const { Events } = require('discord.js');

client.on(Events.InteractionCreate, async interaction => {
    // 初始打开模态框的按钮
    if (interaction.isButton() && interaction.customId === 'open_modal') {
        await interaction.showModal(numberInputModal);
    }

    // 重新打开模态框的按钮
    if (interaction.isButton() && interaction.customId === 'reopen_number_modal') {
        await interaction.showModal(numberInputModal);
    }

    // 处理模态框提交
    if (interaction.isModalSubmit() && interaction.customId === 'number_input_modal') {
        const keywordCount = interaction.fields.getTextInputValue('keywordCount');
        const intValue = parseInt(keywordCount);

        if (isNaN(intValue)) {
            // 回复临时错误消息,附带重新输入按钮
            await interaction.reply({
                content: '请仅输入数字!',
                components: [buttonActionRow],
                ephemeral: true // 仅当前用户可见
            });
            return;
        }

        // 验证通过,执行存储逻辑
        const channel = await interaction.client.channels.fetch('1375275416092278784');
        await channel.send(`${intValue}`);

        // 回复成功提示
        await interaction.reply({
            content: '感谢您的输入!我已保存您的关键词数量',
            ephemeral: true
        });
    }
});
关键说明
  • 用按钮触发模态框的重新打开,符合Discord.js的交互规则,因为只有按钮这类交互支持调用 showModal。
  • 使用 ephemeral: true 确保错误和成功消息仅用户可见,避免频道消息混乱。
  • 验证失败时用 return 终止后续代码,避免重复回复的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:43:13