首页 > 解决方案 > 更改命令 discord.py 所需的角色

问题描述

这不是完整的代码,但这只是我需要解释的,如果一个人想使用这个命令,他需要角色'Admin'但是假设我想用另一个命令将'Admin'更改为'Mod',怎么能我这样做而不从代码本身更改它?

@bot.command(pass_context=True)
    @commands.has_role("Admin")

标签: pythoncommanddiscord.py

解决方案


如果你真的想使用装饰器,你应该创建自己的

role_name = "Admin"

def has_role(item=None):
    def predicate(ctx):
        nonlocal item # So we can edit it's value
        if item is None or item != role_name: # If either the `item` is `None` or it's not the same as the global `role_name` variable, update it
            item = role_name 

        if not isinstance(ctx.channel, discord.abc.GuildChannel):
            raise commands.NoPrivateMessage()

        if isinstance(item, int):
            role = discord.utils.get(ctx.author.roles, id=item)
        else:
            role = discord.utils.get(ctx.author.roles, name=item)
        if role is None:
            raise commands.MissingRole(item)
        return True

    return commands.check(predicate)

这主要是从源代码中复制的,只是做了一些调整

要编辑运行命令所需的角色,您可以简单地执行以下操作:

@bot.command()
async def change(ctx, role: discord.Role):
    global role_name
    role_name = role.name
    await ctx.send(f"Updated to {role.name}")


@bot.command()
@has_role()
async def foo(ctx):
    await ctx.send("Whatever")

推荐阅读