70 lines
2.0 KiB
Python
70 lines
2.0 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import logging
|
||
|
|
|
||
|
|
from .graph import MSTeamsGraphClient
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
|
||
|
|
async def fetch_thread_replies(
|
||
|
|
graph_client: MSTeamsGraphClient,
|
||
|
|
chat_id: str,
|
||
|
|
parent_message_id: str,
|
||
|
|
*,
|
||
|
|
limit: int = 50,
|
||
|
|
) -> list[dict]:
|
||
|
|
path = f"/chats/{chat_id}/messages/{parent_message_id}/replies?$top={limit}"
|
||
|
|
try:
|
||
|
|
data = await graph_client.fetch_json(path)
|
||
|
|
return _parse_messages(data)
|
||
|
|
except Exception as e:
|
||
|
|
logger.warning("Failed to fetch thread replies for chat=%s, message=%s: %s", chat_id, parent_message_id, e)
|
||
|
|
return []
|
||
|
|
|
||
|
|
|
||
|
|
async def fetch_thread_root(
|
||
|
|
graph_client: MSTeamsGraphClient,
|
||
|
|
chat_id: str,
|
||
|
|
parent_message_id: str,
|
||
|
|
) -> dict | None:
|
||
|
|
path = f"/chats/{chat_id}/messages/{parent_message_id}"
|
||
|
|
try:
|
||
|
|
data = await graph_client.fetch_json(path)
|
||
|
|
return _parse_single_message(data)
|
||
|
|
except Exception as e:
|
||
|
|
logger.warning("Failed to fetch thread root for chat=%s, message=%s: %s", chat_id, parent_message_id, e)
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def _parse_single_message(data: dict) -> dict:
|
||
|
|
body = data.get("body", {})
|
||
|
|
content = body.get("content", "")
|
||
|
|
from_info = data.get("from", {})
|
||
|
|
return {
|
||
|
|
"id": data.get("id", ""),
|
||
|
|
"text": content,
|
||
|
|
"timestamp": data.get("createdDateTime", ""),
|
||
|
|
"from": from_info,
|
||
|
|
"from_name": from_info.get("user", {}).get("displayName", ""),
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def _parse_messages(data: dict) -> list[dict]:
|
||
|
|
messages = data.get("value", [])
|
||
|
|
result = []
|
||
|
|
for msg in messages:
|
||
|
|
body = msg.get("body", {})
|
||
|
|
content = body.get("content", "")
|
||
|
|
from_info = msg.get("from", {})
|
||
|
|
result.append(
|
||
|
|
{
|
||
|
|
"id": msg.get("id", ""),
|
||
|
|
"text": content,
|
||
|
|
"timestamp": msg.get("createdDateTime", ""),
|
||
|
|
"from": from_info,
|
||
|
|
"from_name": from_info.get("user", {}).get("displayName", ""),
|
||
|
|
}
|
||
|
|
)
|
||
|
|
return result
|