peppewarrior1
peppewarrior1

Reputation: 55

leaderboard command with mysql discord.py

I am trying to make a leaderboard using mysql but I have no idea how to actually do it. I searched everywhere but unfortunately I found nothing. The only thing I did was a sort query however I don't know how to show it on python. Advice?

@client.command()
async def leaderboard(ctx):
    cursor = levelsystem_db.cursor()
    cursor.execute("SELECT users.user_level, users.user_xp, users.client_id\nFROM users\nORDER BY users.user_level DESC , users.user_xp DESC")
    leaderboard = cursor.fetchall()
    await ctx.send(leaderboard)
[(13, 17500, 356536794646446080), (10, 10255, 488826524791734275), (10, 10160, 523967502665908227), (7, 2500, 572852913664163881), (6, 1000, 640479176280899584), (5, 500, 702691407034318920)]

Upvotes: 1

Views: 477

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

I'm assuming the format is the next one

(level, xp, member_id)

It's pretty simple, you can simply use a for loop

for i, pos in enumerate(leaderboard, start=1):
    lvl, xp, member_id = pos
    print(f"{i}. {member_id}, level: {lvl}, XP: {xp}")

# Result
# 1. 356536794646446080, level: 13, XP: 17500
# 2. 488826524791734275, level: 10, XP: 10255
# 3. 523967502665908227, level: 10, XP: 10160
# 4. 572852913664163881, level: 7, XP: 2500
# 5. 640479176280899584, level: 6, XP: 1000
# 6. 702691407034318920, level: 5, XP: 500

You can put this in an embed, a message... That depends on your creativity really.

To convert an ID to a discord.Member instance

# First you need a `discord.Guild` instance (you can either use `ctx.guild` or `bot.get_guild`
guild = ctx.guild

# Getting the instance
member = guild.get_member(member_id)

Reference:

Upvotes: 2

Related Questions