I'm making a Telegram bot and I need to set a time range for collecting messages for the last month.
from telethon import TelegramClient
from datetime import date
api_id = my_id
api_hash = ''
phone = ''
client = TelegramClient(phone, api_id, api_hash)
dateStart = date(2022, 12, 27)
async def main():
async for message in client.iter_messages(-1001369370434, reverse=True, offset_date=dateStart, search='eth'):
print(message.chat.title, ':', message.date, ':', message.text)
with client:
client.loop.run_until_complete(main())
The offset_date
should be the beginning of the date range.
Then use reverse=True
to loop from the offset_date
to today's latest message:
My complete test script:
import datetime
import asyncio
import re
from telethon import TelegramClient
CHAT = 1234567
BEGIN = datetime.datetime(2022, 11, 1, 0, 0, 0)
client = TelegramClient('anon', '111111', 'aaaabbbbccccddddeee')
client.start()
async def main():
chat = await client.get_input_entity(CHAT)
async for message in client.iter_messages(chat, reverse=True, offset_date=BEGIN):
print(message.date, "\t\t", message.text)
client.loop.run_until_complete(main())
Which output's all the messages starting 2022-11-1
until today:
2022-11-01 00:00:43+00:00 ...
2022-11-01 00:00:59+00:00 ...
2022-11-01 00:01:50+00:00 ...
2022-11-01 00:01:50+00:00 ...
2022-11-01 00:05:32+00:00 ...
2022-11-01 00:08:47+00:00 ...
2022-11-01 00:10:00+00:00 ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.