python - 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()
解决方案
问题很可能在于您的“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}')
推荐阅读
- angular - 角 9 SSR | 无法访问 ads.txt 文件
- postgresql - 如何在 PostgreSQL 中通过 cmd 使用 pg_restore 命令恢复 .bak 文件?
- unity3d - 为子像素阴影映射编码几何信息
- python - 如何处理 Python Selenium 中的“消息:过时的元素引用:元素未附加到页面文档”
- javascript - Javascript - 为存储在用户计算机上的静态网页读取/写入设置的推荐/安全方式是什么?
- html - 为什么叠加的图片和标志+文字不起作用?
- ruby-on-rails - 与乘客一起在生产中使用 resque 时,没有路线匹配 [GET] "/resque/overview"
- c++ - 在字符串中查找模式
- google-apps-script - Google-App-Scripts-Search files 找不到电子表格
- highcharts - Highchart甘特图删除Y轴标签