我正在尝试创建排行榜命令,但它不起作用。有没有人发现我的代码有问题,如果有,你能告诉我如何修复吗?
@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)
答案 0 :(得分:0)
您得到 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)