""" 聊天记录查看工具 用法: python view_chats.py # 列出所有客户 python view_chats.py <客户ID> # 查看某客户的全部对话 python view_chats.py <客户ID> --today # 只看今天 python view_chats.py --search <关键词> # 全文搜索 """ import sys import argparse from chat_log_db import get_customers, get_conversation, get_conversation_today, search_messages # ANSI 颜色 GREEN = "\033[92m" BLUE = "\033[94m" YELLOW = "\033[93m" GRAY = "\033[90m" RESET = "\033[0m" BOLD = "\033[1m" def list_customers(): customers = get_customers(limit=200) if not customers: print("暂无聊天记录") return print(f"\n{BOLD}{'='*60}{RESET}") print(f"{BOLD} 客户聊天记录总览 共 {len(customers)} 位客户{RESET}") print(f"{BOLD}{'='*60}{RESET}") print(f" {'客户ID':<22} {'昵称':<12} {'平台':<15} {'消息数':>6} {'最后联系'}") print(f" {'-'*22} {'-'*12} {'-'*15} {'-'*6} {'-'*19}") for c in customers: cid = c["customer_id"][:20] name = (c["customer_name"] or "未知")[:10] plat = (c["platform"] or "未知")[:13] total = c["total_msgs"] last = c["last_time"][:16] print(f" {YELLOW}{cid:<22}{RESET} {name:<12} {GRAY}{plat:<15}{RESET} {total:>6}条 {last}") print(f"\n{GRAY}查看某客户对话:python view_chats.py <客户ID>{RESET}\n") def show_conversation(customer_id: str, today_only: bool = False): if today_only: records = get_conversation_today(customer_id) label = "今日对话" else: records = get_conversation(customer_id, limit=300) label = "全部对话" if not records: print(f" {GRAY}暂无记录{RESET}") return print(f"\n{BOLD}{'='*60}{RESET}") print(f"{BOLD} 客户:{customer_id} {label} 共 {len(records)} 条{RESET}") print(f"{BOLD}{'='*60}{RESET}\n") last_date = "" for r in records: ts = r["timestamp"] date = ts[:10] time = ts[11:16] msg = r["message"] direction = r["direction"] if date != last_date: print(f" {GRAY}── {date} ──────────────────────────────{RESET}") last_date = date if direction == "in": # 客户消息,左对齐蓝色 print(f" {GRAY}{time}{RESET} {BLUE}【客户】{RESET} {msg}") else: # 客服回复,右对齐绿色 print(f" {GRAY}{time}{RESET} {GREEN}【客服】{RESET} {msg}") print() def show_search(keyword: str): results = search_messages(keyword, limit=50) if not results: print(f" 未找到包含"{keyword}"的消息") return print(f"\n{BOLD}搜索:"{keyword}" 共 {len(results)} 条结果{RESET}\n") for r in results: direction = "客户" if r["direction"] == "in" else "客服" color = BLUE if r["direction"] == "in" else GREEN print(f" {GRAY}{r['timestamp'][:16]}{RESET} {YELLOW}{r['customer_id'][:20]}{RESET} {color}[{direction}]{RESET} {r['message']}") print() def main(): parser = argparse.ArgumentParser( description="查看按用户分开的聊天记录", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__, ) parser.add_argument("customer_id", nargs="?", help="客户ID(不填则列出所有客户)") parser.add_argument("--today", action="store_true", help="只显示今天的对话") parser.add_argument("--search", metavar="关键词", help="全文搜索所有消息") args = parser.parse_args() if args.search: show_search(args.search) elif args.customer_id: show_conversation(args.customer_id, today_only=args.today) else: list_customers() if __name__ == "__main__": main()