Files
Lark-Snooper/lark_snooper.py
Benature c8658ad064 feat: 历史同步优化与消息已读属性
- 历史同步: 本地缓存优先、断点续传、按月批量同步
- 新增 sync_monthly.py: 支持逐月往前推进同步
- 消息表新增 is_read 字段,默认 false
- Obsidian 文档 frontmatter 自动补充 is_read: false
- 新增 migrate_add_is_read.py / migrate_obsidian_is_read.py 迁移脚本
- 总结 prompt 补充: 不记录腾讯会议号
- 历史同步失败时记录日志到 ~/.larkx/logs/history-failures.jsonl
2026-11-08 11:31:18 +08:00

395 lines
16 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Lark Snooper CLI; LarkAgentX is an external dependency."""
import argparse
import json
import os
import sys
from datetime import datetime
from larkx.auth import LarkAuth
from snooper_client import SnifferLarkClient as LarkClient
from snooper_storage import SnifferStorage as Storage
def _print_json(value):
print(json.dumps(value, ensure_ascii=False, indent=2, default=str))
def _report_history_failures(target_day, stats):
if not stats.get("failed"):
return
from snooper_history import format_history_failures, write_history_failures
failures = stats.get("failures", [])
details = format_history_failures(failures) or "无会话明细"
try:
log_path = write_history_failures(target_day, failures)
except OSError as error:
log_note = f"失败日志写入失败: {type(error).__name__}"
else:
log_note = f"失败日志: {log_path}"
print(
f"历史同步失败明细[{target_day.isoformat()}]: {details};{log_note}",
file=sys.stderr,
)
def cmd_web(args):
from snooper_web import WebError, run_web
try:
run_web(
port=args.port,
config_path=args.config,
open_browser=not args.no_browser,
)
return 0
except (WebError, OSError) as error:
print(f"Web 管理页启动失败: {error}", file=sys.stderr)
return 1
def cmd_history(args):
client = LarkClient(LarkAuth())
if args.all or args.date or args.days:
if args.date and args.days:
print("--date 与 --days 不能同时使用", file=sys.stderr)
return 2
if args.days is not None and args.days < 1:
print("--days 必须大于等于 1", file=sys.stderr)
return 2
if not args.all or (not args.date and not args.days) or args.chat_id or args.start is not None:
print(
"按日期批量拉取用法: ./lark_snooper.py history --all --date today --save\n"
"或: ./lark_snooper.py history --all --days 30 --save",
file=sys.stderr,
)
return 2
if not args.save or args.json:
print("按日期批量拉取必须 --save,且不支持 --json(不输出正文)", file=sys.stderr)
return 2
from snooper_history import HistoryError, sync_all_chats_for_day
from snooper_summary import (
SummaryError,
load_config,
resolve_chat_rules,
resolve_day,
)
try:
config = load_config(getattr(args, "config", None))
exclude_chat_ids, _ = resolve_chat_rules(config)
storage = Storage()
if args.days:
from datetime import timedelta
today, _, _, tz = resolve_day("today", "Asia/Shanghai")
total = {
"chats": 0, "scanned": 0, "empty": 0, "matched": 0,
"saved": 0, "failed": 0, "requests": 0, "skipped": 0,
}
for i in range(args.days):
target_day = today - timedelta(days=i)
stats = sync_all_chats_for_day(
client,
storage,
target_day,
tz,
batch_size=args.count,
exclude_chat_ids=exclude_chat_ids,
force=args.force,
)
_report_history_failures(target_day, stats)
for key in total:
total[key] += stats[key]
print(
f" {target_day.isoformat()}: 消息 {stats['matched']} 条,"
f"写入 {stats['saved']} 条,跳过会话 {stats['skipped']} 个,"
f"请求 {stats['requests']} 次"
)
stats = total
print(
f"最近 {args.days} 天入库完成: 会话 {stats['chats']} 个,"
f"跳过 {stats['skipped']} 个,日期内消息 {stats['matched']} 条,"
f"写入/补全 {stats['saved']} 条,失败会话 {stats['failed']} 个,"
f"历史请求 {stats['requests']} 次(正文不打印)"
)
return 1 if stats["failed"] else 0
target_day, _, _, tz = resolve_day(args.date, "Asia/Shanghai")
stats = sync_all_chats_for_day(
client,
storage,
target_day,
tz,
batch_size=args.count,
exclude_chat_ids=exclude_chat_ids,
force=args.force,
)
except (HistoryError, SummaryError) as error:
print(f"历史消息入库失败: {error}", file=sys.stderr)
return 1
_report_history_failures(target_day, stats)
print(
f"历史消息入库完成: {target_day.isoformat()},会话 {stats['chats']} 个,"
f"跳过 {stats['skipped']} 个,日期内消息 {stats['matched']} 条,"
f"写入/补全 {stats['saved']} 条,失败会话 {stats['failed']} 个,"
f"历史请求 {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 snooper_summary import (
DEFAULT_BASE_URL,
DEFAULT_MODEL,
DEFAULT_TIMEZONE,
MagpieClient,
SummaryError,
add_obsidian_properties,
configured_output_path,
default_dry_run_path,
default_summary_path,
load_config,
resolve_chat_rules,
resolve_day,
resolve_people_aliases,
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
config = load_config(getattr(args, "config", None))
output_config = {} if args.output else config["output"]
exclude_chat_ids, chat_prompts = resolve_chat_rules(config)
people_aliases = resolve_people_aliases(config)
storage = Storage()
if not args.no_fetch:
from snooper_history import sync_all_chats_for_day
already_local = storage.has_messages_for_day(
int(start.timestamp()),
int(end.timestamp()),
chat_ids=args.chat,
exclude_chat_ids=exclude_chat_ids,
)
if already_local and not args.force_fetch:
print(
f"本地已有 {target_day.isoformat()} 的数据,跳过网络同步"
"(--force-fetch 可强制重新拉取)"
)
fetch_stats = None
else:
try:
fetch_stats = sync_all_chats_for_day(
LarkClient(LarkAuth()),
storage,
target_day,
tz,
batch_size=50,
chat_ids=args.chat,
exclude_chat_ids=exclude_chat_ids,
force=args.force_fetch,
)
except Exception as error:
raise SummaryError(
f"飞书历史数据同步失败({type(error).__name__});"
"可使用 --no-fetch 明确只读本地库。"
) from error
_report_history_failures(target_day, fetch_stats)
if fetch_stats["failed"]:
raise SummaryError(
f"有 {fetch_stats['failed']} 个会话同步失败,已停止后续总结;"
"可修复后重试,或使用 --no-fetch 明确只读本地库。"
)
print(
f"数据同步完成: 日期内消息 {fetch_stats['matched']} 条,"
f"写入/补全 {fetch_stats['saved']} 条,"
f"跳过会话 {fetch_stats['skipped']} 个,失败会话 0 个"
)
rows = storage.get_received_messages(
int(start.timestamp()),
int(end.timestamp()),
chat_ids=args.chat,
exclude_chat_ids=exclude_chat_ids,
)
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 snooper_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,
chat_prompts=chat_prompts,
people_aliases=people_aliases,
)
output_path = (
args.output
or configured_output_path(output_config, "summary", target_day)
or default_summary_path(target_day)
)
content = add_obsidian_properties(
content, {"model": model.rsplit("/", 1)[-1], "is_read": False}
)
output = write_summary(output_path, content)
dry_run_path = configured_output_path(
config["output"], "dry_run", target_day
) or default_dry_run_path(target_day)
cleanup_note = ""
if (
dry_run_path.suffix.lower() == ".json"
and dry_run_path.absolute() != output.absolute()
):
try:
dry_run_path.unlink()
except FileNotFoundError:
pass
else:
cleanup_note = ",已清理 dry-run JSON"
print(
f"已生成: {output}({target_day.isoformat()},收到消息 {len(rows)} 条,"
f"模型 {model}{cleanup_note})"
)
return 0
except SummaryError as error:
print(f"生成失败: {error}", file=sys.stderr)
return 1
except OSError as error:
print(f"写入总结或清理 dry-run 失败: {type(error).__name__}", file=sys.stderr)
return 1
def main():
parser = argparse.ArgumentParser(
prog="lark_snooper.py", description="LarkAgentX 历史同步与 EFundGPT 日度总结"
)
subparsers = parser.add_subparsers(dest="cmd", required=True)
web = subparsers.add_parser("web", help="打开本机会话搜索与忽略列表管理页")
web.add_argument("--port", type=int, default=8765, help="本机监听端口,默认 8765")
web.add_argument("--config", default="config.yaml", help="要维护的 YAML 配置路径")
web.add_argument("--no-browser", action="store_true", help="不自动打开浏览器")
web.set_defaults(fn=cmd_web)
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("--days", type=int, help="入库最近 N 天消息(含今天),与 --date 互斥")
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("--force", action="store_true", help="忽略本地同步进度,强制重新拉取")
history.add_argument("--json", action="store_true")
history.add_argument("--config", help="YAML 配置路径;默认读取当前目录 config.yaml")
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("--force-fetch", action="store_true", help="即使本地已有数据也强制重新拉取")
summarize.add_argument("--config", help="YAML 配置路径;默认读取当前目录 config.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()