简体   繁体   English

获取用户使用 discord.py 发送的最后一条消息?

[英]Get the last message a user sent using discord.py?

I'm wondering if there is a way for the bot to get the last message a user has sent in the server chat using discord.py in Python?我想知道是否有办法让机器人使用 Python 中的 discord.py 获取用户在服务器聊天中发送的最后一条消息? Thanks a lot非常感谢

Old answer discord.py async (pre-rewrite)旧答案 discord.py 异步(重写前)

Use log_froms to get the messages from a channel.使用log_froms从频道获取消息。

and use get_all_channels to go through all the channels.并使用get_all_channels遍历所有通道。

Then search through the results for the latest version of the author.然后在结果中搜索作者的最新版本。 You have to go through each channel for a reasonable amount until you find a message from that person and then stop.您必须以合理的数量浏览每个渠道,直到找到来自该人的消息,然后停止。 The compare the first from each channel to get the latest time.比较每个通道的第一个以获得最新时间。

To get better help in the future consider joining the "discord api" discord server为了将来获得更好的帮助,请考虑加入“discord api”不和谐服务器

Edit: Method compatible with discord.py rewrite (+1.0)编辑:与 discord.py 重写兼容的方法(+1.0)

You can use channel.history() to get the history of a channel.您可以使用channel.history()来获取频道的历史记录。 It by default only fetches the latest 100 messages from a channel.默认情况下,它仅从通道中获取最新的 100 条消息。 You can increae this limit with the limit keyword.您可以使用limit关键字增加此限制。 (eg channel.history(limit = 200) (例如channel.history(limit = 200)

You can combine this with a find async iterator to get just the messages from the user with the id you are looking for await channel.history().find(lambda m: m.author.id == users_id) .您可以将其与find异步迭代器结合使用,以仅从用户处获取带有您正在寻找的 ID 的消息await channel.history().find(lambda m: m.author.id == users_id)

You then need to loop through each text channel in the server doing this and find the latest message in channel by comparing them to the previous fetched message and keeping the one which was created newer.然后,您需要遍历服务器中的每个文本通道,并通过将它们与先前获取的消息进行比较并保持创建的较新的消息来查找通道中的最新消息。

Example command which find the latest message by the user.查找用户最新消息的示例命令。

@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.")

This is a fair slow operation in my testing due to having to make many requests to discord but should work.在我的测试中,这是一个相当缓慢的操作,因为必须提出许多不和谐的请求,但应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM