Check if user has Admin — Discord.py

Question:

I would like to make a command that requires the user to have Administrator permission to execute the command.

An example is when a user first invited bot on the server, members must not be able to the use the so called "permissions" command. However members with the moderator role should have access to it and execute the rest of the command.

Would anyone be able to help with this in my command?

Asked By: Arda Yılmaz

||

Answers:

It’s still not clear what you want to reserve who you want to command to be avaliable to however, the has_permissions decorator allows you to set what permissions a user can use to access a command. This can be set within the parameters

For example, if you just only want a member with Administrator permissions to have access to your command, you can add @commands.has_permissions(administrator = True) after the command decorator. Heres an example,

@bot.command()
@commands.has_permissions(administrator = True)
async def permission(ctx):
    await ctx.send('You have administrator access...')

More information can be found in Discord’s documentation:
https://discordpy.readthedocs.io/en/latest/ext/commands/api.html

EDIT:

However, using an if statement within a command can be done with:

if ctx.author.guild_permissions.administrator:
...
Answered By: Cohen

While this question is aimed at discord.py – this question came up when I was searching for how to do this with it’s sort-of successor library Discord Interactions as discord.py is quite limited – so I’ll let people know how to do this with interactions too.

So for those wondering, this is how you check if the calling user is a Server Administrator on interactions:

import interactions
bot = interactions.Client(token=TOKEN)

@bot.command(scope=SERVER_IDS)
async def my_command(ctx):
    perms = (await ctx.author.get_guild_permissions(ctx.guild_id))
    if interactions.Permissions.ADMINISTRATOR in perms:
        return await ctx.send("You are an admin")
    
    await ctx.send("You are NOT an admin")

Additionally, here’s a function snippet which can be used within your commands to quickly check if the caller is a server admin:

async def is_server_admin(ctx: Union[CommandContext, ComponentContext]) -> bool:
    """Returns :bool:`True` if the calling user is a Discord Server Administrator"""
    perms = (await ctx.author.get_guild_permissions(ctx.guild_id))
    return interactions.Permissions.ADMINISTRATOR in perms

Example usage of that function:

@bot.command(scope=SERVER_IDS)
async def my_command(ctx):
    if await is_server_admin(ctx):
        return await ctx.send("You are an admin")
    await ctx.send("You are NOT an admin")
Answered By: Someguy123
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.