如何使用Telethon从聊天中仅获取未读消息?

时间:2020-08-21 08:50:14

标签: python telethon

我有client.get_messages(dialog.entity),但它只返回不带“已读/未读标记”的消息... 因此,我如何才能仅获得未读的新消息? 有人知道吗?

2 个答案:

答案 0 :(得分:1)

每个对话框都有unread_count

x = [[d.unread_count, d.title] for d in client.get_dialogs() if not getattr(d.entity, 'is_private', False) and d.unread_count != 0]
x = [[d.unread_count, d.title] for d in client.get_dialogs() if not getattr(d.entity, 'megagroup', False) and d.unread_count != 0]

答案 1 :(得分:1)

除了可接受的答案外,还可以使用GetPeerDialogsRequest仅提取您感兴趣的对话框,该对话框也可以用于对整个文件夹进行操作。

要获取来自'username'的未读邮件数量:

from telethon.sync import TelegramClient
from telethon import functions, types

with TelegramClient(name, api_id, api_hash) as client:
    result = client(functions.messages.GetPeerDialogsRequest(
        peers=['username']
    ))
    print(result.dialogs[0].unread_count)

请注意,peers可能是一个列表,因此您可以一次获取多个。请注意,该对话框包含更多信息,例如“读取ID最多”。