You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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")

错误原因

  1. hybrid命令的上下文兼容性问题:hybrid命令同时支持前缀触发(使用commands.Context)和应用命令触发(使用discord.Interaction),在discord.py 2.3.2中,单独给参数标注commands.Context会导致应用命令路径的类型校验失败,因为应用命令体系不识别该类型注解。
  2. 类方法的导入/继承问题:如果该命令是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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:10:05