你如何从 bot.wait_for('reaction_add') 获得 2 个用户?

时间:2021-07-14 21:14:50

标签: python discord.py

所以我有这个代码:

        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 已准备好的消息。我尝试了多种方法,例如循环,但似乎都不起作用。亲切的问候。

1 个答案:

答案 0 :(得分:0)

我假设您希望 initiatorchallenger 以特定顺序对您的消息做出反应。

首先,如果您没有相应地处理 timeout,则添加 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")

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