【问题标题】:How do you create custom decorators for discord.py?如何为 discord.py 创建自定义装饰器?
【发布时间】:2020-06-02 20:41:40
【问题描述】:

我知道我问过这个问题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 已从函数中定义的角色更改为 None,因此命令对任何人都不起作用,即使他们具有所需的角色。

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

【问题讨论】:

  • 好的,所以你使用了其他人的代码(不接受他们的答案),然后重新发布相同的代码,问几个月后如何修复它?您是否查看过他们提供给您的文档链接?他们提到查看Checks,所以在假设 SO 会为您完成工作之前尝试一下。
  • self.mod_role = ... 行的其余部分是什么?这就是这里实际失败的原因。

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


【解决方案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, ...):
        ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2021-11-16
    • 2019-08-31
    • 1970-01-01
    相关资源
    最近更新 更多