如何为discord.py创建自定义装饰器? [英] How do you create a custom decorator for discord.py?

查看:61
本文介绍了如何为discord.py创建自定义装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究机器人.对于某个齿轮,我希望创建一个自定义检查装饰器,以检查运行该命令的人员是否具有特定角色.角色作为实例变量存储为角色类.当我尝试运行它时,它不起作用.您如何制作装饰器?

I am working on a bot. For a certain cog, I wish to create a custom check decorator that checks to see if the person running the command has a certain role. The role is stored as a role class as an instance variable. When I tried running it, it doesn't work. How do you make the decorator?

class Moderation(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.mod_role = None  # Assume there's already a role here

    class Decorator:
        @classmethod
        def requires_mod(cls, func):
            async def decorator(self, ctx: commands.Context, *args, **kwargs):
                if self.mod_role not in ctx.author.roles:
                    await ctx.send("You do not have permission to use this command")
                func(ctx, *args, **kwargs)
            return decorator

    @commands.command()
    @Decorator.requires_mod
    async def purge(self, ctx: commands.Context, amt: int):
        await ctx.channel.purge(limit=amt+1)
        await ctx.send(f":white_check_mark: | Deleted {amt} messages.")

推荐答案

此概念已作为甚至是特定于齿轮的检查,例如

Even the cog-specific checks like cog_check aren't aware of the cog itself: none of them receive self as an argument.

您需要重写您的支票,以使其不依赖于 self .如果您现在知道角色名称或ID,或在创建 Moderation 类时,可以使用内置的

You need to rewrite your check such that it doesn't rely on self. If you know the role names or ids now, or when creating the Moderation class, you can use the built-in has_any_role check.

否则,最简单的方法可能是使用 Moderation 的类属性或全局值来存储角色:

Otherwise the easiest way is probably to use either a class attribute of Moderation or a global value to store the role:

from discord.ext import commands

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__(bot):
        self.bot = bot
        Moderation.mod_role = ... 

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

这篇关于如何为discord.py创建自定义装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆