如何修复discord.py混合命令中的TypeError:不支持的类型注解?
问题:discord.py hybrid_command 类型注解报错
问题场景
使用discord.py 2.3.2结合Interactions API开发Discord机器人时,运行以下Cog中的hybrid命令代码:
@commands.hybrid_command(name='help', with_app_command=True) async def help(self, ctx: commands.Context): await ctx.reply("Test was good!")
触发如下错误:
line 65, in <module> async def help(self, ctx: commands.Context): TypeError: unsupported type annotation <class 'discord.ext.commands.context.Context'>
同时,纯应用命令可以正常运行:
@bot.tree.command() async def test(interaction: discord.Interaction) -> None: await interaction.response.send_message("test successful")
错误原因
- hybrid命令的上下文兼容性问题:hybrid命令同时支持前缀触发(使用
commands.Context)和应用命令触发(使用discord.Interaction),在discord.py 2.3.2中,单独给参数标注commands.Context会导致应用命令路径的类型校验失败,因为应用命令体系不识别该类型注解。 - 类方法的导入/继承问题:如果该命令是Cog类中的方法,需确保正确继承
commands.Cog,且commands.Context的导入路径正确(应为from discord.ext.commands import Context)。
修复方法
方法1:使用联合类型注解(Python 3.10+)
同时兼容两种上下文类型,让hybrid命令可以正常处理两种触发方式:
from discord.ext import commands import discord @commands.hybrid_command(name='help') # with_app_command=True是默认值,可省略 async def help(self, ctx: commands.Context | discord.Interaction): await ctx.send("Test was good!") # send方法在两种上下文类型中都适用
方法2:使用Union类型(Python <3.10)
对于低版本Python,用typing.Union实现联合类型:
from typing import Union from discord.ext import commands import discord @commands.hybrid_command(name='help') async def help(self, ctx: Union[commands.Context, discord.Interaction]): await ctx.send("Test was good!")
方法3:临时移除类型注解(快速测试用)
若只是快速验证命令逻辑,可暂时去掉类型注解:
@commands.hybrid_command(name='help') async def help(self, ctx): await ctx.reply("Test was good!")
补充检查
确保你的Cog类正确定义并注册到机器人:
class HelpCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.hybrid_command(name='help') async def help_cmd(self, ctx: commands.Context | discord.Interaction): # 避免和内置help命令重名 await ctx.send("Test was good!") async def setup(bot): await bot.add_cog(HelpCog(bot))
内容的提问来源于stack exchange,提问作者Woahdang Jr
相关产品推荐
相关产品推荐

