首页 > 解决方案 > 你如何从 bot.wait_for('reaction_add') 获得 2 个用户?

问题描述

所以我有这个代码:

        msg = await channel.send("React to this with ✅ to ready up. ``(0/2)``")
        await msg.add_reaction('✅')

        def check(reaction, user):
            return reaction == '✅' and user.id == initiator or user.id == challenger

        reaction, user = await self.bot.wait_for('reaction_add', timeout=30, check=check)

        print(user)

当我打印用户时,我希望它不仅打印 1。因为当他们做出反应时,我想编辑 1 已经准备好的消息。我尝试了多种方法,例如循环,但似乎都没有。亲切的问候。

标签: pythondiscord.py

解决方案


我假设您想要两者initiatorchallenger以特定顺序对您的消息做出反应。

首先,timeout如果您没有相应地处理,则添加 a 是没有意义的TimeoutError

一个好的解决方案是将代码嵌入到无限循环中,并带有一个try:except子句来捕获超时错误并转义循环。

在您的情况下,您还应该定义某种标志来确定轮到谁做出反应:

@bot.command
async def my_command(ctx, challenger: discord.Member):
    initiator = ctx.author
    msg = await channel.send("React to this with ✅ to ready up. ``(0/2)``")
    await msg.add_reaction('✅')

    in_turn = initiator
    while True:
        try:
            reaction, user = await self.bot.wait_for('reaction_add', timeout=30, check=lambda r, u: r == "✅" and u == in_turn
            turn = 1 if in_turn == initiator else 2
            await msg.edit(f"React to this with ✅ to ready up. ``({turn}/2)``")
            if in_turn == initiator:
                in_turn = challenger
            else:
                break
        except asyncio.TimeoutError:
            await ctx.send(f"{in_turn.display_name} didn't react in time")

显然,这只是我对如何实现这一点的想法,但是你必须对这些反应做一些事情(你没有在你的问题中明确说明),否则整个任务是毫无意义的。


推荐阅读