如何在Discord.py Rewrite中使用JSON操作显示排行榜?

时间:2020-07-23 07:47:03

标签: python discord.py

如何在Discord.py Rewrite中使用JSON操作显示排行榜?

货币是赞美的,我将它们存储在JSON文件中。 关于如何表现出最高荣誉的前十名排行榜的任何想法?我是一个初学者,但是我很容易掌握JSON操作的窍门。这是我的代码。

python @bot.command(pass_context=True)
async def balance(ctx):
    id = str(ctx.message.author.id)
    if id in amounts:
        await ctx.send("You have {} accolades.".format(amounts[id]))
    else:
        await ctx.send("You do not have an account.")

@bot.command(pass_context=True)
async def register(ctx):
    id = str(ctx.message.author.id)
    if id not in amounts:
        amounts[id] = 0
        await ctx.send("You are now registered to AccoladeBot.")
        _save()
    else:
        await ctx.send("You already have an account.")


@commands.has_
@bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
    primary_id = str(ctx.message.author.id)
    other_id = str(other.id)
    if primary_id not in amounts:
        await ctx.send("You do not have an account.")
    elif other_id not in amounts:
        await ctx.send("The other party does not have an account.")
    else:
        amounts[other_id] += amount
        await ctx.send("Transaction complete.")
    _save()

def _save():
    with open('amounts.json', 'w+') as f:
        json.dump(amounts, f)

2 个答案:

答案 0 :(得分:0)

我假设您的json文件是这样的。

{
  "ID_HERE": AMOUNT_HERE
}

因此,您可以使用某些东西。

@bot.command()
async def leadeboard(ctx):

    with open('amounts.json', 'r') as f:
        data = json.load(f)

    top_users = {k: v for k, v in sorted(data.items(), key=lambda item: item[1], 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)

Sample

答案 1 :(得分:0)

您可以使用sorted()内置函数对json文件数据进行排序。
然后,要显示其在排行榜中的位置,您必须使用enumerate()内置函数。
最后,我用discord.Embed在不和谐的服务器上漂亮地显示了排行榜。

这是命令的外观:

@bot.command()
async def top10(ctx):
    embed = discord.Embed(title="Top 10 server's leaderboard:", color=discord.Colour.gold())
    with open('amounts.json', 'r') as file:
        data = json.load(file)
    sorted_data = {id: bal for id, bal in sorted(data.items(), reverse=True ,key=lambda item: item[1])}

    for pos, (id, bal) in enumerate(sorted_data.items()):
        member = ctx.guild.get_member(int(id))
        embed.add_field(name=f"{pos+1} - {member.display_name}", value=f"{bal} accolades", inline=False)
        if pos+1 > 9:
            break 
    await ctx.send(embed=embed)

注意:如果要提及用户,则提及的内容不应在字段名称中。标题,字段名称和页脚中未提及提及