You need to enable JavaScript to run this app. discord.py命令内部调用自定义命令报错 无需Cog方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

discord.py命令内部调用自定义命令报错 无需Cog方案咨询

无需Cog的discord.py命令复用实现方案

报错根因

当前调用抛出AttributeError: 'NoneType' object has no attribute 'cog'的核心原因是命令名匹配错误:

  • 原cv_local函数的装饰器指定name='Bot',实际注册到机器人命令树里的命令名是大写的Bot,并非小写的cv_local
  • 代码中通过bot.get_command('cv_local')查找命令对象时,因名称不匹配直接返回None,后续ctx.invoke尝试读取空对象的cog属性就直接触发了报错

最简无Cog实现方案

完全不需要搭建额外Cog结构,也不需要硬走跨命令调用链路,直接抽离核心业务逻辑为独立普通异步函数,两个命令入口直接调用即可,是结构最轻量的实现方式:

  • 抽离核心查询逻辑
    把原cv_local函数内所有疫情数据获取、embed生成、消息发送、日志打印的代码,全部移到无装饰器的独立异步函数中,保留ctx和参数透传逻辑即可,示例代码:
    async def get_covid_stats(ctx, country=""):
        translator = Translator()
        translation = translator.translate(country, 'en')
        country = translation.text
        now = datetime.datetime.now()
        startTime = time.time()
        if country == "":
            country = "world"
            print(f"At {now.hour}:{now.minute} user {ctx.message.author.name}(Id: {ctx.message.author.id}) didn't mention any country, sent data for world")
        else:
            print(f"At {now.hour}:{now.minute} user {ctx.message.author.name}(Id: {ctx.message.author.id}) searched for: {Library.exceptionCheck(country)[1]}")
    
        if str(country).lower() in ("world", "kw", "za"):
            url = 'https://www.worldometers.info/coronavirus/'
            code = Library.HttpsRead(url, "świata", translation.src)
        else:
            temp1 = Library.exceptionCheck(country)[0]
            url = f'https://www.worldometers.info/coronavirus/country/{temp1}'
            code = Library.HttpsRead(url, country, config[ctx.guild.name]['country'])
    
        await ctx.send(embed=code)
        print(f"execution took {time.time() - startTime} seconds \n")
    
  • 原Bot命令简化为函数调用入口
    @bot.command(name='Bot', help="Dane nt. zakażenia w danym miejscu")
    async def cv_local(ctx, country=""):
        await get_covid_stats(ctx, country)
    
  • 新增Cv命令同样直接调用核心函数即可
    @bot.command(name='Cv', help="Dane nt. zakażenia w danym miejscu")
    async def cv_local2(ctx, leng=""):
        # 可根据需求透传参数,比如固定传波兰查询参数
        await get_covid_stats(ctx, leng)
    

可选:跨命令invoke实现(无需Cog)

如果不想抽离公共函数,非要使用invoke的方式实现复用,只要避开命令名匹配的坑即可,不需要引入Cog结构:

  • 方式1:修正命令树查找时的名称匹配问题,使用实际注册的命令名查找
    @bot.command(name='Cv', help="Dane nt. zakażenia w danym miejscu")
    async def cv_local2(ctx, leng=""):
        print("Invoking...")
        # 匹配实际注册的命令名,也就是原装饰器指定的 'Bot'
        target_command = bot.get_command('Bot')
        await ctx.invoke(target_command, country=leng)
    
  • 方式2:直接引用原装饰后的命令对象调用invoke方法,完全绕开命令树查找逻辑
    @bot.command(name='Cv', help="Dane nt. zakażenia w danym miejscu")
    async def cv_local2(ctx, leng=""):
        print("Invoking...")
        # 直接引用原命令对象,不需要查询命令树,无名称匹配问题
        await cv_local.invoke(ctx, country=leng)
    

注意:这种依赖命令调用链路的实现方式稳定性较差,一旦后续修改原命令的name参数,很容易再次出现空对象报错,抽公共函数的实现方式无外部依赖,调试和维护成本更低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 05:27:09