Discord.py 如何在 mongoDB 排行榜命令中获取用户名?

Discord.py how do I get a username in a mongoDB leaderboard command?

所以我用 MongoDB 创建了一个 Discord.py 排行榜命令,一切正常,但我无法发送用户名。

数据是这样存储的:

_id: 484363190168322049 #users id
experience: 964
level: 5

Python代码:

@client.command(aliases = ["et", "leaderboard"])
async def lb(ctx, arg=10):
    rankings = collection.find().sort("experience",-1)
    i=1
    embed = discord.Embed(title = f"***Top {arg} users***")
    for x in rankings:
        print(x["_id"])
        user = client.get_user(x["_id"])
        user_xp = x["experience"]
        ##########################################################################
        # This is where I want to add the user username instead of <@{x['_id']}> #
        ##########################################################################
        embed.add_field(name=f"{i}: <@{x['_id']}>", value=f"XP │ {user_xp}", inline=False)
        if i == arg:
            break
        else:
            i += 1
    embed.set_footer(text=f"{ctx.guild}", icon_url=f"{ctx.guild.icon_url}")
    embed.timestamp = datetime.datetime.utcnow()
    await ctx.send(embed=embed)

这提到了用户,但我不想那样,我只想要用户的用户名, 我试过:

user = client.get_user(x["_id"])
embed.add_field(name=f"{i}: {user.name}>", value=f"XP │ {user_xp}", inline=False)

以前这对我的其他命令有效,但 returns:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'

你的问题是机器人没有获取用户(NoneType 错误)。尝试这样做:

user1 = int(x["_id"])
user = client.get_user(user1) 
embed.add_field(name=f"{i}: {user.name}>", value=f"XP │ {user_xp}", inline=False)

或者检查数据库,错误可能是上面的,也可能是数据库find()错误。