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

discord.py报错:'Command' object has no attribute 'Context' 求助

问题排查与解决

错误根源

你触发的AttributeError: 'Command' object has no attribute 'Context',核心原因是错误地在命令函数的参数类型注解里,引用了bot.command(name="avatar")返回的Command对象的Context属性。bot.command()调用后返回的是一个Command实例,它本身并不包含Context属性——Context是discord.py的commands模块提供的独立类,和你之前正常运行的命令里用的commands.Context是同一个。

正确的非装饰器写法

如果你不想用装饰器语法,需要按以下步骤正确实现:

  1. 先定义命令函数,参数类型注解保持和之前正常命令一致,用commands.Context:
async def avatar(ctx: commands.Context) -> discord.Message:
    # 示例逻辑:获取提及用户或发送者的头像
    target = ctx.author if not ctx.message.mentions else ctx.message.mentions[0]
    return await ctx.send(f"{target.name}的头像:{target.avatar.url}")
  1. 手动创建Command对象并添加到bot中:
# 方式一:分步创建
avatar_cmd = bot.command(name="avatar")(avatar)
bot.add_command(avatar_cmd)

# 方式二:合并写法
bot.add_command(bot.command(name="avatar")(avatar))

关键注意点

无论用装饰器还是手动注册命令,参数的类型注解必须始终使用commands.Context,不能写成bot.command(...).Context——这是混淆了Command对象和Context类的归属关系导致的低级错误。其余6个同格式命令正常运行,说明它们的类型注解都是正确的commands.Context,只有这个avatar命令写错了注解部分。

内容的提问来源于stack exchange,提问作者Daeltam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 09:19:53