【问题标题】:Discord.py - how to detect if a user mentions/pings the botDiscord.py - 如何检测用户是否提到/ping 机器人
【发布时间】:2020-07-29 06:35:34
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    纯文本中的不和谐 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!')
    

    【讨论】:

    • 这段代码运行良好,没有引发任何错误,但是当你实际 ping 机器人时,它不会发送任何内容。我在函数代码的末尾添加了await client.process_commands(message),以确保它正常运行,即使那样它也没有。我是不是做错了什么?
    • @z1234556631 await client.process_commands(message) 总是还会检查你的机器人的前缀,这意味着除非你的前缀是提到机器人,否则它永远不会触发。如果您想知道如何仍然调用命令,请打开一个新问题。
    【解决方案2】:
    @bot.event
    async def on_message(message):
        mention = f'<@!{bot.user.id}>'
        if mention in message.content:
            await message.channel.send("You mentioned me")
    

    【讨论】:

    • 如果 Discord 提及的字符串发生变化,此代码可能会中断。我推荐使用内置的user.mention
    【解决方案3】:

    我发现一些有用的东西是:

    if str(client.user.id) in message.content:
         await message.channel.send('You mentioned me!')
    

    【讨论】:

      【解决方案4】:

      我发现默认函数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

      【讨论】:

      • 嗨 :),你能在你的答案中添加一点描述吗?
      • 我觉得这是不言自明的,但确实
      猜你喜欢
      • 2019-08-07
      • 2021-09-28
      • 2021-07-17
      • 2021-05-02
      • 1970-01-01
      • 2021-01-26
      • 2021-04-04
      • 2021-04-16
      • 2021-12-04
      相关资源
      最近更新 更多