248 lines
10 KiB
Python
248 lines
10 KiB
Python
"""LarkSniffer CLI; upstream LarkAgentX remains a separate dependency."""
|
||
|
||
import argparse
|
||
import json
|
||
import os
|
||
import sys
|
||
from datetime import datetime
|
||
|
||
from larkx.auth import LarkAuth
|
||
|
||
from .client import SnifferLarkClient as LarkClient
|
||
from .storage import SnifferStorage as Storage
|
||
|
||
|
||
def _print_json(value):
|
||
print(json.dumps(value, ensure_ascii=False, indent=2, default=str))
|
||
|
||
|
||
def cmd_history(args):
|
||
client = LarkClient(LarkAuth())
|
||
if args.all or args.date:
|
||
if not args.all or not args.date or args.chat_id or args.start is not None:
|
||
print(
|
||
"按日期批量拉取用法: larksniffer history --all --date today --save",
|
||
file=sys.stderr,
|
||
)
|
||
return 2
|
||
if not args.save or args.json:
|
||
print("按日期批量拉取必须 --save,且不支持 --json(不输出正文)", file=sys.stderr)
|
||
return 2
|
||
from .history import HistoryError, sync_all_chats_for_day
|
||
from .summary import SummaryError, resolve_day
|
||
|
||
try:
|
||
target_day, _, _, tz = resolve_day(args.date, "Asia/Shanghai")
|
||
stats = sync_all_chats_for_day(
|
||
client,
|
||
Storage(),
|
||
target_day,
|
||
tz,
|
||
batch_size=args.count,
|
||
)
|
||
except (HistoryError, SummaryError) as error:
|
||
print(f"历史消息入库失败: {error}", file=sys.stderr)
|
||
return 1
|
||
print(
|
||
f"历史消息入库完成: {target_day.isoformat()},会话 {stats['chats']} 个,"
|
||
f"日期内消息 {stats['matched']} 条,写入/补全 {stats['saved']} 条,"
|
||
f"失败会话 {stats['failed']} 个,历史请求 {stats['requests']} 次(正文不打印)"
|
||
)
|
||
return 1 if stats["failed"] else 0
|
||
if not args.chat_id:
|
||
print("请指定 chat_id,或使用 --all --date today --save", file=sys.stderr)
|
||
return 2
|
||
chat_id = args.chat_id
|
||
if args.start is not None:
|
||
start = args.start
|
||
else:
|
||
info = client.get_chat_info(chat_id)
|
||
if not info or not info.get("lastMessagePosition"):
|
||
print("拿不到会话的最新 position,请用 --start 指定", file=sys.stderr)
|
||
return 1
|
||
start = int(info["lastMessagePosition"]) - args.count + 1
|
||
if info.get("name"):
|
||
storage = Storage()
|
||
storage.update_chat_name(
|
||
chat_id,
|
||
info["name"],
|
||
info.get("type", 0) if isinstance(info.get("type"), int) else 0,
|
||
)
|
||
positions = list(range(max(1, start), max(1, start) + args.count))
|
||
storage = Storage() if args.save else None
|
||
messages = client.pull_history(chat_id, positions, save_storage=storage)
|
||
for message in messages:
|
||
if args.json:
|
||
continue
|
||
timestamp = (
|
||
datetime.fromtimestamp(message["create_time"]).strftime("%m-%d %H:%M")
|
||
if message.get("create_time")
|
||
else ""
|
||
)
|
||
scope = f"[{message['scope']}:{message['anchor'][:8]}]" if message["anchor"] else ""
|
||
content = message["content"] or ""
|
||
shown = content[:120] + ("…" if len(content) > 120 else "")
|
||
print(f"{message['position']:>6} [{timestamp}]{scope} {message['from_id']}: {shown}")
|
||
if args.json:
|
||
_print_json(
|
||
[{key: value for key, value in message.items() if key != "content_data"} for message in messages]
|
||
)
|
||
if args.save:
|
||
print(f"已入库 {len(messages)} 条")
|
||
return 0
|
||
|
||
|
||
def cmd_summarize(args):
|
||
from .summary import (
|
||
DEFAULT_BASE_URL,
|
||
DEFAULT_MODEL,
|
||
DEFAULT_TIMEZONE,
|
||
MagpieClient,
|
||
SummaryError,
|
||
configured_output_path,
|
||
default_dry_run_path,
|
||
default_summary_path,
|
||
load_output_config,
|
||
resolve_day,
|
||
serialize_message,
|
||
summarize_messages,
|
||
write_summary,
|
||
)
|
||
|
||
try:
|
||
target_day, start, end, tz = resolve_day(
|
||
args.date, args.timezone or DEFAULT_TIMEZONE
|
||
)
|
||
model = args.model or os.environ.get("MAGPIE_MODEL", DEFAULT_MODEL)
|
||
base_url = args.base_url or os.environ.get("MAGPIE_BASE_URL", DEFAULT_BASE_URL)
|
||
client = MagpieClient(
|
||
model=model,
|
||
base_url=base_url,
|
||
api_key=os.environ.get("MAGPIE_API_KEY"),
|
||
timeout=args.timeout,
|
||
)
|
||
# The EFundGPT preflight must pass before history sync or storage access.
|
||
client.assert_model_available()
|
||
if args.check:
|
||
print(f"OK Magpie 可用模型: {model}(未读取消息)")
|
||
return 0
|
||
output_config = {} if args.output else load_output_config(getattr(args, "config", None))
|
||
storage = Storage()
|
||
if not args.no_fetch:
|
||
from .history import sync_all_chats_for_day
|
||
|
||
try:
|
||
fetch_stats = sync_all_chats_for_day(
|
||
LarkClient(LarkAuth()),
|
||
storage,
|
||
target_day,
|
||
tz,
|
||
batch_size=50,
|
||
chat_ids=args.chat,
|
||
)
|
||
except Exception as error:
|
||
raise SummaryError(
|
||
f"飞书历史数据同步失败({type(error).__name__});"
|
||
"可使用 --no-fetch 明确只读本地库。"
|
||
) from error
|
||
if fetch_stats["failed"]:
|
||
raise SummaryError(
|
||
f"有 {fetch_stats['failed']} 个会话同步失败,已停止后续总结;"
|
||
"可修复后重试,或使用 --no-fetch 明确只读本地库。"
|
||
)
|
||
print(
|
||
f"数据同步完成: 日期内消息 {fetch_stats['matched']} 条,"
|
||
f"写入/补全 {fetch_stats['saved']} 条,失败会话 0 个"
|
||
)
|
||
rows = storage.get_received_messages(
|
||
int(start.timestamp()), int(end.timestamp()), chat_ids=args.chat
|
||
)
|
||
if args.dry_run:
|
||
records = [serialize_message(row, tz) for row in rows]
|
||
output_path = (
|
||
args.output
|
||
or configured_output_path(output_config, "dry_run", target_day)
|
||
or default_dry_run_path(target_day)
|
||
)
|
||
output = write_summary(
|
||
output_path, json.dumps(records, ensure_ascii=False, indent=2)
|
||
)
|
||
print(
|
||
f"DRY RUN 已导出: {output}"
|
||
f"({target_day.isoformat()},收到消息 {len(rows)} 条,未发送给模型)"
|
||
)
|
||
return 0
|
||
contacts = None
|
||
if rows and not args.no_contacts:
|
||
from .contacts import ContactsError, fetch_contacts
|
||
|
||
try:
|
||
contacts = fetch_contacts(LarkClient(LarkAuth()), rows)
|
||
except ContactsError as error:
|
||
raise SummaryError(str(error)) from error
|
||
content = summarize_messages(
|
||
client,
|
||
rows,
|
||
target_day,
|
||
tz,
|
||
max_chars=args.max_chars,
|
||
contacts=contacts,
|
||
)
|
||
output_path = (
|
||
args.output
|
||
or configured_output_path(output_config, "summary", target_day)
|
||
or default_summary_path(target_day)
|
||
)
|
||
output = write_summary(output_path, content)
|
||
print(
|
||
f"已生成: {output}({target_day.isoformat()},收到消息 {len(rows)} 条,模型 {model})"
|
||
)
|
||
return 0
|
||
except SummaryError as error:
|
||
print(f"生成失败: {error}", file=sys.stderr)
|
||
return 1
|
||
except OSError as error:
|
||
print(f"写入总结失败: {type(error).__name__}", file=sys.stderr)
|
||
return 1
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(
|
||
prog="larksniffer", description="LarkAgentX 历史同步与 EFundGPT 日度总结"
|
||
)
|
||
subparsers = parser.add_subparsers(dest="cmd", required=True)
|
||
|
||
history = subparsers.add_parser("history", help="拉取历史消息;支持全部可见 INBOX 会话按日期入库")
|
||
history.add_argument("chat_id", nargs="?")
|
||
history.add_argument("--all", action="store_true", help="枚举全部可见 INBOX 会话,需配合 --date --save")
|
||
history.add_argument("--date", help="只入库指定自然日消息:YYYY-MM-DD、today 或 yesterday")
|
||
history.add_argument("--start", type=int, help="起始 position;不可与 --date 同用")
|
||
history.add_argument("--count", type=int, default=20)
|
||
history.add_argument("--save", action="store_true", help="同时写入本地库")
|
||
history.add_argument("--json", action="store_true")
|
||
history.set_defaults(fn=cmd_history)
|
||
|
||
summarize = subparsers.add_parser("summarize", help="按对话分别摘要后,仅用 EFundGPT* 生成每日总结")
|
||
summarize.add_argument("--date", default="today", help="YYYY-MM-DD、today(默认) 或 yesterday")
|
||
summarize.add_argument("--timezone", default="Asia/Shanghai", help="统计日边界时区")
|
||
summarize.add_argument("--chat", action="append", help="只汇总指定 chat_id;可重复")
|
||
summarize.add_argument("--model", help="实际模型段必须以 EFundGPT 开头;也可设 MAGPIE_MODEL")
|
||
summarize.add_argument("--base-url", help="Magpie OpenAI 兼容地址")
|
||
summarize.add_argument("--timeout", type=int, default=180, help="单次 Magpie 请求超时秒数")
|
||
summarize.add_argument("--max-chars", type=int, default=80000, help="每个对话内每块消息最大字符数")
|
||
summarize.add_argument("--no-contacts", action="store_true", help="不联网获取相关会话通讯录")
|
||
summarize.add_argument("--no-fetch", action="store_true", help="只读取本地已入库记录")
|
||
summarize.add_argument("--config", help="YAML 配置路径;默认读取当前目录 larksniffer.yaml")
|
||
summarize.add_argument("-o", "--output", help="输出路径,优先级高于 YAML")
|
||
mode = summarize.add_mutually_exclusive_group()
|
||
mode.add_argument("--check", action="store_true", help="只检查模型,不同步或读取消息")
|
||
mode.add_argument("--dry-run", action="store_true", help="只导出消息 JSON,不发送给模型")
|
||
summarize.set_defaults(fn=cmd_summarize)
|
||
|
||
args = parser.parse_args()
|
||
sys.exit(args.fn(args))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|