【发布时间】:2020-07-29 06:35:34
【问题描述】:
所以我只是想知道,如何在 discord.py 中创建一个事件,如果用户 ping 机器人,它会回复一条消息?
我在任何地方都没有找到关于如何做到这一点的任何具体内容,如果有人能帮助我了解如何做到这一点,我将不胜感激。我很感激!
【问题讨论】:
标签: python python-3.x discord discord.py
所以我只是想知道,如何在 discord.py 中创建一个事件,如果用户 ping 机器人,它会回复一条消息?
我在任何地方都没有找到关于如何做到这一点的任何具体内容,如果有人能帮助我了解如何做到这一点,我将不胜感激。我很感激!
【问题讨论】:
标签: python python-3.x discord discord.py
纯文本中的不和谐 ping 是使用特殊字符串完成的。幸运的是,您不必自己生成这些,因为 discord.py 有 user.mention (documentation)。你的客户用户也有这个documentation。所以我们只是通过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!')
【讨论】:
await client.process_commands(message),以确保它正常运行,即使那样它也没有。我是不是做错了什么?
@bot.event
async def on_message(message):
mention = f'<@!{bot.user.id}>'
if mention in message.content:
await message.channel.send("You mentioned me")
【讨论】:
user.mention
我发现一些有用的东西是:
if str(client.user.id) in message.content:
await message.channel.send('You mentioned me!')
【讨论】:
我发现默认函数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!')
我不知道为什么,但我还没有看到其他人使用这个功能。也许他们只是没有意识到这一点,而是使用client.user.id in message.content
【讨论】: