如何使用python在discord.py上制作排行榜命令?

时间:2020-05-23 17:18:53

标签: python python-3.x sorting discord discord.py

我一直在尝试和我的朋友们一起写一个Discord机器人,并且试图做出一个排行榜命令。我一直在尝试修复命令并重新填充数字,但是没有任何效果。

1 个答案:

答案 0 :(得分:2)

您不想对dict.items()进行排序,因为那样一来您就很难找到密钥。您可以使用类定义。

class LeaderBoardPosition:

    def __init__(self, user, coins):
        self.user = user
        self.coins = coins

并使用简单的排序功能(假设您的数据存储在“硬币”中):

leaderboards = []
for key, value in coins.items():
    leaderboards.append(LeaderBoardPosition(key, value))

top = sorted(leaderboards, key=lambda x: x.coins, reverse=True)

现在您有了一个名为top的数据列表。这是一个简单的排行榜功能。

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.')