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

Discord.py Modal无法发送求助:按钮触发模态框失败

问题分析与修复方案

你的代码存在三个核心问题导致Modal无法正常触发:

  1. Modal未添加文本输入组件:自定义的VerifyModal类中,创建了TextInput但没有将其添加到Modal实例中,导致Modal没有可输入的字段。
  2. Modal发送方式错误:在按钮回调中使用ctx.send()发送Modal是错误的,Discord.py中必须通过interaction.response.send_modal()来触发Modal。
  3. 按钮视图未设置永久有效:默认的View会在一段时间后超时失效,需要设置timeout=None让按钮一直可用。

以下是修复后的完整代码:

class VerifyModal(discord.ui.Modal, title="Verify"):
    def __init__(self):
        super().__init__(timeout=None)
        self.username = discord.ui.TextInput(label="Fortnite Username", placeholder="Ninja...", required=True)
        # 将文本输入组件添加到Modal
        self.add_item(self.username)

    # 可选:处理Modal提交后的逻辑
    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"已收到你的用户名:{self.username.value}", ephemeral=True)

@bot.command()
async def verify_embed(ctx):
    embed = discord.Embed(
        title="Verify",
        color=discord.Color.green()
    )
    embed.add_field(name="How Do I Verify?", value="To Verify Please Click The Button below!", inline=False)

    verify_button = discord.ui.Button(label="Verify", style=discord.ButtonStyle.green, custom_id="verify", emoji="✅")

    async def verify_button_callback(interaction: discord.Interaction):
        # 通过交互响应发送Modal
        modal = VerifyModal()
        await interaction.response.send_modal(modal)

    verify_button.callback = verify_button_callback
    # 设置视图永久有效
    button_view = discord.ui.View(timeout=None)
    button_view.add_item(verify_button)

    message = await ctx.send(embed=embed, view=button_view)

关键修复点说明

  • 添加TextInput到Modal:在VerifyModal的__init__方法中调用self.add_item(self.username),确保输入字段被加载到Modal中。
  • 使用正确的Modal发送方法:替换ctx.send()为interaction.response.send_modal(modal),这是Discord.py触发Modal的标准方式。
  • 设置View永久有效:创建View时传入timeout=None,避免按钮因超时失效。
  • 可选的提交处理逻辑:添加on_submit方法可以处理用户提交Modal后的响应,比如发送仅用户可见的确认消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 18:42:07