Files
Lark-Snooper/sync_monthly.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

135 lines
4.6 KiB
Python
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
"""按月批量同步飞书历史消息到本地库,支持持续往前推进。"""
import argparse
import sys
import time
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from larkx.auth import LarkAuth
from snooper_client import SnifferLarkClient as LarkClient
from snooper_history import HistoryError, _feed_chats, sync_all_chats_for_day
from snooper_storage import SnifferStorage as Storage
from snooper_summary import load_config, resolve_chat_rules
def month_range(year: int, month: int):
"""返回该月第一天和下个月第一天的 date。"""
start = datetime(year, month, 1).date()
if month == 12:
end = datetime(year + 1, 1, 1).date()
else:
end = datetime(year, month + 1, 1).date()
return start, end
def sync_one_month(client, storage, chats, exclude_chat_ids, year, month, batch_size, force):
tz = ZoneInfo("Asia/Shanghai")
start, end = month_range(year, month)
today = datetime.now(tz).date()
if end > today:
end = today + timedelta(days=1)
total = {
"chats": 0, "scanned": 0, "empty": 0, "matched": 0,
"saved": 0, "failed": 0, "requests": 0, "skipped": 0,
}
# 倒序同步:从月末/今天往月初推进,利用断点续传避免重复扫描
current = end - timedelta(days=1)
while current >= start:
day_start = int(datetime.combine(current, datetime.min.time(), tzinfo=tz).timestamp())
day_end = day_start + 86400
if not force and storage.has_messages_for_day(day_start, day_end):
print(
f" {current.isoformat()}: 本地已有数据,跳过",
flush=True,
)
current -= timedelta(days=1)
continue
stats = sync_all_chats_for_day(
client,
storage,
current,
tz,
batch_size=batch_size,
exclude_chat_ids=exclude_chat_ids,
force=force,
chats=chats,
)
for key in total:
total[key] += stats[key]
print(
f" {current.isoformat()}: 消息 {stats['matched']} 条,"
f"写入 {stats['saved']} 条,跳过 {stats['skipped']} 会话,"
f"请求 {stats['requests']} 次",
flush=True,
)
current -= timedelta(days=1)
return total
def main():
parser = argparse.ArgumentParser(description="按月同步历史消息,自动逐月往前推进")
parser.add_argument("--months", type=int, default=1, help="同步多少个月(默认 1)")
parser.add_argument("--start-month", help="起始月份 YYYY-MM,默认当前月")
parser.add_argument("--batch-size", type=int, default=200)
parser.add_argument("--force", action="store_true", help="忽略本地进度强制重拉")
parser.add_argument("--config", help="YAML 配置路径")
args = parser.parse_args()
if args.months < 1:
print("--months 必须大于等于 1", file=sys.stderr)
return 2
tz = ZoneInfo("Asia/Shanghai")
if args.start_month:
try:
start_dt = datetime.strptime(args.start_month, "%Y-%m")
except ValueError:
print("--start-month 格式应为 YYYY-MM", file=sys.stderr)
return 2
else:
start_dt = datetime.now(tz)
config = load_config(args.config)
exclude_chat_ids, _ = resolve_chat_rules(config)
client = LarkClient(LarkAuth())
storage = Storage()
print("正在枚举会话列表...", flush=True)
chats = list(_feed_chats(client, page_size=50))
print(f"共 {len(chats)} 个会话\n", flush=True)
for i in range(args.months):
year = start_dt.year
month = start_dt.month - i
while month < 1:
month += 12
year -= 1
print(f"开始同步 {year}-{month:02d} ...", flush=True)
started = time.time()
try:
stats = sync_one_month(
client, storage, chats, exclude_chat_ids,
year, month, args.batch_size, args.force,
)
except HistoryError as error:
print(f"{year}-{month:02d} 同步失败: {error}", file=sys.stderr)
return 1
elapsed = time.time() - started
print(
f"{year}-{month:02d} 完成: 消息 {stats['matched']} 条,"
f"写入 {stats['saved']} 条,跳过 {stats['skipped']} 会话,"
f"失败 {stats['failed']} 会话,请求 {stats['requests']} 次,"
f"耗时 {elapsed:.0f} 秒\n",
flush=True,
)
return 0
if __name__ == "__main__":
sys.exit(main())