Alpha
Alpha

Reputation: 329

How could i get the name of a role in discord.py

I created an add role command. It works fine but my problem is that it works only with the id of the role. I was wondering how could I somehow convert the id of the role to the name of the role. This is the code.

    @commands.has_permissions(manage_messages=True)
    async def addrole(self, ctx, member: discord.Member,rolename):
        if member is None:
            member=ctx.author
        role = discord.utils.get(ctx.guild.roles, id=rolename)
        await member.add_roles(role)
        await ctx.send(f"{member.mention}was added {rolename}")

Any help is appreciated.edit

solution

I made use of the 2 comments and created this command which works perfectly.

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def addrole(self, ctx, role: discord.Role, member: discord.Member=None):
        if member is None:
            member=ctx.author
        await member.add_roles(role)
        await ctx.send(f"{member.mention} was added {role}")```

Upvotes: 1

Views: 360

Answers (2)

Nurqm
Nurqm

Reputation: 4743

You can use role converter just like you used member converter. You can pass role: discord.Role in arguments. Then, you just have to mention the role.

Also, you have to assign a default value None to the member argument in order to check if it's None.

@commands.has_permissions(manage_messages=True)
async def addrole(self, ctx, role: discord.Role, member: discord.Member=None):
    if not member:
        member=ctx.author
    await member.add_roles(role)
    await ctx.send(f"{member.mention}was added {role.name}")

References

Upvotes: 1

Lukas Thaler
Lukas Thaler

Reputation: 2720

You could declare your rolename variable as a discord.Role and make use of the implicit role converter that will be applied, just like what happens to your member object. Your function would look something like this:

@commands.has_permissions(manage_messages=True)
async def addrole(self, ctx, member: discord.Member, role: discord.Role):
    await member.add_roles(role)
    await ctx.send(f"{member.mention} was added {rolename}")

Upvotes: 1

Related Questions