如何获得用户角色discord.py

时间:2020-05-23 19:35:21

标签: python discord discord.py-rewrite

我正在尝试执行信息命令,如您所见,但是在角色部分中,我无法显示用户的角色。 最初,我执行了一个有效的命令,但是它也显示了“ @everyone”角色,因此我做了一个字符串来删除它(mention.remove("everyone")),但是它不起作用,它给出了此错误:

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

我也尝试用“ @everyone”替换“ everyone”,但仍然无法正常工作。

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

2 个答案:

答案 0 :(得分:0)

您应该简单地使用if来检查值,然后再添加到列表中-这样就不需要remove

mention = []

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

与列表理解相同

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

顺便说一句::如果您要删除某些内容,请仅在for循环后再执行一次,并使用if检查元素是否存在

mention = []

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


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

答案 1 :(得分:0)

您可以只使用if语句来检查角色的名称是否为@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)