排行榜命令与不和谐和MongoDB



我正在尝试制作一个排行榜命令,但它不起作用。有人看到任何错误与我的代码,如果是这样,你能告诉我如何修复它吗?

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

你得到一个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)

最新更新