Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何为discord.py创建自定义装饰器?_Python_Python 3.x_Discord.py_Discord.py Rewrite - Fatal编程技术网

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

Python 如何为discord.py创建自定义装饰器?,python,python-3.x,discord.py,discord.py-rewrite,Python,Python 3.x,Discord.py,Discord.py Rewrite,我在做机器人。对于某个cog,我希望创建一个自定义检查装饰器,用于检查运行命令的人是否具有特定角色。角色作为实例变量存储为角色类。当我试着运行它时,它不起作用。你是怎么做装饰工的 类仲裁命令。Cog: def uuu init uuu self,bot:commands.bot: self.bot=bot self.mod_role=None假设这里已经有一个角色 类装饰器: @类方法 def需要_modcls,func: 异步def decoratorself,ctx:commands.Con

我在做机器人。对于某个cog,我希望创建一个自定义检查装饰器,用于检查运行命令的人是否具有特定角色。角色作为实例变量存储为角色类。当我试着运行它时,它不起作用。你是怎么做装饰工的

类仲裁命令。Cog: def uuu init uuu self,bot:commands.bot: self.bot=bot self.mod_role=None假设这里已经有一个角色 类装饰器: @类方法 def需要_modcls,func: 异步def decoratorself,ctx:commands.Context,*args,**kwargs: 如果self.mod_角色不在ctx.author.roles中: wait ctx.send您没有使用此命令的权限 funcctx、*args、**kwargs 返回装饰器 @命令 @Decorator.mod 异步def purgeself,ctx:commands.Context,amt:int: 等待ctx.channel.purgelimit=amt+1 等待ctx.sendf:white_check_mark:|已删除{amt}消息。
这一概念被内置到commands扩展中

即使是特定于cog的检查,如,也不知道cog本身:它们都不接受self作为参数

你需要重写你的支票,这样它就不会依赖于你自己了。如果您现在知道角色名称或ID,或者在创建仲裁类时知道,则可以使用内置检查

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

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, ...):
        ...