python-3.xdiscorddiscord.pypycord

How do I fetch roles that user has? Discord python


I need to get a list of roles of the user that executes a slash command. I can't seem to find a working solution, that would work with ctx and not with the user.Member or anything else.

My cog code:

from discord.commands import slash_command
from discord.ext import commands


class Cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print("Cog connected.")

    @slash_command(guild_ids=[12345], name='test')
    async def test(self, ctx):
        roles = """ here goes some code that fetches roles of the user who executed this command """
        ctx.respond(f"Your roles are {roles}")

def setup(bot):
    bot.add_cog(Cog(bot))

I am using Pycord 2.4.1, but I guess discord.py solutions would also work in my case. Thank you.


Solution

  • You can easily do this by using for roles in member.roles. This declares a variable called "roles" and member.roles checks what roles the member has.

    Here is the code:

    for roles in member.roles:
        embed=discord.Embed(title="Roles"
                            description=f"Here are the roles of the following member: {member}"
                            color=discord.Color.red()) # choose any color you would like.
        embed.add_field(name="Roles:", value=roles, inline=False)
        await interaction.response.send_message(embed=embed)
    

    Remember to declare a member role:

    @bot.tree.command(name="roles")
    async def roles(interaction:discord.Interaction, member:discord.Member=None):
        if member == None:
            member=interaction.user
        for roles in member.roles:
            # rest of the code
    

    (Some of this code is based off of Rexy's code)

    PS (just a small note), you can use slash commands by using:

    @bot.slash_command(name="(command)", description="whatever you want this to be", guild_ids=["whatever guild you want, but ignore this argument if you want it for all guilds"])
    

    This will only work if you use these two imports:

    from discord.ext import commands
    from discord import default_permissions