使用discord.py开发模态窗口无响应问题求助
问题原因及修复方案
核心问题分析
你的代码存在两个关键错误,导致前缀命令$test执行后无响应:
- 前缀命令参数错误:使用
@commands.command()定义的前缀命令,第一个参数必须是commands.Context(通常简写为ctx),而非直接传入discord.Interaction。 - 模态窗口调用方式错误:前缀命令无法直接通过
interaction对象发送模态窗口,需通过上下文对象获取交互实例,或改用更适配的斜杠命令。
修复方案
方案一:改用斜杠命令(推荐)
模态窗口基于Discord交互系统设计,斜杠命令天然适配该机制,无需额外处理意图兼容性:
from discord.ext import commands import discord from discord import app_commands class ModalTest(discord.ui.Modal, title='ModalTest'): name = discord.ui.TextInput( label='Name', placeholder='Your name here...', ) feedback = discord.ui.TextInput( label='Something', style=discord.TextStyle.long, placeholder='placeholder', required=False, max_length=300, ) async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message(f'Name: {self.name.value}!', ephemeral=True) async def on_error(self, interaction: discord.Interaction, error: Exception) -> None: await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True) class TestCog(commands.Cog): def __init__(self, client): self.client = client @app_commands.command(name='test', description='测试模态窗口') async def test(self, interaction: discord.Interaction): await interaction.response.send_modal(ModalTest()) async def setup(client): await client.add_cog(TestCog(client))
方案二:修复前缀命令
若坚持使用$test前缀命令,需调整参数并启用消息内容意图:
from discord.ext import commands import discord class ModalTest(discord.ui.Modal, title='ModalTest'): name = discord.ui.TextInput( label='Name', placeholder='Your name here...', ) feedback = discord.ui.TextInput( label='Something', style=discord.TextStyle.long, placeholder='placeholder', required=False, max_length=300, ) async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message(f'Name: {self.name.value}!', ephemeral=True) async def on_error(self, interaction: discord.Interaction, error: Exception) -> None: await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True) class TestCog(commands.Cog): def __init__(self, client): self.client = client @commands.command(description='测试模态窗口') async def test(self, ctx: commands.Context): # 检查是否存在可用交互对象 if not ctx.interaction: await ctx.send('该命令需在服务器上下文使用!') return await ctx.interaction.response.send_modal(ModalTest()) async def setup(client): await client.add_cog(TestCog(client))
额外配置要求
- 启用消息内容意图:在Discord开发者门户的机器人页面开启
Message Content Intent,并在客户端初始化时添加:intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix='$', intents=intents) - 同步斜杠命令:若使用方案一,需在
on_ready事件中同步命令到服务器:@client.event async def on_ready(): await client.tree.sync() print(f'已登录为 {client.user}')
内容的提问来源于stack exchange,提问作者FlamyIce
相关产品推荐
相关产品推荐

