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

使用discord.py创建模态框遇AttributeError问题求助

问题解决与实现指南

错误原因分析

  1. Context对象无response属性:Discord模态框(Modal)只能通过交互(Interaction)对象触发,前缀命令的Context(即ctx)不具备response属性,无法直接用来发送模态框。
  2. 错误的交互调用:你写的await interaction.interaction.response.defer属于重复嵌套,interaction本身就是交互对象,正确写法是await interaction.response.defer(),但发送模态框不需要提前defer,直接调用send_modal即可。

正确实现代码示例

1. 定义模态框类

import discord
from discord import app_commands

class TestModal(discord.ui.Modal, title="测试模态框"):
    # 定义输入字段
    username = discord.ui.TextInput(
        label="用户名",
        placeholder="请输入你的用户名",
        required=True,
        max_length=30
    )
    feedback = discord.ui.TextInput(
        label="反馈内容",
        placeholder="写下你的反馈...",
        style=discord.TextStyle.long,  # 多行输入框
        required=False
    )

    # 提交后的处理逻辑(这里获取用户输入)
    async def on_submit(self, interaction: discord.Interaction):
        # 通过self.输入框变量名.value获取输入内容
        await interaction.response.send_message(
            f"收到你的提交:\n用户名:{self.username.value}\n反馈:{self.feedback.value if self.feedback.value else '无'}",
            ephemeral=True
        )

2. 用Slash命令触发模态框(推荐方式)

# 注册slash命令
@bot.tree.command(name="open_modal", description="打开测试模态框")
async def open_modal(interaction: discord.Interaction):
    # 直接发送模态框
    await interaction.response.send_modal(TestModal())

3. 前缀命令触发模态框(需通过中转按钮)

如果想用前缀命令(如!openmodal)触发,需要先发送带按钮的消息,用户点击按钮后触发交互再打开模态框:

@bot.command()
async def openmodal(ctx):
    # 创建触发按钮
    trigger_btn = discord.ui.Button(label="打开模态框", style=discord.ButtonStyle.blurple)

    # 按钮回调函数
    async def btn_callback(interaction):
        await interaction.response.send_modal(TestModal())

    trigger_btn.callback = btn_callback

    # 发送带按钮的消息
    view = discord.ui.View()
    view.add_item(trigger_btn)
    await ctx.send("点击下方按钮打开模态框", view=view)

获取用户输入的方法

在模态框类的on_submit方法中,通过self.输入框变量名.value即可获取对应输入字段的内容:

  • 比如定义的username输入框,用self.username.value获取用户输入的用户名
  • 可选字段可以用if判断是否有值,避免空值报错

注意事项

  • 确保你的discord.py版本≥2.0,模态框是2.0版本新增的功能,可通过pip install -U discord.py更新
  • Slash命令需要在机器人上线后同步到Discord,可在机器人启动时添加同步代码(或手动同步)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 14:32:26