首页 > 解决方案 > 如何让机器人识别何时提到角色,然后做出回应?

问题描述

我希望机器人能够识别何时标记了@Community Manager、@Admin、@Moderator 角色,在同一条消息中标记了单个或多个角色,然后向提及用户名的频道发送消息。

我可以让机器人识别何时使用此代码对其进行标记:

if client.user.mentioned_in(message) and message.mention_everyone is False:
        await message.delete()

我一生都无法弄清楚如何查看是否标记了其他角色。

我试过了

if message.role_mentions.name('Admin'):
#do stuff

但得到这个错误: AttributeError: 'list' object has no attribute 'name'

标签: botsdiscordpython-3.7

解决方案


message.role_mentions返回一个列表Role

然后您可以使用从公会获取角色message.guild.get_role(id),以便与您从消息中获得的角色列表进行比较。

应该会产生类似这样的结果:

# Create a list of roles to check against
rolesToCheckAgainst [
    # Fetches the role from the guild which the message was sent from
    message.guild.get_role("The ID of the role"),
    message.guild.get_role("The ID of the second role")
    #etc...
]

# 'rolesWerePinged' will be true if any of the roles were pinged
rolesWerePinged = any(item in rolesToCheckAgainst for item in message.role_mentions)

if rolesWerePinged:
    # Do something, some of the roles was pinged.

Also, I used any() to check if any of the roles mentioned contained any of the roles that needed to be check against.
You can use a double-loop instead if you need different actions to be done depending on the type of roles mentioned.


推荐阅读