Disnake框架Modal异常:提交报错且无法自动关闭
问题分析与修复方案
核心问题
出现报错的原因有三个:
- Cog中的 slash 命令方法未传入
self参数,导致方法无法正确关联Cog实例 - 模态框的
callback方法没有对交互进行回应,Discord要求所有模态框提交后必须完成交互响应 - 提交成功的消息发送时机错误,在用户打开模态框时就发送了,而非提交之后
修复后的代码
import disnake from disnake.ext import commands from disnake import TextInputStyle class FactionModal(disnake.ui.Modal): def __init__(self): components = [ disnake.ui.TextInput( label="Faction Name", custom_id="name", placeholder="Clan", style=TextInputStyle.short ), disnake.ui.TextInput( label="Members", custom_id="members", placeholder="1. CraftyTheHawk", style=TextInputStyle.paragraph ) ] super().__init__(title="Faction Application", custom_id="faction", components=components) async def callback(self, inter: disnake.ModalInteraction): # 先回应交互,避免Discord报错 await inter.response.send_message("申请已提交!", ephemeral=True) # 获取目标频道并发送嵌入消息 channel = disnake.utils.get(inter.guild.text_channels, id=1036359251926466591) embed = disnake.Embed(title="Faction Application") for key, value in inter.text_values.items(): embed.add_field(name=key.capitalize(), value=value[:1024], inline=False) await channel.send(embed=embed) class faction_cog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.slash_command(name='faction', description='Apply to get your faction official!') async def faction(self, inter: disnake.AppCmdInter): # 添加self参数 await inter.response.send_modal(modal=FactionModal()) def setup(bot): bot.add_cog(faction_cog(bot))
关键修改说明
- 添加
self参数到slash命令:Cog类中的命令方法必须以self作为第一个参数,这样才能正确访问Cog实例的属性和方法。 - 在Modal的
callback中添加交互回应:使用inter.response.send_message()回应模态框交互,ephemeral=True表示只有提交者能看到这条提示,也可以用inter.response.defer()然后后续跟进消息,但必须完成回应。 - 调整成功消息的发送时机:把原slash命令中的成功消息移到
callback里,确保用户提交后才发送提示,修正逻辑错误。 - 统一custom_id大小写:将"Members"改为"members",避免后续处理时出现键名大小写不一致的问题,提升代码健壮性。
内容的提问来源于stack exchange,提问作者CraftyTheHawk
相关产品推荐
相关产品推荐

