kezz
kezz

Reputation: 107

How to get role id in discord.py

I was creating a createrole command and I wanted to show some info about the role, such as the name, color, and id, but how did I get the role id? I tried looking on this site, Reddit, and the API reference but I couldn't find an answer.

This is what I have now:

@bot.command(name='createrole')
async def createrole(ctx, *, content):
    guild = ctx.guild
    await guild.create_role(name=content)
    role = get(ctx.guild.roles, name='content')
    roleid = role.id
    description = f'''
    **Name:** <@{roleid}>
    **Created by:** {ctx.author.mention}
    '''
    embed = discord.Embed(name='New role created', description=description)
    await ctx.send(content=None, embed=embed)

Upvotes: 0

Views: 5196

Answers (1)

chluebi
chluebi

Reputation: 1829

Quick Fix:

Right now you are passing the string 'content' to your get function instead of the variable with the name content. Try replacing the following line: role = get(ctx.guild.roles, name='content')

with this:

role = get(ctx.guild.roles, name=content)

Much more efficient and less error prone way of doing it:

await guild.create_role returns the role object created, meaning you don't need to refetch it by name and can just do this:

@bot.command(name='createrole')
async def createrole(ctx, *, content):
    guild = ctx.guild
    role = await guild.create_role(name=content)  
    roleid = role.id
    description = f'''
    **Name:** <@{roleid}>
    **Created by:** {ctx.author.mention}
    '''
    embed = discord.Embed(name='New role created', description=description)
    await ctx.send(content=None, embed=embed)

Upvotes: 2

Related Questions