"""Feishu contact enrichment scoped to chats participating in a summary.""" from __future__ import annotations from collections.abc import Iterable from typing import Any class ContactsError(RuntimeError): """Contact lookup failed without exposing names or upstream response bodies.""" def _names(payload: dict[str, Any]) -> dict[str, str]: result = {} for key, person in (payload or {}).items(): if not isinstance(person, dict): continue user_id = str(person.get("id") or key or "") name = person.get("name") if user_id and isinstance(name, str) and name.strip(): result[user_id] = name.strip() return result def _sender_metadata( client: Any, sender_ids: Iterable[str] ) -> tuple[dict[str, str], dict[str, int]]: ids = sorted({str(user_id) for user_id in sender_ids if user_id}) names = {} types = {} for offset in range(0, len(ids), 50): response = client.api( "chatters.PullChattersByIdsRequest", { "chatterIds": ids[offset : offset + 50], "notSubscribeChatters": True, }, ) chatters = (response or {}).get("chatters") or {} names.update(_names(chatters)) for key, person in chatters.items(): if not isinstance(person, dict): continue user_id = str(person.get("id") or key or "") try: sender_type = int(person.get("type") or 0) except (TypeError, ValueError): sender_type = 0 if user_id: types[user_id] = sender_type return names, types def _sender_names(client: Any, sender_ids: Iterable[str]) -> dict[str, str]: return _sender_metadata(client, sender_ids)[0] def _chat_member_names(client: Any, chat_id: str) -> dict[str, str]: names = {} cursor = None for _ in range(100): request = {"chatId": chat_id, "needChatters": True, "limit": 100} if cursor is not None: request["cursor"] = cursor response = client.api("chats.PullChatChattersRequest", request) or {} names.update(_names(response.get("chatters") or {})) next_cursor = response.get("nextCursor") if not next_cursor: return names if cursor is not None and str(next_cursor) == str(cursor): raise ContactsError("通讯录分页游标没有前进。") cursor = next_cursor raise ContactsError("通讯录分页超过安全页数上限。") def fetch_contacts( client: Any, rows: list[Any], sender_types: dict[str, int] | None = None ) -> dict[str, dict[str, str]]: """Return scoped full names and optionally sender type metadata (1=human, 2=bot).""" chats = {} for row in rows: chat_id = str(row.chat_id) chats.setdefault(chat_id, {"type": row.chat_type, "sender_ids": set()}) if row.sender_id: chats[chat_id]["sender_ids"].add(str(row.sender_id)) try: senders, types = _sender_metadata( client, { sender_id for chat in chats.values() for sender_id in chat["sender_ids"] }, ) if sender_types is not None: sender_types.update(types) result = {} for chat_id, chat in chats.items(): names = { user_id: senders[user_id] for user_id in chat["sender_ids"] if user_id in senders } if chat["type"] in (2, 3, "2", "3", "GROUP", "TOPIC_GROUP"): names.update(_chat_member_names(client, chat_id)) result[chat_id] = names return result except ContactsError: raise except Exception as exc: raise ContactsError( f"获取飞书通讯录失败({type(exc).__name__});可使用 --no-contacts 显式关闭补全。" ) from exc