Discord.py模态表单命令无响应且控制台无报错问题排查
Discord Bot模态表单问题排查与解决
一、原代码无响应的可能原因
- 模态类定义错误:如果
myModal未正确继承discord.ui.Modal,或内部TextInput的custom_id重复、未配置,会导致send_modal执行失败。检查类结构是否符合规范:class myModal(discord.ui.Modal): def __init__(self): super().__init__(title="自定义模态标题") # 确保每个TextInput的custom_id唯一 self.add_item(discord.ui.TextInput(label="输入框名称", custom_id="unique_input_1")) - Cog加载异常:确认
modalGroup Cog已通过bot.add_cog()正确加载,命令的@app_commands.command()装饰器无拼写错误。 - 交互响应超时:Discord要求交互触发后3秒内必须发送响应,若
print("0")之后有阻塞性同步操作,会导致响应超时失效。
二、启动时打印调试信息的原因
启动时输出的2、3等数字,是代码中残留的调试print()语句导致的。全局搜索这些数字对应的打印代码,删除即可消除启动时的冗余输出。
三、让控制台打印表单回复的方法
在模态的提交回调函数中,通过interaction.data提取用户输入并打印:
async def on_submit(self, interaction: discord.Interaction): # 根据组件层级获取输入内容,custom_id需与定义的文本框一致 user_input = interaction.data["components"][0]["components"][0]["value"] print(f"用户提交内容:{user_input}") # 发送私信与指定频道逻辑 await interaction.user.send(f"你提交了:{user_input}") target_channel = interaction.guild.get_channel(你的目标频道ID) if target_channel: await target_channel.send(f"{interaction.user.mention}提交了:{user_input}") await interaction.response.send_message("提交成功", ephemeral=True)
测试模态打印问题本身,说明你在测试代码的回调中错误打印了固定文本而非用户输入,需修正测试代码的回调逻辑。
内容的提问来源于stack exchange,提问作者AJ Goh
相关产品推荐
相关产品推荐

