【问题标题】:Leaderboard Command with Discordpy and MongoDBDiscordpy 和 MongoDB 的排行榜命令
【发布时间】:2021-05-29 00:27:43
【问题描述】:

我正在尝试创建排行榜命令,但它不起作用。有人发现我的代码有什么问题吗,如果有,你能告诉我如何解决吗?

    @challenge.command(aliases=['leaderboard'])
    async def lb(self, ctx):
        lb_data = main_db['challenges'].find().sort("total_points", -1)
        embed = discord.Embed(title='**Challenge Leaderboard**',
                            description='''description msg''', color=discord.Colour.red())
        for i, x in enumerate(lb_data, 1):
            embed.add_field(name=f"#{i}", value=f"<@{str(x['id'])}> has {str(x['total_points'])}",
                            inline=False)
        await ctx.send(embed=embed)

【问题讨论】:

  • 它不起作用怎么办?你有错误吗?
  • 我收到错误 discord.ext.commands.errors.CommandInvokeError: Command raise an exception: KeyError: 'total_points' 这让我很困惑,因为我知道它存在并在其他命令中引用了它。
  • 你从main_db['challenges'].find()得到什么?
  • 文档是否有可能没有total_points字段?

标签: mongodb discord discord.py


【解决方案1】:

您会得到一个KeyError,因为其中有一个没有total_points 字段的文档。

您可以事先进行检查以避免此错误。它可能看起来像这样:

for i, x in enumerate(lb_data, 1):
    if 'total_points' in x:
        total_points = str(x['total_points'])
    else:
        total_points = "0"
    embed.add_field(name=f"#{i}", value=f"<@{str(x['id'])}> has {total_points}", inline=False)

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2020-11-21
    • 2021-04-20
    • 2021-03-20
    • 2021-07-03
    • 2022-01-26
    • 2021-09-14
    • 2021-07-05
    • 2021-10-14
    相关资源
    最近更新 更多