【问题标题】:Is there a way in Telethon to get messages from chats along with the sender name, date and time?Telethon 有没有办法从聊天中获取消息以及发件人姓名、日期和时间?
【发布时间】:2021-10-03 02:39:16
【问题描述】:

我可以从聊天中获取消息,但我需要在消息中添加发件人姓名、日期和时间。

【问题讨论】:

    标签: python-3.x telegram telethon telegram-api


    【解决方案1】:

    是的。并且所有内容都在文档中进行了解释,浏览它或简单地搜索消息会引导您到 iter_messages

    在函数接受的参数列表下方,您有方法返回的实例。举个例子:

    # From most-recent to oldest
    async for message in client.iter_messages(chat):
        print(message.id, message.text)
    
    # From oldest to most-recent
    async for message in client.iter_messages(chat, reverse=True):
        print(message.id, message.text)
    
    # Filter by sender
    async for message in client.iter_messages(chat, from_user='me'):
        print(message.text)
    
    # Server-side search with fuzzy text
    async for message in client.iter_messages(chat, search='hello'):
        print(message.id)
    
    # Filter by message type:
    from telethon.tl.types import InputMessagesFilterPhotos
    async for message in client.iter_messages(chat, filter=InputMessagesFilterPhotos):
        print(message.photo)
    
    # Getting comments from a post in a channel:
    async for message in client.iter_messages(channel, reply_to=123):
        print(message.chat.title, message.text)
    

    返回的Message 实例具有您可以使用的这些属性和方法:

    message.date - UTC+0 日期时间对象,指示此消息的发送时间。这将始终存在,除了空消息。

    message.get_sender() - 返回sender,但会调用 API 来查找发件人,除非它已被缓存。

    因此,鉴于所有这些,您拥有:

    async for message in client.iter_messages(chat):
        date = message.date
        sender = await message.get_sender()
        name = sender.first_name
    

    【讨论】:

    • 当使用iter_messages 时,message.sender 将始终存在。 get_sender 用于消息事件之类的事情,sender 可能会丢失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2022-01-08
    • 1970-01-01
    • 2021-11-09
    • 2016-05-22
    相关资源
    最近更新 更多