Reputation: 23
I have been trying to write a Discord bot with my friends and I’m trying to make a leaderboard command. I have been trying to fix the command and refilling the numbers, but nothing has worked.
Upvotes: 2
Views: 3636
Reputation: 3924
You don't want to sort dict.items()
because then you'll be stuck finding the keys. You can use a class definition.
class LeaderBoardPosition:
def __init__(self, user, coins):
self.user = user
self.coins = coins
and use a simple sorting function (this assuming your data is stored in "coins"):
leaderboards = []
for key, value in coins.items():
leaderboards.append(LeaderBoardPosition(key, value))
top = sorted(leaderboards, key=lambda x: x.coins, reverse=True)
Now you have a list, named top
with the data. Here is a simple leaderboard function.
await message.channel.send(f'**<< 1 >>** <@{top[0].user}> with {top[0].coins} coins')
try:
await message.channel.send(f'**<< 2 >>** <@{top[1].user}> with {top[1].coins} coins')
try:
await message.channel.send(f'**<< 3 >>** <@{top[2].user}> with {top[2].coins} coins')
except IndexError:
await message.channel.send('There is no 3rd place yet.')
except IndexError:
await message.channel.send('There is no 2nd place yet.')
Upvotes: 2