Discord.py - 如何检测用户是否提及/ping 机器人

z12*_*631 5 python python-3.x discord discord.py

所以我只是想知道,如何在 discord.py 中创建一个事件,如果用户 ping 机器人,它会以消息响应?

我还没有在任何地方找到任何关于如何做到这一点的具体内容,如果有人能帮助我了解如何做到这一点,我将不胜感激。我很感激!

小智 7

我发现默认功能discord.User.mentioned_in可以用

为了让它检查我们的机器人,我们client.user在函数前面添加(这是我们的机器人),使其成为client.user.mentioned_in(message). 参数, 应该与您为该行message给出的参数相同async def on_message(message)

例子:

@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        await message.channel.send('You mentioned me!')
Run Code Online (Sandbox Code Playgroud)

我不知道为什么,但我还没有看到其他人使用这个功能。也许他们只是没有意识到这一点,而是使用client.user.id in message.content


小智 1

纯文本中的不一致 ping 是使用特殊字符串完成的。幸运的是,您不必像discord.py 那样自己生成这些内容user.mention文档)。您的客户用户也有此文档。所以我们只需通过以下方式获取我们自己提到的字符串client.user.mention

现在我们只需检查该特定字符串是否在消息中:

@client.event
async def on_message(message):
    if client.user.mention in message.content.split():
        await message.channel.send('You mentioned me!')
Run Code Online (Sandbox Code Playgroud)