如何为discord.py创建自定义装饰器?

时间:2020-02-18 18:40:06

标签: python discord.py discord.py-rewrite python-3.8

我知道我问了这个问题before,但是新的更新突然中断了我的代码。这就是我所拥有的:

def predicate(ctx):
    return Moderation.mod_role in ctx.author.roles


has_mod_role = commands.check(predicate)


class Moderation(commands.Cog):
    mod_role = None

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.mod_role = ...

    @commands.command()
    @has_mod_role
    async def command(self, ctx):
        ...

这曾经起作用,但是现在Moderation.mod_role已从函数中定义的角色更改为“无”,因此即使任何人都具有所需的角色,这些命令也无法与任何人一起使用。

我正在使用python 3.8和discord.py 1.3.1。

1 个答案:

答案 0 :(得分:1)

我使用全局变量解决了该问题。如果有人遇到此问题,这是我的代码:

def has_mod_role():
    def predicate(ctx):
        return mod_role in ctx.author.roles
    return commands.check(predicate)


class Moderation(commands.Cog):
    mod_role = None

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        global mod_role
        mod_role = ...

    @commands.command()
    @has_mod_role()
    async def command(self, ctx, ...):
        ...