【问题标题】:Discord.py how do I get a username in a mongoDB leaderboard command?Discord.py 如何在 mongoDB 排行榜命令中获取用户名?
【发布时间】:2021-07-03 13:40:09
【问题描述】:

所以我用 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)

以前这与我的其他命令一起使用,但它返回:

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

【问题讨论】:

    标签: python mongodb discord.py leaderboard pymongo-3.x


    【解决方案1】:

    您的问题是机器人没有获取用户(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()错误。

    【讨论】:

    • 它可以很好地打印出所有的 ID,但仍然给出相同的错误
    • 尝试打印(用户)
    • 如果不起作用,请尝试 client.fetch_user() 而不是 get_user()
    • 感谢 client.fetch_user() 为我工作!
    • 错误可能是用户没有进入带有机器人的服务器,在这种情况下 fetch_user 很有用。很高兴为您提供帮助!
    猜你喜欢
    • 2021-09-14
    • 2020-09-10
    • 2021-04-20
    • 2021-10-07
    • 2021-05-29
    • 1970-01-01
    • 2021-03-12
    • 2020-09-11
    • 2020-12-25
    相关资源
    最近更新 更多