fix: escape newlines in get_messages instead of switching to JSON
Replace the JSON output approach with a non-breaking fix: escape newlines in message text (\n → \\n) to preserve the existing pipe-delimited format. This fixes multi-line message parsing without breaking downstream consumers.
This commit is contained in:
parent
ff37abdb01
commit
b38051a9ee
1 changed files with 11 additions and 25 deletions
36
main.py
36
main.py
|
|
@ -727,34 +727,20 @@ async def get_messages(chat_id: Union[int, str], page: int = 1, page_size: int =
|
||||||
messages = await client.get_messages(entity, limit=page_size, add_offset=offset)
|
messages = await client.get_messages(entity, limit=page_size, add_offset=offset)
|
||||||
if not messages:
|
if not messages:
|
||||||
return "No messages found for this page."
|
return "No messages found for this page."
|
||||||
result = []
|
lines = []
|
||||||
for msg in messages:
|
for msg in messages:
|
||||||
sender_name = get_sender_name(msg)
|
sender_name = get_sender_name(msg)
|
||||||
entry = {
|
reply_info = ""
|
||||||
"id": msg.id,
|
|
||||||
"sender": sender_name,
|
|
||||||
"date": str(msg.date),
|
|
||||||
"text": msg.message,
|
|
||||||
}
|
|
||||||
if msg.reply_to and msg.reply_to.reply_to_msg_id:
|
if msg.reply_to and msg.reply_to.reply_to_msg_id:
|
||||||
entry["reply_to"] = msg.reply_to.reply_to_msg_id
|
reply_info = f" | reply to {msg.reply_to.reply_to_msg_id}"
|
||||||
# Engagement metrics (views, forwards, reactions)
|
|
||||||
engagement = {}
|
engagement_info = get_engagement_info(msg)
|
||||||
views = getattr(msg, "views", None)
|
safe_text = (msg.message or "").replace("\n", "\\n")
|
||||||
if views is not None:
|
|
||||||
engagement["views"] = views
|
lines.append(
|
||||||
forwards = getattr(msg, "forwards", None)
|
f"ID: {msg.id} | {sender_name} | Date: {msg.date}{reply_info}{engagement_info} | Message: {safe_text}"
|
||||||
if forwards is not None:
|
)
|
||||||
engagement["forwards"] = forwards
|
return "\n".join(lines)
|
||||||
reactions = getattr(msg, "reactions", None)
|
|
||||||
if reactions is not None:
|
|
||||||
results = getattr(reactions, "results", None)
|
|
||||||
if results:
|
|
||||||
engagement["reactions"] = sum(getattr(r, "count", 0) or 0 for r in results)
|
|
||||||
if engagement:
|
|
||||||
entry["engagement"] = engagement
|
|
||||||
result.append(entry)
|
|
||||||
return json.dumps(result, ensure_ascii=False, default=json_serializer)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return log_and_format_error(
|
return log_and_format_error(
|
||||||
"get_messages", e, chat_id=chat_id, page=page, page_size=page_size
|
"get_messages", e, chat_id=chat_id, page=page, page_size=page_size
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue