discord.py模态框功能异常,报‘command function must be a coroutine function’错误
问题解决:discord.py中应用命令绑定Modal报错的修复
错误原因
你直接用@tree.command装饰了ui.Modal类,但这个装饰器要求绑定的是异步协程函数,不是类,所以触发了TypeError: command function must be a coroutine function错误。
正确写法
需要先单独定义Modal类,再创建一个被@tree.command装饰的异步命令函数,在函数里调用模态框:
# 先定义Modal类,不要用装饰器 class test2Modal(ui.Modal, title='Questionnaire Response'): name = ui.TextInput(label='Name') answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph) async def on_submit(self, interaction: discord.Interaction): # 注意:TextInput的输入值存在value属性里,要改成self.name.value await interaction.response.send_message(f'Thanks for your response, {self.name.value}!', ephemeral=True) # 用@tree.command装饰异步函数,在函数中触发模态框 @tree.command(name="test2", description="My second application Command", guild=discord.Object(id=736684536741625988)) async def test2(interaction: discord.Interaction): # 实例化Modal并发送给用户 modal = test2Modal() await interaction.response.send_modal(modal)
额外注意点
- 原代码中
on_submit里的self.name要改为self.name.value,否则会输出TextInput对象本身,而不是用户输入的名字。 - 确保你的discord.py版本是最新的,旧版本可能对Modal的支持有差异。
内容的提问来源于stack exchange,提问作者snow
相关产品推荐
相关产品推荐

