You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Discord机器人排行榜按计数从高到低排序?

问题:Discord机器人排行榜无法按计数降序排序

我在开发Discord机器人的leaderboard命令,希望将成员按计数从高到低排序,但始终无法实现。

现有排行榜代码

@bot.command()
@commands.cooldown(1, 20, commands.BucketType.user) 
async def leaderboard(ctx):
    embed = discord.Embed(
         title="Leadboard",
         description="Your Servers Count",
         color=0xFF000
        )
    with open('messages.json') as file:
         data = json.load(file)
    for key, value in data[f"{ctx.guild.name}"].items():
        try:
            embed.add_field(name = key, value = value)
            embed.set_footer(text="If you feel your message's are not being counted, please get the server owner to send me a dm!")
        except: return
    await ctx.respond(embed=embed)

当前输出

成员列表按JSON文件中的原始存储顺序展示,未按计数从高到低排序。

目标效果

成员按计数数值从高到低排列,计数最高的成员显示在最上方。

解决方案

问题核心是直接遍历JSON原始键值对未做排序处理,只需对服务器成员数据按计数降序排序后再遍历即可:

@bot.command()
@commands.cooldown(1, 20, commands.BucketType.user) 
async def leaderboard(ctx):
    embed = discord.Embed(
         title="排行榜",
         description="本服务器消息计数排行",
         color=0xFF0000  # 修正颜色值(原0xFF000少一位会报错)
        )
    guild_name = ctx.guild.name
    try:
        with open('messages.json') as file:
             data = json.load(file)
        # 按计数从高到低排序,x[1]取value值,reverse=True实现降序
        sorted_members = sorted(data[guild_name].items(), key=lambda x: x[1], reverse=True)
        for member_name, count in sorted_members:
            embed.add_field(name=member_name, value=count, inline=False)  # 让每个成员占一行,排版更清晰
        embed.set_footer(text="如果觉得你的消息计数有误,请联系服务器所有者私信我!")
        await ctx.respond(embed=embed)
    except KeyError:
        await ctx.respond("本服务器暂无消息计数数据!")
    except Exception as e:
        await ctx.respond(f"加载排行榜失败:{str(e)}")

关键修改点

  • 用sorted()函数对成员数据排序,指定按计数(value)降序排列
  • 修正颜色值格式错误,避免运行报错
  • 优化异常处理,针对不同情况给出明确反馈,避免静默失败
  • 将界面文本改为中文,适配中文使用场景
  • 新增inline=False让每个成员的排行信息单独占一行,提升可读性

内容的提问来源于stack exchange,提问作者superhackedmonkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:05:12