首页 > 解决方案 > python子命令cog文件

问题描述

您好,我在主页中的子命令一切正常。但是,如果我将命令移动到 cog 文件子命令不起作用,我添加了self, ctxself.bot但它仍然不知道我在哪个地方做错了。

@commands.group(pass_context=True)
async def first(self, ctx):
    if ctx.invoked_subcommand is None:
        await self.bot.say("Ping 1")

@first.group(pass_context=True)
async def second(self, ctx):
    if ctx.invoked_subcommand is second:
        await self.bot.say("Ping 2")

@second.command(pass_context=True)
async def third(self, ctx):
    await self.bot.say("Ping 3")

标签: python-3.xdiscord.py

解决方案


secondsecond评估主体时未定义。此外,invoked_subcommand将永远在second这里,即使你也调用third.

您应该将invoke_without_command属性传递给您的group装饰器。

@commands.group(pass_context=True, invoke_without_command=True)
async def first(self, ctx):
    await self.bot.say("Ping 1")

@first.group(pass_context=True, invoke_without_command=True)
async def second(self, ctx):
    await self.bot.say("Ping 2")

@second.command(pass_context=True)
async def third(self, ctx):
    await self.bot.say("Ping 3")

编辑:

仔细想想,这可能是多虑了。你只需要second通过类来解决它是一种方法:

class MyCog:    
    @commands.group(pass_context=True)
    async def first(self, ctx):
        if ctx.invoked_subcommand is None:
            await self.bot.say("Ping 1")

    @first.group(pass_context=True)
    async def second(self, ctx):
        if ctx.invoked_subcommand is MyCog.second:  # Possibly self.second instead, but I'm not sure.  
            await self.bot.say("Ping 2")

    @second.command(pass_context=True)
    async def third(self, ctx):
        await self.bot.say("Ping 3")

推荐阅读