Search code examples
pythondiscord.pyuser-roles

How can i check if a user has a specific role


@bot.command()
async def help(ctx):
    Log = open("logs/log.md", "a")
    Log.write(f"\n {ctx.message.author} used (help) ")

    color = int(0xecec28)
    guild = ctx.guild

    CommandReplyHelpPerms = open("helpCmd/CommandReplyHelpPermsNeeded.md", "r")
    CommandReplyHelpPerms2 = open("helpCmd/CommandReplyHelpPermsNeeded2.md", "r")
    CommandReplyHelpPerms3 = open("helpCmd/CommandReplyHelpPermsNeeded3.md", "r")

    role5 = discord.utils.get(guild.roles, name="PERM-mod")
    role6 = discord.utils.get(guild.roles, name="PERM-admin")
    role7 = discord.utils.get(guild.roles, name="Moderator")

    if not role5:
        role5 = await guild.create_role(name="PERM-mod", colour=discord.Colour(color))
    if not role6:
        role6 = await guild.create_role(name="PERM-admin", colour=discord.Colour(color))

    CommandReplyHelpNoPerms = open("helpCmd/CommandReplyHelpNoPerms.md", "r")

    embed2 = discord.Embed(title="Help", description=f"Zeigt alle Befehle mit der zugehörigen Syntax an",colour=0xecec28)
    embed2.add_field(name="Help", value="Befehle  MIT benötigten Berechtigungen", inline=False)
    embed2.add_field(name="Allgemeine Befehle", value=CommandReplyHelpPerms.read(), inline=False)
    embed2.add_field(name="Mute/Warn/Softban", value=CommandReplyHelpPerms2.read(), inline=False)
    embed2.add_field(name="ModRoles/Permissions", value=CommandReplyHelpPerms3.read(), inline=False)

    embed = discord.Embed(title="Help", description=f"Zeigt alle Befehle mit der zugehörigen Syntax an",
                          colour=0xecec28)
    embed.add_field(name="Befehle OHNE benötigte Berechtigungen", value=CommandReplyHelpNoPerms.read(),
                    inline=False)
    if role7 in user.roles:
        await ctx.send(embed=embed2)
    else:
        await ctx.send(embed=embed)
    Log.write(f" : (help) executed successfully")
    Log.close()

I have this Code and i cant figure out how to check if a user has a role. I looked up on the Internet but it isnt working. i also tried Member.roles. Can someone help me?


Solution

  • To check for a role in discord.py you do the following if you're in a command:

    role = ctx.guild.get_role(role id here) #by id
    role = discord.utils.get(guild.roles, name="name here") #by name
    
    if role in ctx.author.roles:
    
        #do stuff
    

    Both of these funcs return none if not found