使用discord.py创建模态框遇AttributeError问题求助
问题解决与实现指南
错误原因分析
- Context对象无response属性:Discord模态框(Modal)只能通过交互(Interaction)对象触发,前缀命令的
Context(即ctx)不具备response属性,无法直接用来发送模态框。 - 错误的交互调用:你写的
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
相关产品推荐
相关产品推荐

