请帮我在discord.py中制作一个平衡排行榜
我从网上尝试了很多不同的方法,但都不起作用。数据库采用json格式{"id":{"balance":0}}制作。我不知道该怎么做。请帮忙。
我的最后一个代码:
def get_balance(id):
with open("wallets.json", "r", encoding="UTF-8") as file:
data = json.load(file)
return data.get("balance")
@bot.command(name="single")
async def single(ctx, user_mention=None):
with open("wallets.json", "r", encoding="UTF-8") as file:
data = json.load(file)
top_users = data.sort(data, key=get_balance, reverse=True)
names = ""
for postion, user in enumerate(top_users):
# add 1 to postion to make the index start from 1
names += (
f"{postion + 1} - <@!{user}> with {top_users[user]}\n"
)
embed = discord.Embed(title="Leaderboard")
embed.add_field(name="Names", value=names, inline=False)
await ctx.send(embed=embed)
你的代码非常接近,尽管
get_balance
没有做它应该做的事情(而且你不应该重新读取你已经为每个排序迭代读取的数据)。
尝试类似的事情
with open("wallets.json", "r", encoding="UTF-8") as file:
data = json.load(file)
leaderboard = sorted(
data.items(),
key=lambda pair: pair[1]["balance"],
reverse=True,
)
names = ""
for position, (user, user_info) in enumerate(leaderboard, 1):
balance = user_info["balance"]
names += f"{position} - <@!{user}> with {balance}\n"