KemoF
KemoF

Reputation: 11

Change needed role for command discord.py

this is not the full code but it's only what I need to explain, if a person wants to use this command he needs the role 'Admin' but let's say I want to change 'Admin' to 'Mod' with another command, how can I do that without changing it from the code itself?

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

Upvotes: 0

Views: 209

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

If you really want to use the decorator you should create your own one

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)

This is mostly copied from the source code just with a few tweaks

To edit the role necessary to run the command you could simply do something like this:

@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")

Upvotes: 1

Related Questions