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

如何在File 2中定义TextInputBuilder的CustomID 'titlem'?

处理模态框CustomID为'titlem'的输入值

核心逻辑

当用户提交模态框时会触发对应交互事件,你需要在该事件中通过输入框的CustomID(即titlem)提取输入内容。以下是基于主流Discord开发库的实现示例:


Discord.js 示例

File 1(模态框创建)

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

// 创建模态框
const titleModal = new ModalBuilder()
    .setCustomId('title_submit_modal') // 模态框自身的CustomID
    .setTitle('输入标题');

// 创建CustomID为'titlem'的输入框
const titleInput = new TextInputBuilder()
    .setCustomId('titlem')
    .setLabel('请输入标题内容')
    .setStyle(TextInputStyle.Short);

titleModal.addComponents(new ActionRowBuilder().addComponents(titleInput));

// 在send按钮点击时触发模态框
client.on('interactionCreate', async interaction => {
    if (interaction.isButton() && interaction.customId === 'send_button') {
        await interaction.showModal(titleModal);
    }
});

File 2(模态框提交处理)

client.on('interactionCreate', async interaction => {
    // 处理模态框提交事件
    if (interaction.isModalSubmit() && interaction.customId === 'title_submit_modal') {
        // 通过CustomID 'titlem' 获取输入值
        const userTitle = interaction.fields.getTextInputValue('titlem');
        
        // 后续逻辑:比如回复用户、存储数据等
        await interaction.reply(`你输入的标题是:${userTitle}`);
    }
});

Pycord(Python)示例

File 1(模态框创建)

import discord
from discord.ui import Modal, TextInput

class TitleModal(Modal):
    def __init__(self):
        super().__init__(title="输入标题", custom_id="title_submit_modal")
        # 添加CustomID为'titlem'的输入框
        self.add_item(TextInput(
            label="请输入标题",
            custom_id="titlem",
            style=discord.TextStyle.short
        ))

# 绑定send按钮的回调
async def send_button_callback(interaction):
    await interaction.response.send_modal(TitleModal())

File 2(按钮及模态框处理)

@client.tree.command(name="open_modal", description="打开标题输入模态框")
async def open_modal(interaction):
    send_button = discord.ui.Button(label="Send", custom_id="send_button")
    send_button.callback = send_button_callback
    view = discord.ui.View()
    view.add_item(send_button)
    await interaction.response.send_message("点击按钮输入标题", view=view)

# 处理模态框提交
@client.event
async def on_modal_submit(interaction):
    if interaction.custom_id == "title_submit_modal":
        # 通过CustomID 'titlem' 获取输入值
        user_title = interaction.fields.get("titlem").value
        await interaction.response.send_message(f"你输入的标题是:{user_title}")

关键注意点

  • 区分模态框的CustomID和输入框的CustomID:前者用于识别是哪个模态框的提交事件,后者用于定位具体的输入字段。
  • 确保在interactionCreate(JS)或on_modal_submit(Python)事件中正确监听模态框提交动作,再通过指定的titlem提取内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:40:50