discord.py获取消息反应时event_message.reactions返回空列表如何解决
问题原因
- 代码中使用的
event_message是消息发送完成时返回的本地缓存对象,属性不会随Discord服务端的状态变化自动更新,等待4秒后直接访问reactions属性仍为消息刚发送时的初始状态,因此无法读取到用户后续添加的反应。 - 未正确开启Discord机器人的相关权限意图,导致无法获取反应相关的事件和数据。
- 现有代码存在两处隐性问题:
client.fetch_user是异步方法,直接同步调用会抛出异常,无法正常生成结果Embed;修改用户金币数据后没有写回stats.json文件,修改不会生效。
解决方案
- 等待结束后重新从服务端拉取最新的消息对象,获取最新的反应数据
- 开启机器人的相关权限意图:
- 进入Discord开发者后台的机器人设置页,开启
Server Members Intent和Guild Message Reactions Intent - 代码初始化客户端时开启对应意图:
intents = discord.Intents.default() intents.reactions = True intents.members = True # 用commands.Bot的话参数逻辑一致 client = discord.Client(intents=intents) - 进入Discord开发者后台的机器人设置页,开启
- 修复异步方法调用错误,同时排除机器人自身的反应避免误统计,新增json文件写入逻辑。
修改后的完整代码
async def make_event(ctx): with open('stats.json', "r") as f: users = json.load(f) event_embed = discord.Embed(title="AN EVENT IS HAPPENING!", description="React to the message to gain some coins!", color=discord.Colour.red()) event_message = await ctx.send(embed=event_embed) await event_message.add_reaction("💵") await asyncio.sleep(4) # 重新拉取最新消息对象,同步服务端的反应数据 event_message = await ctx.channel.fetch_message(event_message.id) reactors = [] for reaction in event_message.reactions: reactorsForThatReaction = await reaction.users().flatten() for user in reactorsForThatReaction: # 排除机器人自身的反应 if not user.bot and str(user.id) not in reactors: reactors.append(str(user.id)) resultEmbed = discord.Embed(title="Event results", description="The following users won coins:") for user_id in reactors: gain = random.randint(5000, 100000) users[user_id]["cash"] += gain formattedGain = "{:,}".format(gain) # 正确await异步方法获取用户信息 user = await client.fetch_user(int(user_id)) resultEmbed.add_field(name=user.name, value=f"{formattedGain} cash.") # 写入修改后的用户数据到json文件 with open('stats.json', "w") as f: json.dump(users, f) await ctx.send(embed=resultEmbed)
内容的提问来源于stack exchange,提问作者Alan duan
相关产品推荐
相关产品推荐

