【问题标题】:Get the last message a user sent using discord.py?获取用户使用 discord.py 发送的最后一条消息?
【发布时间】:2018-01-15 18:52:38
【问题描述】:

我想知道机器人是否有办法使用 Python 中的 discord.py 获取用户在服务器聊天中发送的最后一条消息?非常感谢

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    旧答案 discord.py 异步(预重写)

    使用log_froms 从频道获取消息。

    并使用get_all_channels 浏览所有渠道。

    然后在结果中搜索作者的最新版本。您必须以合理的数量通过每个渠道,直到找到该人的消息然后停止。比较每个频道的第一个以获得最新的时间。

    为了将来获得更好的帮助考虑加入the "discord api" discord server

    编辑:与 discord.py rewrite (+1.0) 兼容的方法

    您可以使用channel.history() 获取频道的历史记录。默认情况下,它仅从频道中获取最新的 100 条消息。您可以使用 limit 关键字增加此限制。 (例如channel.history(limit = 200)

    您可以将它与 find 异步迭代器结合使用,以仅从具有您正在寻找的 id await channel.history().find(lambda m: m.author.id == users_id) 的用户那里获取消息。

    然后,您需要遍历服务器中的每个文本通道,并通过将它们与先前获取的消息进行比较并保持创建的更新消息来找到通道中的最新消息。

    查找用户最新消息的示例命令。

    @commands.command()
    async def lastMessage(self, ctx, users_id: int):
        oldestMessage = None
        for channel in ctx.guild.text_channels:
            fetchMessage = await channel.history().find(lambda m: m.author.id == users_id)
            if fetchMessage is None:
                continue
    
    
            if oldestMessage is None:
                oldestMessage = fetchMessage
            else:
                if fetchMessage.created_at > oldestMessage.created_at:
                    oldestMessage = fetchMessage
    
        if (oldestMessage is not None):
            await ctx.send(f"Oldest message is {oldestMessage.content}")
        else:
            await ctx.send("No message found.")
    

    在我的测试中,这是一个相当缓慢的操作,因为必须提出许多不和谐的请求,但应该可以工作。

    【讨论】:

    • log_froms 不再是 discord.py 的一部分,但似乎使用 channel.history 是执行此操作的新方法。您可以遍历所有消息并记录作者。
    • @Cole128 感谢您指出这一点!我刚刚更新了我的答案以与 discord.py rewrite 兼容。如果您有任何反馈或问题,请发表评论。 :)
    • 此代码似乎不起作用。声称某些用户从未发送过消息,尽管这样做了。
    • @Laif 您是否尝试过像await channel.history(limit = 1000).find(lambda m: m.author.id == users_id) 一样增加await channel.history().find(lambda m: m.author.id == users_id) 中的获取限制
    • @Tim 实际上我只是尝试了这个,在研究了它为什么不起作用之后。不过,这对我的用例并不适用。我正在尝试制作一个脚本,让用户在 x 时间没有说话后自动绑定用户。是否有某种 API 钩子可以让我检查这个?也许利用搜索功能?
    猜你喜欢
    • 2022-07-10
    • 2022-01-22
    • 2019-05-10
    • 2018-04-20
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多