Home > Back-end >  How to get discord bot to send an embed of an order numbered json? (Discord.py)
How to get discord bot to send an embed of an order numbered json? (Discord.py)

Time:12-07

So I am trying to create a leaderboard command with discord.py to get all the json values and make it order it from the values with the highest number to the lowest number and only the top ten.

Here is what I tried

@client.command()
@commands.has_role("Draft manager" or "Draft Manager")
async def leaderboard(ctx):
    winss = await get_win_data()

    leaderboard = winss["Wins"]

    balemb = discord.Embed(title=f"Draft's Leaderboard", colour=discord.Colour.blue())
    balemb.add_field(name="Win board", value=f"{leaderboard}")
    

I was unable to figure out the ordering part(The command didn't work regardless). Here are my functions

get win data

async def get_win_data():
    with open("leaderboard.json", "r") as f:
        users = json.load(f)

    return users

open wins

async def open_wins(user):
    users = await get_win_data()

    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["Wins"] = 0
    
    with open("leaderboard.json", "w") as f:
        json.dump(users, f, indent=4)
    return True 


Update wins

async def update_wins(user,change = 0,mode = "Wins"):
    users = await get_win_data()

    users[str(user.id)][mode]  = change 

    with open("leaderboard.json", "w") as f:
        json.dump(users, f, indent=4)

    bal = [users[str(user.id)]["Wins"]]
    return bal

Here is my json file

{
    "325837218222440460": {
        "Wins": 3
    },
    "828366691049406484": {
        "Wins": 0
    }
}

Sorry for it being so lengthy but I had to include every function so you are aware of what they do and if I need to change those as well. The main thing though is I need the leaderboard command to send an embed of the highest wins with the id's matching their wins. Thank you ahead of time and if you have any other tips or questions I will gladly accept them :)

CodePudding user response:

@client.command()
@commands.has_role("Draft manager" or "Draft Manager")
async def leaderboard(ctx):
    embed = discord.Embed(title=f"Draft's Leaderboard", colour=discord.Colour.blue())
    embed.add_field(name="Win board", value=f"\n".join([f"{ctx.guild.get_member(member[0])}: {member[1]} wins" for member in sorted((await get_win_data()).items(), key=lambda x: x[1]['Wins'], reverse=True)]))
    await ctx.send(embed=embed)

  • Related