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

Python中Discord Modal更新TextInput标签后不生效问题

问题描述

我正在学习编写Discord Bot,现在遇到一个Modal组件的问题:我希望用户每次点击按钮打开Modal时,输入框的标签能从预设的问题数组中随机选择,但目前修改new_modal.question.label后,Modal显示的始终是类定义时的默认标签。

我的代码如下:

class FormButtons(discord.ui.View):
    def __init__(self):
        super().__init__()
    
    @discord.ui.button(label="Moderator form", style=discord.ButtonStyle.gray)
    async def moderatorBtn(self, interaction: discord.Interaction, button: discord.ui.Button):
        rand = random.randint(0, len(config.moderator_questions) - 1)
        new_modal = moderation_modal()
        new_modal.question = ui.TextInput(label = config.moderator_questions[rand], style = discord.TextStyle.paragraph, placeholder = f"{rand}", required = True, max_length = 128)
        await interaction.response.send_modal(new_modal)
        await new_modal.wait()
            

class moderation_modal(ui.Modal, title = "Example modal"):
    question = ui.TextInput(label = "Hello!", style = discord.TextStyle.paragraph, placeholder = "Not sure!", required = True, max_length = 128)
    
    async def on_submit(self, interaction: discord.Interaction):
        channel = bot.get_channel(config.form_result_channel)
        embed = discord.Embed(title = self.title, description = f"**{self.answer.label}**\n{self.answer}", timestamp = datetime.now(), color = discord.Colour.blue())
        embed.set_author(name = interaction.user, icon_url = interaction.user.avatar)
        await channel.send(embed = embed)
        await interaction.response.send_message(content=config.response_completed_form, ephemeral=True)

我已经确认每次点击按钮时new_modal.title能正常变化,但Modal的输入框标签始终是默认的"Hello!",请问该如何解决?

解决方案

问题出在discord.py中Modal的组件初始化逻辑:当你把TextInput定义为moderation_modal的类属性时,组件会在类加载时就被初始化,实例化后直接给new_modal.question赋值,并不会把新的TextInput添加到Modal的组件列表里,所以显示的还是默认的那个输入框。

正确的做法是在Modal的__init__方法中动态创建并添加TextInput组件,这样每次实例化Modal时都能传入自定义的标签:

步骤1:修改moderation_modal类

class moderation_modal(ui.Modal, title="Example modal"):
    def __init__(self, question_label: str, placeholder: str):
        super().__init__()
        # 动态创建TextInput并添加到Modal中
        self.question = ui.TextInput(
            label=question_label,
            style=discord.TextStyle.paragraph,
            placeholder=placeholder,
            required=True,
            max_length=128
        )
        self.add_item(self.question)
    
    async def on_submit(self, interaction: discord.Interaction):
        channel = bot.get_channel(config.form_result_channel)
        # 注意:原代码中的self.answer是错误的,应该用self.question.value获取输入内容
        embed = discord.Embed(
            title=self.title,
            description=f"**{self.question.label}**\n{self.question.value}",
            timestamp=datetime.now(),
            color=discord.Colour.blue()
        )
        embed.set_author(name=interaction.user, icon_url=interaction.user.avatar)
        await channel.send(embed=embed)
        await interaction.response.send_message(content=config.response_completed_form, ephemeral=True)

步骤2:修改按钮回调逻辑

在实例化moderation_modal时,直接传入随机选中的问题和占位符:

class FormButtons(discord.ui.View):
    def __init__(self):
        super().__init__()
    
    @discord.ui.button(label="Moderator form", style=discord.ButtonStyle.gray)
    async def moderatorBtn(self, interaction: discord.Interaction, button: discord.ui.Button):
        rand = random.randint(0, len(config.moderator_questions) - 1)
        selected_question = config.moderator_questions[rand]
        # 传入自定义的问题标签和占位符
        new_modal = moderation_modal(question_label=selected_question, placeholder=f"{rand}")
        await interaction.response.send_modal(new_modal)
        await new_modal.wait()

关键说明

  • 不再将TextInput作为类属性定义,而是在__init__中动态创建并通过self.add_item()添加到Modal,确保每次实例化Modal时都使用新的组件配置。
  • 修正了on_submit方法中的错误:原代码中的self.answer不存在,应该用self.question.value来获取用户输入的内容。

这样修改后,用户每次点击按钮打开Modal时,输入框的标签都会是随机选中的问题,满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:05:37