Discord模态框回调未触发,提交报错无控制台日志
问题排查与解决方案
可能原因1:模态框未设置自定义ID(custom_id)
Discord 通过 custom_id 关联模态框实例与回调函数。如果 HostGameModal 未显式设置该参数,Discord 无法正确将提交事件匹配到对应回调,导致触发失败。
修复方案
在 HostGameModal 的初始化方法中添加 custom_id,可根据业务场景设置固定值或动态生成唯一标识:
class HostGameModal(Modal): def __init__(self, era: str, *args, **kwargs): # 显式设置custom_id,这里按era区分不同模态框实例 super().__init__(custom_id=f"host_game_modal_{era}", *args, **kwargs) self.era = era # 剩余组件添加代码保持不变...
可能原因2:模态框实例被垃圾回收
命令函数执行完毕后,局部变量 modal 会被 Python 垃圾回收机制销毁。当用户提交模态框时,Bot 找不到对应的实例来触发 callback,从而抛出无提示的错误。
修复方案
将模态框实例添加到 Bot 的视图管理器中,确保实例在回调触发前不会被回收:
@discord.app_commands.command(name="host_game_test", description="Host a new game") async def host_game_test(self, interaction: discord.Interaction): modal = HostGameModal(title="Host New Game", era=GameAge.EA) # 将模态框添加到Bot视图,延长实例生命周期 interaction.client.add_view(modal) await interaction.response.send_modal(modal)
额外验证项
- 检查 Bot 在目标服务器中是否拥有
SendMessages、EmbedLinks等必要权限 - 确保
GameAge.EA是有效的字符串类型(若为枚举类,需确认其__str__或value能返回合法字符串) - 在
HostGameModal的__init__中添加日志,验证实例是否被正确创建
内容的提问来源于stack exchange,提问作者Cerzi
相关产品推荐
相关产品推荐

