python - 只有当我的机器人特别提到某人时,如何让我的机器人回复某人?
问题描述
我想创建一个机器人来响应特别提到/标记@someone 的消息。例如:如果@Person1 在消息中提到/标记@Me,那么机器人应该用表情符号做出反应。但是,如果@Person1 在消息中提及/标记任何其他@People,则不会发生任何事情。这是我尝试过的:
import discord
import os
emoji = '\N{THUMBS UP SIGN}'
client = discord.Client()
@client.event
async def on_ready():
print('{0.user} is now active!'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('@<@666372975062417459>'): #that's my discord id
await message.add_reaction(emoji) #add emoji to message
client.run(os.environ['TOKEN'])
解决方案
message
您收到的第一个参数是on_message
一个消息对象。它有一个提及属性(来自文档)属性,其中包含提及的用户或成员列表。所以你可以使用:
if <user id> in [user.id for user in message.mentions]:
await message.add_reaction(emoji)
替换<user id>
为适当的用户 ID。[user.id for user in message.mentions]
将用户对象列表转换为用户 ID 列表。这种方法称为列表推导。然后 if 语句检查<user id>
生成的用户 ID 列表中是否存在。
要检查是否没有提到其他人,请使用:
if len(message.mentions) == 1 and <user id> in [user.id for user in message.mentions]:
await message.add_reaction(emoji)
这里第一个条件检查只提到了一个人,第二个条件检查提到的用户是必需用户。
推荐阅读
- google-cloud-platform - 我们如何在 Big-query 中执行 SQL 脚本
- python-3.x - 外部 Python 文件中的多个蜘蛛 - 如何随后运行
- symfony - 为什么执行 $form->setValues($data); 时 $form 爬虫不改变
- css - readthedocs + mkdocs 错误渲染代码块
- python - 如果另一个数据帧中的 NaN 是 NaN,如何用 NaN 覆盖数据帧中的值(相同大小)
- javascript - JSON 对象未正确转换为 javascript,JSON 作为从 php 到 AJAX 的回调发送
- python-2.7 - Selenium 清除输入字段的不同行为
- angular - Angular 9 通用和延迟加载的路由
- php - 如何从 Swift JSONEncoder 向 PHP 文件发送 POST 请求
- javascript - Reactjs - setState 在 fetch 中的更好解决方案