Discord.py上下文菜单类内定义报错TypeError,如何解决?
修复Discord机器人上下文菜单类内定义的报错问题
问题描述
我想要在Discord机器人中创建上下文菜单,参考文档编写了如下代码:
@app_commands.context_menu(name='react') async def react_(self, interaction: discord.Interaction, message: discord.Message): await interaction.response.send_message('Very cool message!', ephemeral=True)
运行代码时控制台出现错误:TypeError: context menus cannot be defined inside a class,请问该如何修复这个问题?
解决方案
方案1:将上下文菜单函数移到类外部定义
直接把被装饰的函数放到类的外部,避开类内定义的限制,之后在类的初始化或钩子方法中注册该命令:
@app_commands.context_menu(name='react') async def react_(interaction: discord.Interaction, message: discord.Message): await interaction.response.send_message('Very cool message!', ephemeral=True) class MyBot(commands.Bot): async def setup_hook(self): await self.tree.add_command(react_)
方案2:手动创建上下文菜单对象并绑定类方法
如果需要在类内处理逻辑,可以定义类方法,然后手动实例化上下文菜单对象并绑定回调,最后注册到命令树:
class MyBot(commands.Bot): async def setup_hook(self): react_menu = app_commands.ContextMenu( name='react', callback=self.react_ ) self.tree.add_command(react_menu) async def react_(self, interaction: discord.Interaction, message: discord.Message): await interaction.response.send_message('Very cool message!', ephemeral=True)
报错原因说明
@app_commands.context_menu装饰器不支持直接在类内部修饰函数,因为该装饰器默认会将函数当作独立的命令单元处理,无法识别类的实例绑定关系,因此会抛出类型错误。上述两种方案分别通过移出类外或手动绑定类方法的方式解决了该问题。
内容的提问来源于stack exchange,提问作者Bohdan
相关产品推荐
相关产品推荐

