【问题标题】:How to make a leaderboard command on discord.py using python?如何使用 python 在 discord.py 上制作排行榜命令?
【发布时间】:2020-09-10 12:33:58
【问题描述】:

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

【问题讨论】:

  • 您的硬币数据是如何存储的?是字典吗?
  • 是的,它是一本字典
  • 请出示您的代码

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


【解决方案1】:

您不想对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.')

【讨论】:

  • 在第二个代码中进行列表和排序,你能解释一下吗?
  • 所以基本上我创建了一个类,这样更容易存储用户标识符和硬币值,因此我可以按属性(x.coins)对它们进行排序,并且对象仍然具有用户 ID,所以然后可以在消息发送部分用&lt;@123456&gt; 提及它们
猜你喜欢
  • 2021-09-14
  • 2021-04-20
  • 2021-07-03
  • 2022-01-26
  • 2011-05-15
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
相关资源
最近更新 更多