How to get user's role discord.py

Viewed 4213

I'm trying to do a info command as you can see but in the roles section, i can't display the user's roles. At first i did a working command but it display the "@everyone" role too, so i did a string for remove it (mention.remove("everyone")) but it doesn't work it gives an this error:

Command raised an exception: ValueError: list.remove(x): x not in list

I tried to replace "everyone" with "@everyone" too but it still doesn't work..

@client.command()
async def info(ctx, user: discord.Member):

    mention = []
    for role in user.roles:
        mention.append(role.mention)
        mention.remove("everyone")

    b = ", ".join(mention)


    embed = discord.Embed(title="Info:", description=f"Info of: {user.mention}", color=discord.Color.orange())
    embed.add_field(name="Top role:", value=user.top_role)
    embed.add_field(name="Roles:", value=b)

    await ctx.send(embed=embed)
3 Answers

You can just use an if statement to check if the name of the role is @everyone.

@client.command()
async def info(ctx, user: discord.Member):

    mention = []
    for role in user.roles:
        if role.name != "@everyone":
            mention.append(role.mention)

    b = ", ".join(mention)


    embed = discord.Embed(title="Info:", description=f"Info of: {user.mention}", color=discord.Color.orange())
    embed.add_field(name="Top role:", value=user.top_role)
    embed.add_field(name="Roles:", value=b)

    await ctx.send(embed=embed)

You should simply use if to check value before you add to list - and then you don't need remove

mention = []

for role in user.roles:
    if role.mention != "@everyone":
        mention.append(role.mention)

The same as list comprehension

mention = [role.mention for role in user.roles if role.mention != "@everyone"]

BTW: if you want to remove something then do it only once after for-loop and also use if to check if element exists

mention = []

for role in user.roles:
    mention.append(role.mention)


if "@everyone" in mention:
    mention.remove("@everyone")

Try:

roles = ""
for role in user.roles:
    if role.id == ctx.guild.id:
      continue
    roles += f" <@&{role.id}>"

Then maybe print the roles or send the roles in a channel (an embed is adviced cause it doesn't ping anyone, and looks prettier)

Related