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

discord.js执行modal命令时Modal弹窗未显示的代码问题排查

问题诊断

你的代码存在3处核心错误,会直接导致模态框无法正常弹出:

  • 事件与触发逻辑完全不匹配
    interactionCreate事件仅在用户触发斜杠命令、点击组件、提交模态框等交互场景触发,回调传入的是交互对象,不存在content属性,你写的if(msg.content === 'modal')判断永远不会成立。
    另外Discord 本身有接口限制:模态框只能作为交互响应弹出,你无法在用户发送普通文本消息(即messageCreate事件捕获的场景)时给用户弹模态框,必须通过斜杠命令、按钮点击这类用户主动触发的交互调用弹框方法。
  • 缺少交互类型校验
    即使你是通过斜杠命令触发模态框,也需要先校验当前交互的类型,避免处理模态提交、按钮点击等其他交互时抛出异常。
  • 组件类名适配问题
    如果你使用v14版本discord.js,MessageActionRow、Modal、TextInputComponent已经更新为ActionRowBuilder、ModalBuilder、TextInputBuilder,旧类名仅在部分过渡版本做了兼容,正式环境使用建议替换为官方推荐的Builder类,避免出现兼容问题。
修正方案

首先你需要提前注册一个名为modal的斜杠命令,之后使用如下代码即可正常弹出模态框:

const { Client, GatewayIntentBits, ActionRowBuilder, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js');
// 初始化客户端,弹模态框不需要申请消息内容权限
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.on('interactionCreate', async (interaction) => {
  // 过滤非斜杠命令的交互
  if (!interaction.isChatInputCommand()) return;
  // 匹配modal命令
  if (interaction.commandName === 'modal') {
    // 构建模态框
    const modal = new ModalBuilder()
      .setCustomId('myModal')
      .setTitle('My Modal');

    // 构建单行文本输入
    const favoriteColorInput = new TextInputBuilder()
      .setCustomId('favoriteColorInput')
      .setLabel("What's your favorite color?")
      .setStyle(TextInputStyle.Short);

    // 构建多行文本输入
    const hobbiesInput = new TextInputBuilder()
      .setCustomId('hobbiesInput')
      .setLabel("What's some of your favorite hobbies?")
      .setStyle(TextInputStyle.Paragraph);

    // 每个ActionRow仅可放置一个文本输入组件
    const firstActionRow = new ActionRowBuilder().addComponents(favoriteColorInput);
    const secondActionRow = new ActionRowBuilder().addComponents(hobbiesInput);

    modal.addComponents(firstActionRow, secondActionRow);
    // 向用户展示模态框
    await interaction.showModal(modal);
  }
});

// 替换为你的机器人Token
client.login('YOUR_BOT_TOKEN');

提示:全局斜杠命令注册后最长需要1小时同步到所有服务器,测试阶段可以注册服务器级别的斜杠命令,注册后即时生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:48:14