【问题标题】:How to make my discord.py bot respond to a specific user being mentioned?如何让我的 discord.py 机器人响应被提及的特定用户?
【发布时间】:2021-10-22 21:55:09
【问题描述】:

我希望我的机器人在提到某个用户时做出响应。我只在谷歌上找到了答案的 sn-ps,我不能把它们放在一起。我注意到,如果我调用一个字符串来代替用户 ID,它会起作用,但是如果我在同一条消息中调用带有用户 ID 的字符串,它不会返回任何内容。

感谢您的任何见解,工作如下(当然,将所需的用户 ID 替换为 ):

@client.event
async def on_message(message):
    if message.author == client.user:
      return
        #Making sure it doesn't respond to itself

    if "@here" in message.content: 
      return
    if "@everyone" in message.content:
      return
        #Making sure it doesn't respond to tags including everyone

    if '<@user_id>' in message.content:
        clock = get_time()
        clock = json.dumps(clock, indent=4)
        await message.channel.send("The time in Athens is currently: ")
        await message.channel.send(clock[-11: -6])

client.run(os.environ['TOKEN'])

【问题讨论】:

标签: discord.py


【解决方案1】:

Message 对象有一个提及对象,因此您可以像这样从那里获取提到的用户:

    message.mentions[0]

返回用户对象,你可以用它做任何你想做的事情。

如果您想检查消息中是否有提及,只需执行以下操作:

    if message.mentions:
        #your code

【讨论】:

  • 感谢您的帮助!这让我更近了一步(除非我遗漏了什么),但运行它给了我这个错误:忽略 on_message Traceback 中的异常(最近一次调用最后一次):文件“/opt/virtualenvs/python3/lib/python3.8/ site-packages/discord/client.py”,第 343 行,在 _run_event 中 await coro(*args, **kwargs) 文件“main.py”,第 31 行,on_message 如果 user_id 在 message.mentions[0] 中:类型错误: “成员”类型的参数不可迭代我不知道如何继续使成员可迭代。代码在下面的评论中:
  • ` python if user_id in message.mentions[0]: clock = get_time() clock = json.dumps(clock, indent=4) await message.channel.send("雅典的时间是当前:") 等待 message.channel.send(clock[-11: -6])`
猜你喜欢
  • 2019-12-21
  • 2018-05-10
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 2021-01-27
  • 2021-03-29
  • 1970-01-01
  • 2018-07-09
相关资源
最近更新 更多