如何让Discord.py Trivia机器人同时添加消息反应?
Discord.py 琐事游戏机器人:并发添加消息反应的解决方案
我开发了一个基于discord.py的琐事(Trivia)游戏机器人,当前机器人会逐个按顺序添加消息反应,要是用户在所有反应加载完成前进行操作,会导致反应追踪失效。我看到其他机器人能无延迟一次性添加所有反应,请问该怎么实现?
我尝试用asyncio.gather()方法并发添加反应,替换了原来逐个添加数字按键表情、单独添加旗帜表情的代码,具体代码片段如下:
question_message = await ctx.send(embed=embed) # 延迟添加问题嵌入的反应 await asyncio.sleep(5) # 创建要添加的表情列表 emojis = [f"{i+1}\N{combining enclosing keycap}" for i in range(len(answers))] + ["\N{CHEQUERED FLAG}"] # 使用asyncio.gather并发添加所有反应 await asyncio.gather(*(question_message.add_reaction(emoji) for emoji in emojis)) reacted_users = {} # 存储已反应用户的字典 # 调整后的check_reaction函数 def check_reaction(reaction, user): if user == bot.user: return False if reaction.message.id != question_message.id: return False if reaction.emoji == "\N{CHEQUERED FLAG}": # 忽略旗帜表情的反应 return False if user.id in reacted_users: return False # 检查锦标赛模式 if mode == "tourney" and user.id not in participants: return False reacted_users[user.id] = True # 标记用户已反应 # 检查当前频道的游戏是否仍在进行 return ctx.channel.id in trivia_manager.active_games def check_message(message): if mode == "tourney" and message.author.id not in trivia_manager.active_game_users[ctx.channel.id]: return False # 检查当前频道的游戏是否仍在进行 return message.author == ctx.author and message.content.lower() == "skip" and ctx.channel.id in trivia_manager.active_games timeout_duration = reaction_timeout
原替换前代码
reaction_tasks = [question_message.add_reaction(f"{i+1}\N{combining enclosing keycap}") for i in range(len(answers))] await gather(*reaction_tasks) await question_message.add_reaction("\N{CHEQUERED FLAG}") # 添加旗帜表情
替换后代码
# 创建要添加的表情列表 emojis = [f"{i+1}\N{combining enclosing keycap}" for i in range(len(answers))] + ["\N{CHEQUERED FLAG}"] # 使用asyncio.gather并发添加所有反应 await asyncio.gather(*(question_message.add_reaction(emoji) for emoji in emojis))
内容的提问来源于stack exchange,提问作者jQuery-Student1989
相关产品推荐
相关产品推荐

