如何修改discord.py命令以支持多用户提交正确答案
实现discord.py机器人接收多用户正确答案并按名次反馈
修改思路
- 替换单次
wait_for为循环监听,持续接收正确答案 - 用集合记录已答对用户,避免同一用户重复上榜
- 保留超时逻辑,到时间后停止接收并结束游戏
- 每次收到正确答案时,按顺序播报用户名次
修改后完整代码
import asyncio import discord from discord.ext import commands bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @bot.command() async def rev(ctx): target_str = "liechtenstein" # 示例字符串 correct_answer = target_str[::-1] await ctx.send(f"请反转以下字符串:{target_str}") # 记录已答对的用户,避免重复上榜 answered_users = set() rank = 1 timeout = 7 # 超时时间(秒) def check(msg: discord.Message) -> bool: # 验证答案正确、在同一频道、且用户未答对过 return (msg.content == correct_answer and msg.channel == ctx.message.channel and msg.author not in answered_users) try: while True: # 循环等待正确消息,超时则退出循环 guess = await bot.wait_for('message', timeout=timeout, check=check) # 标记用户已答对 answered_users.add(guess.author) # 播报名次 await ctx.send(f"第{rank}名 恭喜{guess.author.mention}!") rank += 1 except asyncio.TimeoutError: await ctx.send(f"时间到!本次共有{len(answered_users)}位用户答对。") # 替换为你的机器人Token bot.run("YOUR_BOT_TOKEN")
关键改动说明
- 新增
answered_users集合:存储已经提交正确答案的用户,确保同一用户不会重复获得名次 - 改用
while True循环:持续监听符合条件的消息,直到超时触发TimeoutError - 名次变量
rank:每次答对后递增,实现按顺序播报第1、第2名等 - 检查逻辑升级:在原有的答案和频道验证基础上,增加了用户未答对过的判断
内容的提问来源于stack exchange,提问作者jean
相关产品推荐
相关产品推荐

