5

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?

EightShift
  • 71
  • 1
  • 5

2 Answers2

7

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

Lonami
  • 5,945
  • 2
  • 20
  • 38
  • for some reason can't find it in the docs ([search results from the docs](https://docs.telethon.dev/en/stable/search.html?q=GetPeerDialogsRequest&check_keywords=yes&area=default)) Is it still the recommended way to get unread messages? – Rotkiv Oct 23 '22 at 23:35
  • 1
    The docs you linked do not include raw API (that's in https://tl.telethon.dev). If you have a particular chat you want to fetch unread messages from, yes, this is still the best ("more efficient") you can do. If you want to get all unread messages from all chats, Arthur's answer is better. – Lonami Oct 24 '22 at 08:47
1

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]
vmemmap
  • 510
  • 4
  • 20