不和谐等级命令

时间:2021-03-25 17:10:06

标签: python discord.py system rank

我尝试了几次将玩家的排名(如果他是 xp 最多的用户,或者广告排名第二的用户,依此类推),但我只是想列出我从中获得的经验从最高到最低。 有人可以帮助我如何获得玩家的排名吗?

    @commands.command(aliases = ["rank","lvl"])
    async def level(self, ctx, member: discord.Member = None):
        async with ctx.typing():
            user = ctx.message.author
            with open("level.json","r") as f:
                users = json.load(f)
            lvl = users[str(ctx.guild.id)][str(user.id)]["level"]
            exp = users[str(ctx.guild.id)][str(user.id)]["experience"]


            rankcard = Image.open("Zumtest.png")

            url = requests.get(user.avatar_url)
            avatar = Image.open(BytesIO(url.content))
            avatar = avatar.resize((177, 177));
            avatar.convert('RGBA')
            bigsize = (avatar.size[0] * 3, avatar.size[1] * 3)
            mask = Image.new("L", bigsize, 0)
            draw = ImageDraw.Draw(mask)
            draw.ellipse((0, 0) + bigsize, fill=255)
            mask = mask.resize(avatar.size, Image.ANTIALIAS)
            avatar.putalpha(mask)

            rankcard.paste(avatar, (100,40), avatar)

            lvltext = "Level {}".format(lvl)
            exptext = f"{exp} XP"


            draw = ImageDraw.Draw(rankcard)
            font = ImageFont.truetype("arial.ttf", 30)

            draw.text((255,60), lvltext, (0, 0, 0,), font=font)


            draw = ImageDraw.Draw(rankcard)

            draw.text((255,117), exptext, (0, 0, 0,), font=font)



        rankcard.save("profile.png")

        await ctx.send(file = discord.File("profile.png"))

那是 level.json

{"719479402953572383": {"504641949068689430": {"experience": 4, "level": 1}}}

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以简单地使用 sorted 来获取排序,然后使用 enumerate 对其进行编号:

users = users[ctx.guild.id] 

ranking = {key: rank for rank, key in enumerate(sorted(users, key=users.get, reverse=True), 1)}

user_rank = ranking[member.id]

这不考虑关系。你可以用它来代替得分。如果您希望所有绑定的键都具有相同的等级。我们有:

r = {key: rank for rank, key in enumerate(sorted(set(users.values()), reverse=True), 1)}
ranking = {k: r[v] for k,v in users.items()}

答案 1 :(得分:0)

            users = users[str(ctx.guild.id)]

            r = {key: rank for rank, key in enumerate(sorted(set(users.values()), reverse=True), 1)}
            ranking = {k: r[v] for k,v in users.items()}


            user_rank = ranking[member.id]

我稍微修改了一下代码

Ignoring exception in command level:
Traceback (most recent call last):
  File "C:\Users\Lasse\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Lasse\Documents\Discord Bots\MyBot\cogs\LevelSystem.py", line 63, in level
    r = {key: rank for rank, key in enumerate(sorted(set(users.values()), reverse=True), 1)}
TypeError: unhashable type: 'dict'

但知道我不知道如何解决这个错误