Discord.py投票统计异常:无法等待用户反应直接执行代码求助
问题解决:Discord机器人未等待用户投票就执行统计逻辑
问题根源
你的代码在发送带反应的消息后立刻查询统计反应数——此时只有机器人自己添加的两个初始反应,reaction.count - 1结果都是0,不会触发发送结果的判断逻辑;而且完全没给用户留投票时间,自然不会出现预期的结果消息。
解决方案
方案1:固定延迟等待用户投票(简单直接)
通过asyncio.sleep()让程序暂停一段时间,给用户留足投票时间后再统计结果,需先导入asyncio库。
修改后的完整代码:
import asyncio import discord @bot.event async def on_message(message): if 'aoe2' in message.content and message.channel.id == 1048127088688889866: BlueEmbed = discord.Embed(title='AOE Lobby', description='**Lobby Link:** ' + '<' + str(message.content) + '>', colour=discord.Colour.blue()) # 重命名变量避免覆盖原message对象 sent_message = await message.channel.send(embed=BlueEmbed) await sent_message.add_reaction('❤️') await sent_message.add_reaction('💙') # 等待30秒供用户投票(可按需调整时长) await asyncio.sleep(30) # 获取最新的消息反应数据 msg = await sent_message.channel.fetch_message(sent_message.id) highest_reaction = "" highest_reaction_count = 0 for reaction in msg.reactions: # 减去机器人自身的初始反应,计算用户实际投票数 user_votes = reaction.count - 1 if user_votes > highest_reaction_count: highest_reaction_count = user_votes highest_reaction = reaction.emoji # 有有效投票才发送结果,避免无意义提示 if highest_reaction_count > 0: await sent_message.channel.send(f"{highest_reaction} wins with {highest_reaction_count} votes!") else: await sent_message.channel.send("没有收到任何用户投票!")
方案2:等待用户交互后统计(更灵活)
使用bot.wait_for()监听用户的反应操作,既可以设置超时时间,也能自定义触发统计的条件(比如达到指定投票数)。
修改后的完整代码:
import asyncio import discord @bot.event async def on_message(message): if 'aoe2' in message.content and message.channel.id == 1048127088688889866: BlueEmbed = discord.Embed(title='AOE Lobby', description='**Lobby Link:** ' + '<' + str(message.content) + '>', colour=discord.Colour.blue()) sent_message = await message.channel.send(embed=BlueEmbed) await sent_message.add_reaction('❤️') await sent_message.add_reaction('💙') # 定义反应检查规则:只关注目标消息的反应,排除机器人自身 def check(reaction, user): return reaction.message.id == sent_message.id and not user.bot try: # 等待30秒,直到有用户添加反应(超时后自动执行统计) await bot.wait_for('reaction_add', timeout=30.0, check=check) except asyncio.TimeoutError: # 超时后统计最终投票结果 pass # 获取最新反应数据并统计 msg = await sent_message.channel.fetch_message(sent_message.id) highest_reaction = "" highest_reaction_count = 0 for reaction in msg.reactions: user_votes = reaction.count - 1 if user_votes > highest_reaction_count: highest_reaction_count = user_votes highest_reaction = reaction.emoji if highest_reaction_count > 0: await sent_message.channel.send(f"{highest_reaction} wins with {highest_reaction_count} votes!") else: await sent_message.channel.send("投票时间结束,无有效投票!")
关键修改说明
- 变量重命名:将
message改为sent_message,避免覆盖原消息对象导致逻辑出错 - 添加等待逻辑:两种方案都给用户留了投票时间,解决了"立刻统计"的核心问题
- 有效投票计算:通过
reaction.count - 1排除机器人自身的初始反应,统计真实用户投票数 - 结果判断:增加无投票时的提示,避免程序静默无输出
内容的提问来源于stack exchange,提问作者Josh Fsune
相关产品推荐
相关产品推荐

