Merge pull request #28 from strato-space/main

fix: make list_messages respect date/search limits (#27)
This commit is contained in:
Eugene Evstafev 2025-10-13 20:12:27 +01:00 committed by GitHub
commit da3f3ec524
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

50
main.py
View file

@ -412,20 +412,48 @@ async def list_messages(
# Prepare filter parameters # Prepare filter parameters
params = {} params = {}
if search_query: if search_query:
# IMPORTANT: Do not combine offset_date with search.
# Use server-side search alone, then enforce date bounds client-side.
params["search"] = search_query params["search"] = search_query
messages = []
messages = await client.get_messages(entity, limit=limit, **params) async for msg in client.iter_messages(entity, **params): # newest -> oldest
# Apply date filters (Telethon doesn't support date filtering in get_messages directly)
if from_date_obj or to_date_obj:
filtered_messages = []
for msg in messages:
if from_date_obj and msg.date < from_date_obj:
continue
if to_date_obj and msg.date > to_date_obj: if to_date_obj and msg.date > to_date_obj:
continue continue
filtered_messages.append(msg) if from_date_obj and msg.date < from_date_obj:
messages = filtered_messages break
messages.append(msg)
if len(messages) >= limit:
break
else:
# Use server-side iteration when only date bounds are present
# (no search) to avoid over-fetching.
if from_date_obj or to_date_obj:
messages = []
if from_date_obj:
# Walk forward from start date (oldest -> newest)
async for msg in client.iter_messages(
entity, offset_date=from_date_obj, reverse=True
):
if to_date_obj and msg.date > to_date_obj:
break
if msg.date < from_date_obj:
continue
messages.append(msg)
if len(messages) >= limit:
break
else:
# Only upper bound: walk backward from end bound
async for msg in client.iter_messages(
# offset_date is exclusive; +1µs makes to_date inclusive
entity,
offset_date=to_date_obj + timedelta(microseconds=1),
):
messages.append(msg)
if len(messages) >= limit:
break
else:
messages = await client.get_messages(entity, limit=limit, **params)
if not messages: if not messages:
return "No messages found matching the criteria." return "No messages found matching the criteria."