Deniz Ascherl
Deniz Ascherl

Reputation: 353

how do I check if a user has a specific role in discord

This should check if the specific person does or doesn't have the mute role

    @bot.command(pass_context=True)
    @commands.has_role("Admin")
    async def unmute(ctx, user: discord.Member):
        role = discord.utils.find(lambda r: r.name == 'Member', 
    ctx.message.server.roles)
        if user.has_role(role):
            await bot.say("{} is not muted".format(user))
        else:
            await bot.add_roles(user, role)

This error is thrown

Command raised an exception: AttributeError: 'Member' object has no attribute 'has_role'

I don't know how to do it so i would really appreciate every help I can get

Upvotes: 9

Views: 73440

Answers (2)

Rovindu Thamuditha
Rovindu Thamuditha

Reputation: 220

Personally I use this:

@bot.command(pass_context=True)
@commands.has_role("Admin")
async def unmute (ctx,user:discord.Member):
  role = discord.utils.get(ctx.guild.roles, name="Muted")

  if role in user.roles:
    await user.remove_roles(role)

    await user.add_roles(role)
    embed = discord.Embed(title="Unmuute Members", description=f"{user.mention} has been unmuted" , color = discord.Color.blue())


    embed.add_field(name='Unmuted by:' , value = f"{ctx.author.mention}")


    await user.remove_roles(role)

    await ctx.send(embed=embed)

  else:
    await ctx.send("Invalid Argumnets or The user is not muted.")

So as you can see

role = discord.utils.get(ctx.guild.roles, name="Muted") this variable locates the Muted role in the server

if role in user.roles:
    await user.remove_roles(role)

and this will remove the role from the user

Upvotes: 0

ktzr
ktzr

Reputation: 1645

Member does not have a .has_role() method, you can however get a list of all their roles using .roles.

To see if a user has a given role we can use role in user.roles.

    @bot.command(pass_context=True)
    @commands.has_role("Admin")
    async def unmute(ctx, user: discord.Member):
        role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
        if role in user.roles:
            await bot.say("{} is not muted".format(user))
        else:
            await bot.add_roles(user, role)

Docs for reference: https://discordpy.readthedocs.io/en/latest/api.html#member

Note: ctx.message.guild.roles use to be ctx.message.server.roles. Updated due to API change.

Upvotes: 19

Related Questions