How to get only unread messages from chat using telethon?

Viewed 1721

I have client.get_messages(dialog.entity) but its return just messages without "read/unread mark"... So, how can I get unread new messages only? Anybody know?

2 Answers

In addition to the accepted answer, it's possible to fetch only the dialogs you are interested in with GetPeerDialogsRequest, which may be used to do operations on entire folders as well.

To get the amount of unread messages from '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)

Note that peers may be a list, so you can fetch multiple at once. Note that the dialog includes more information, such as "up to which ID has been read".

Each dialog has 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]
Related