【问题标题】:How do I make a leaderboard command? Discord.py如何制作排行榜命令?不和谐.py
【发布时间】:2022-01-26 03:39:25
【问题描述】:

这是我为每个成员配置级别并将信息存储在 JSON 文件中的事件。我想要一个列出最高级别的前 10 名的排行榜,但我不确定如何去做。提前致谢。

class on_message(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


    @commands.Cog.listener()
    async def on_message(self, message):
        channel = self.bot.get_channel(config.server_chat)
        with open("users.json", "r") as f:
            users = json.load(f)
            await update_data(users, message.author)
            await add_experience(users, message.author, 1)
            await level_up(users, message.author, message, channel)
            with open("users.json", "w") as f:
                json.dump(users, f)


async def update_data(users, user):
    if not str(user.id) in users:
        users[str(user.id)] = {}
        users[str(user.id)]["experience"] = 0
        users[str(user.id)]["level"] = 1
        users[str(user.id)]["messages"] = 0


async def add_experience(users, user, exp):
    users[str(user.id)]["experience"] += exp
    users[str(user.id)]["messages"] += exp


async def level_up(users, user, message, channel):
    experience = users[str(user.id)]["experience"]
    lvl_start = users[str(user.id)]["level"]
    lvl_end = int(lvl_start * 5)
    update = lvl_start + 1
    if experience >= lvl_end:
        users[str(user.id)]["experience"] = 0
        users[str(user.id)]["level"] = lvl_start + 1
        if not message.author.bot:
            lvl = users[str(user.id)]["level"]
            await channel.send(f"**{user.mention} reached level {update}**")


def setup(bot):
    bot.add_cog(on_message(bot))

【问题讨论】:

    标签: python json discord discord.py


    【解决方案1】:

    您可以对 JSON 数据进行排序并获得前 10 个用户:

    @commands.command()
    async def leaderboard(self, ctx):
        with open("users.json", "w") as f:
            data = json.load(f)
        embed = discord.Embed(title="Leaderboard")
        for user_id, user_data in sorted(data.items(), key=lambda x: x[1]['experience'], reverse=True)[:10]:
            embed.add_field(name=self.bot.get_user(user_id), value=f"Experience: {user_data['experience']}\nLevel: {user_data['level']}", inline=False)
        await ctx.send(embed=embed)
    

    【讨论】:

    • 谢谢,这很有帮助。你知道为什么 (name=self.bot.get_user(user_id) 显示为 None 吗?
    • @FU510N 如果机器人无法访问(查看)具有给定 ID 的用户,Tgis 函数将返回 None
    猜你喜欢
    • 2021-09-05
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2019-01-29
    • 2020-11-22
    相关资源
    最近更新 更多