【问题标题】:How to get the ID of a mentioned User in Python discord bot?如何在 Python discord bot 中获取提到的用户的 ID?
【发布时间】:2018-06-29 12:13:23
【问题描述】:

所以我在 python 中编写了一个不和谐的机器人。但有一个问题。我知道如何提及发送消息的用户。但是如何获取作者在消息中提到的用户 ID?我无法得到答案。

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    discord.Message 对象具有mentions 属性,它返回消息内容中提到的所有用户的discord.Member 对象列表,discord.Member 对象具有discord.User 对象作为父对象,因此您可以访问discord.User author.idauthor.name 等属性只需使用

    for member in message.mentions:
        # do stuff with member
    

    你真的应该使用discord.ext.commands(async rewrite) 因为制作一个纯粹在 on_message 事件方法中工作的命令解析器是一个糟糕的非 Python 想法。

    你可能想要什么

    似乎您只想要能够访问消息的作者对象和消息中提到的用户作为参数,为此请参阅我的答案here。要访问作者,您只需通过 discord.Message 对象和 message.author 即可完成

    【讨论】:

      【解决方案2】:

      您可以使用message.mentions (async rewrite) 获取消息中提到的用户

      从那里,您可以从成员对象中获取 ID,或者从这些对象中获取格式化的提及

      message.mentions[0].id
      message.mentions[0].mention
      

      【讨论】:

      • 那么下面的例子正确吗? async def on_message(): if message.content.upper() == "+CALL": await bot.send_message(message.channel, "<%s> and <%s> are called to come" % (message.mentions[0].id,message.mentions[1].id))
      • 没有。提及的格式为<@...> 而不仅仅是<...>。此外,您可以只使用member.mention 创建预先格式化的提及。 "%s" % message.mentions[0].mention。最后,可能值得研究str.format
      猜你喜欢
      • 2020-10-04
      • 2021-05-22
      • 2021-10-24
      • 2020-12-26
      • 2021-07-18
      • 2021-03-15
      • 2019-05-03
      • 2021-02-07
      相关资源
      最近更新 更多