如何在discord.py单次命令内实现临时积分排行榜功能
Discord.py 临时答题积分排行榜实现方案
需求说明
- 答题命令结束时展示所有获得积分用户的排行榜
- 积分无需持久化存储,每次启动新命令时所有用户积分自动重置为0
- 目标排行榜格式:
results david 6 points maria 3 points dharma 2 points mikey 1 point
完整实现代码
先修正原代码的拼写错误(wait_for事件名mesage改为message),再用字典实现积分存储与排行榜功能:
import discord import asyncio from discord.ext import commands bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @bot.command() async def quiz(ctx): # 初始化积分字典:键为用户对象(保证唯一性),值为积分 user_scores = {} # 示例正确答案集合,可根据实际需求修改 answer = ["apple", "banana", "cherry"] # 答题轮次数量,可自定义调整 total_rounds = 3 # 消息校验函数 def check(msg): return msg.content.lower() in answer and msg.channel == ctx.channel # 答题流程循环 for _ in range(total_rounds): try: await ctx.send("请输入你的答案!") guess = await bot.wait_for('message', timeout=6, check=check) # 更新用户积分:存在则+1,不存在则初始化为1 if guess.author in user_scores: user_scores[guess.author] += 1 else: user_scores[guess.author] = 1 await ctx.send(f"{guess.author.mention} 当前积分为 {user_scores[guess.author]} 分") except asyncio.TimeoutError: await ctx.send("时间到!本轮答题结束") break # 生成并发送排行榜 await ctx.send("### 排行榜结果") # 按积分降序排序,积分相同时按用户名升序排列 sorted_scores = sorted(user_scores.items(), key=lambda x: (-x[1], x[0].name)) result_content = ["results"] for user, score in sorted_scores: # 自动处理单复数:1分用point,大于1分用points point_label = "point" if score == 1 else "points" result_content.append(f"{user.name} {score} {point_label}") # 拼接成字符串发送 await ctx.send('\n'.join(result_content)) bot.run("你的Bot令牌")
核心实现逻辑
- 积分存储:每次启动
!quiz命令时,都会重新初始化user_scores字典,实现「每次命令重置积分」的需求 - 积分更新:用户答对题时,检查字典中是否已有该用户条目,有则积分+1,无则添加新条目并设为1
- 排行榜排序:通过
sorted()函数结合自定义排序规则,实现积分从高到低的排列,积分相同时按用户名排序保证结果稳定 - 格式适配:根据积分数值自动切换
point/points,完全匹配示例中的显示格式
内容的提问来源于stack exchange,提问作者jean
相关产品推荐
相关产品推荐

