【问题标题】:How to make my bot respond to someone only if it mentions someone specifically?只有当我的机器人特别提到某人时,如何让我的机器人回复某人?
【发布时间】:2021-09-17 01:17:32
【问题描述】:

我想创建一个机器人,它可以对特别提及/标记@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'])

【问题讨论】:

    标签: python discord discord.py bots


    【解决方案1】:

    您收到的message 作为on_message 的第一个参数是一个消息对象。它有一个mention property(from documentation) 属性,其中包含提到的用户或成员列表。所以你可以使用:

    if <user id> in [user.id for user in message.mentions]:
        await message.add_reaction(emoji)
    

    用适当的用户 ID 替换 &lt;user id&gt;[user.id for user in message.mentions] 将用户对象列表转换为用户 ID 列表。这种方法称为列表推导。然后 if 语句检查 &lt;user id&gt; 是否存在于生成的用户 ID 列表中。
    要检查是否没有提到其他人,请使用:

    if len(message.mentions) == 1 and <user id> in [user.id for user in message.mentions]:
        await message.add_reaction(emoji)
    

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

    【讨论】:

    • 考虑为一些东西添加更多文档/解释,因为 OP 说他在编程和 python 方面非常非常非常新
    猜你喜欢
    • 2020-12-30
    • 2021-04-09
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2019-06-29
    • 2021-03-31
    • 2021-05-11
    相关资源
    最近更新 更多