如何在 discord.py 中获取角色 ID

How to get role id in discord.py

我正在创建一个 createrole 命令,我想显示一些关于角色的信息,例如名称、颜色和 ID,但我是如何获得角色 ID 的?我尝试查看此网站、Reddit 和 API 参考资料,但找不到答案。

这是我现在拥有的:

@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)

快速修复:

现在您正在将字符串 'content' 传递给 get 函数,而不是名称为 content 的变量。尝试替换以下行: role = get(ctx.guild.roles, name='content')

有了这个:

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

更高效且更不容易出错的方法:

await guild.create_role returns 创建的角色对象,这意味着您不需要按名称重新获取它,只需这样做即可:

@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)