refactor: convert to Lark Snooper script project

This commit is contained in:
Benature
2026-11-07 11:23:50 +08:00
parent 941ba26bc6
commit 3e5ac07183
16 changed files with 106 additions and 112 deletions

92
snooper_contacts.py Normal file
View File

@ -0,0 +1,92 @@
"""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_names(client: Any, sender_ids: Iterable[str]) -> dict[str, str]:
ids = sorted({str(user_id) for user_id in sender_ids if user_id})
names = {}
for offset in range(0, len(ids), 50):
response = client.api(
"chatters.PullChattersByIdsRequest",
{
"chatterIds": ids[offset : offset + 50],
"notSubscribeChatters": True,
},
)
names.update(_names((response or {}).get("chatters") or {}))
return names
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]) -> dict[str, dict[str, str]]:
"""Return full names per relevant chat, never the unrelated enterprise directory."""
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 = _sender_names(
client,
{
sender_id
for chat in chats.values()
for sender_id in chat["sender_ids"]
},
)
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