4

how to get message that posted today using TELETHON

I'm using the below code

date_of_post = datetime.datetime(2019, 12, 24)

with TelegramClient(name, api_id, api_hash) as client:
    for message in client.iter_messages(chat , offset_date = date_of_post):
        print(message.sender_id, ':', message.text)
shahaf
  • 4,750
  • 2
  • 29
  • 32
alex smolyakov
  • 198
  • 2
  • 8

2 Answers2

6

offset_date is used to get messages prior to that date. So you should use the day after:

async def get_messages_at_date(chat, date):
    result = []
    tomorrow = date + datetime.timedelta(days=1)
    async for msg in client.iter_messages(chat, offset_date=date):
        if msg.date < date:
            return result
        result.append(msg)
Lonami
  • 5,945
  • 2
  • 20
  • 38
  • simply `offset_date` doesn't work on `telethon`. I had to compare the `message.date` with the target date to achieve the same goal. – pouya Feb 07 '23 at 10:58
  • If you are using `iter_messages` as showcased and `offset_date` is returning messages equal to or after that date, either the implementation is bug (in which case a bug report would be appreciated) or the Telegram server is not honoring the request. – Lonami Feb 07 '23 at 18:06
2

The point made by @Lonami is valid - offset_date is used to get messages prior to that date. However, the docs describe another argument called reverse that you can supply to iter_messages :

reverse (bool, optional): If set to True, the messages will be returned in reverse order (from oldest to newest, instead of the default newest to oldest). This also means that the meaning of offset_id and offset_date parameters is reversed, although they will still be exclusive.

So, if you use it like this:


for message in client.iter_messages(chat, reverse = True, offset_date = date_of_post):
   print(message.sender_id, ':', message.text)

it should work as you expected.

esimonov
  • 546
  • 3
  • 8