首页 > 解决方案 > Discord.py:wait_for('reaction_add') 未按预期工作

问题描述

我正在尝试在 discord.py 上制作一个常见问题解答机器人,到目前为止进展顺利。我想添加一个额外功能,当机器人检测到常见问题解答时,机器人不会直接发送答案,而是会发送一条提示消息,其中包含两个反应——竖起大拇指和不喜欢——并取决于所选的反应由用户,机器人要么发送答案,要么删除提示消息。

现在,当询问常见问题解答时,机器人会检测到它并发送提示询问用户是否想要答案,甚至对其做出反应。问题是,一旦机器人完成对拇指向下表情符号的反应,提示消息就会被删除。我希望它等待用户做出反应并相应地继续。

我究竟做错了什么?请帮忙。提前致谢!

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    
    if (message.author.bot):
        return        

    if(isQuestion(message.content)):
        (answer_text, question_text) = answer_question(message.content)

        if answer_text:
            botmessage = await message.channel.send(f"""Do you want the answer to: {question_text} ?""")
            
            await botmessage.add_reaction('\N{THUMBS UP SIGN}')
            await botmessage.add_reaction('\N{THUMBS DOWN SIGN}')

            def checkUp(reaction, user):
                return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' or str(reaction.emoji) == '\N{THUMBS DOWN SIGN}'

            try:
                reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=checkUp)
            except asyncio.TimeoutError:
                await botmessage.delete()
            else:
                print(reaction.emoji)
                if reaction.emoji == '\N{THUMBS UP SIGN}':
                    await botmessage.delete()
                    await message.channel.send(answer_text)

                elif reaction.emoji == '\N{THUMBS DOWN SIGN}':
                    await botmessage.delete()

标签: pythonpython-3.xbotsdiscorddiscord.py

解决方案


问题很可能在于您的“checkUp”功能,因为您缺少括号。

user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' or str(reaction.emoji) == '\N{THUMBS DOWN SIGN}'

当遇到这样的布尔链时,我不确定python的默认行为,但它可能是这样放置括号的:

(user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}') or (str(reaction.emoji) == '\N{THUMBS DOWN SIGN}')

你看到问题了吗?现在,只要有人对消息做出反应,检查就会返回 True。这意味着它可以对自己之前的反应做出反应(尽管您之前可能已经执行过此操作,但我们在这里讨论的是异步)。

修复:这样放置括号:

user == message.author and (str(reaction.emoji) == '\N{THUMBS UP SIGN}' or str(reaction.emoji) == '\N{THUMBS DOWN SIGN}')

推荐阅读