简体   繁体   English

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

[英]How to make a leaderboard command on discord.py using python?

I have been trying to write a Discord bot with my friends and I'm trying to make a leaderboard command.我一直在尝试与我的朋友一起编写 Discord 机器人,并且我正在尝试制作排行榜命令。 I have been trying to fix the command and refilling the numbers, but nothing has worked.我一直在尝试修复命令并重新填充数字,但没有任何效果。

You don't want to sort dict.items() because then you'll be stuck finding the keys.您不想对dict.items()进行排序,因为那样您将无法找到密钥。 You can use a class definition.您可以使用 class 定义。

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"):并使用简单的排序 function (假设您的数据存储在“硬币”中):

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.现在你有一个列表,命名为top的数据。 Here is a simple leaderboard function.这是一个简单的排行榜 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.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM