首页 > 解决方案 > 只有当我的机器人特别提到某人时,如何让我的机器人回复某人?

问题描述

我想创建一个机器人来响应特别提到/标记@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'])

标签: pythondiscorddiscord.pybots

解决方案


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)

这里第一个条件检查只提到了一个人,第二个条件检查提到的用户是必需用户。


推荐阅读