""" Boss 激活自动化模块(单机功能,低痕迹 CDP 版) 目标:对"已沟通但对方未读我消息"的 Boss 补发一条自定义消息,激活会话。 真实页面结构(消息页 /web/geek/chat,已实测): - 左侧列表:.user-list-content > ul > li,内容块 .friend-content(可信点击目标), 姓名 .name-text,缩略消息 .gray.last-msg 内含 i.message-status(class 取值: status-read=[已读] / status-delivery=[送达])与预览文本 .last-msg-text; - 点击联系人后右侧 .chat-conversation 渲染 .message-content, 消息条目 li.message-item(我发出的带 .item-myself),正文 .text-content; - 发送:button.btn-send。 合成 el.click() 对列表项无效,必须 Input.dispatchMouseEvent 可信点击。 """ import difflib import json import random import time import threading from loguru import logger from .cdp_lite import LiteCDP, CDPSession from .manager import BrowserManager # 消息页 CHAT_PAGE = "https://www.zhipin.com/web/geek/chat" # 我发出消息的已读状态(DOM class → 展示文案) STATUS_MAP = { "status-read": "已读", "status-delivery": "送达", } # 视为"对方未读"的状态([送达]=对方还没看;页面若出现字面[未读]同样命中) UNREAD_STATUS = {"送达", "未读"} # 读取左侧联系人列表(实测 DOM) _LIST_JS = """(() => [...new Set([...document.querySelectorAll('.friend-content-warp')] .map(w => w.closest('li')).filter(Boolean))].map(li => { const fc = li.querySelector('.friend-content'); const st = li.querySelector('.message-status'); const lm = li.querySelector('.last-msg-text'); const nm = li.querySelector('.name-text'); const co = li.querySelector('.title-box .name-box'); const r = fc ? fc.getBoundingClientRect() : null; return { name: nm ? nm.innerText.trim() : '', title: co ? co.innerText.replace(/\\s+/g, ' ').trim().slice(0, 40) : '', status: st ? String(st.className) : '', statusText: st ? st.innerText.trim() : '', preview: lm ? lm.innerText.trim() : '', x: r ? Math.round(r.x + r.width / 2) : 0, y: r ? Math.round(r.y + r.height / 2) : 0, visible: !!r && r.height > 0, }; }))()""" # 右侧会话:最后一条"我发出的"消息正文(实测:.message-item.item-myself) _LAST_MINE_JS = """(() => { const items = [...document.querySelectorAll( '.chat-conversation .message-item.item-myself')]; if (!items.length) return ''; const el = items[items.length - 1].querySelector('.text-content'); return el ? el.innerText.trim() : ''; })()""" # 发送按钮坐标(实测:button.btn-send) _SEND_BTN_JS = """(() => { const b = document.querySelector('button.btn-send'); if (!b || b.offsetHeight <= 0) return null; const r = b.getBoundingClientRect(); return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2, disabled: !!b.disabled}); })()""" # 左侧列表滚动(加载更多联系人) _LIST_SCROLL_JS = """(() => { const el = document.querySelector('.user-list-content') || document.querySelector('.user-list') || document.querySelector('.chat-content'); if (!el) return -1; el.scrollTop += 480; return el.scrollTop; })()""" def similarity(a: str, b: str) -> float: """两段文本的相似度(0~1,difflib 序列比对)""" a, b = (a or "").strip(), (b or "").strip() if not a or not b: return 0.0 return difflib.SequenceMatcher(None, a, b).ratio() class Activator: """Boss 激活执行器(可启停,单机功能不依赖云端)""" def __init__(self, manager: BrowserManager): self.manager = manager self.cdp = LiteCDP() self._stop_event = threading.Event() self._thread: threading.Thread | None = None self.is_running = False self.stats = {"scanned": 0, "sent": 0, "skipped": 0, "current": ""} self._tab: dict | None = None self._sess: CDPSession | None = None # ------------------------------------------------------------------ # 启停控制 # ------------------------------------------------------------------ def start(self, match_text: str, threshold: float, reply_message: str, max_count: int = 20, dry_run: bool = False) -> None: if self.is_running: logger.warning("已有激活任务在运行") return self.match_text = match_text.strip() self.threshold = max(0.0, min(1.0, threshold)) self.reply_message = reply_message.strip() self.max_count = max_count self.dry_run = dry_run self._stop_event.clear() self.is_running = True self.stats = {"scanned": 0, "sent": 0, "skipped": 0, "current": "初始化..."} self._thread = threading.Thread(target=self._run, daemon=True) self._thread.start() logger.success(f"Boss 激活任务已启动(阈值 {self.threshold:.0%}," f"上限 {self.max_count},试跑={self.dry_run})") def stop(self) -> None: logger.info("收到停止激活请求...") self._stop_event.set() def _should_stop(self) -> bool: return self._stop_event.is_set() def _sleep(self, min_s: float, max_s: float) -> None: total = random.uniform(min_s, max_s) elapsed = 0.0 while elapsed < total and not self._should_stop(): time.sleep(0.5) elapsed += 0.5 # ------------------------------------------------------------------ # 主循环 # ------------------------------------------------------------------ def _run(self): processed: set[str] = set() try: self.manager.ensure_browser_started() self._tab = self.cdp.open_tab(CHAT_PAGE) time.sleep(8) # 等 SPA 挂载 self._sess = CDPSession(self._tab["webSocketDebuggerUrl"]) no_new = 0 while not self._should_stop(): if self.max_count and self.stats["sent"] >= self.max_count: logger.info(f"已达发送上限({self.max_count}),任务结束") break items = self._read_list() candidates = [it for it in items if self._item_key(it) not in processed] logger.debug(f"联系人列表读取:共 {len(items)} 条,待处理 {len(candidates)} 条") if not candidates: no_new += 1 if no_new >= 3: logger.info("列表已扫完,没有新的联系人") break else: no_new = 0 for it in candidates: if self._should_stop(): break if self.max_count and self.stats["sent"] >= self.max_count: break processed.add(self._item_key(it)) self._handle_item(it) # 下拉加载更多联系人 self._sess.eval_js(_LIST_SCROLL_JS) self._sleep(1.5, 3) except Exception as e: logger.error(f"激活任务异常:{e}") finally: if self._sess: self._sess.close() if self._tab: self.cdp.close_tab(self._tab["id"]) self.is_running = False self.stats["current"] = "已结束" logger.info(f"激活任务结束。扫描 {self.stats['scanned']} 个," f"发送 {self.stats['sent']} 条,跳过 {self.stats['skipped']} 个") # ------------------------------------------------------------------ # 列表读取与状态解析 # ------------------------------------------------------------------ def _read_list(self) -> list[dict]: raw = self._sess.eval_js(_LIST_JS) if isinstance(raw, str): try: raw = json.loads(raw or "[]") except Exception: raw = [] return [it for it in (raw or []) if it.get("visible")] @staticmethod def _item_status(it: dict) -> str: """缩略消息状态文案:优先 class 映射,其次元素文字,兼容字面[未读]/[已读]""" cls = it.get("status") or "" for k, v in STATUS_MAP.items(): if k in cls: return v text = (it.get("statusText") or "").strip("[] ") return text @staticmethod def _item_key(it: dict) -> str: """联系人去重键:姓名 + 缩略预览""" return f"{it.get('name', '')}|{it.get('preview', '')[:20]}" # ------------------------------------------------------------------ # 单联系人处理:未读过滤 → 进入会话 → 最后一条消息 → 相似度 → 发送 # ------------------------------------------------------------------ def _handle_item(self, item: dict) -> None: name = item.get("name") or "未知联系人" status = self._item_status(item) self.stats["scanned"] += 1 self.stats["current"] = f"查看:{name}({status or '无状态'})" # 条件1:最后一条消息必须是未读([已读]/对方发来的消息直接跳过) if status not in UNREAD_STATUS: self.stats["skipped"] += 1 logger.debug(f"状态[{status or '无'}]非未读,跳过:{name}") return # 条件2:点击进入会话,读取真实消息内容 self._sess.human_click(item["x"], item["y"]) time.sleep(random.uniform(1.8, 2.8)) last_msg = (self._sess.eval_js(_LAST_MINE_JS) or "").strip() if not last_msg: # 会话里没读到我发出的消息时退回缩略预览 logger.debug(f"会话内未读到我发出的消息,退回缩略预览:{name}") last_msg = (item.get("preview") or "").strip() if not last_msg: self.stats["skipped"] += 1 logger.warning(f"无法读取最后一条消息,跳过:{name}") return # 条件3:与用户输入文本相似度达标 ratio = similarity(last_msg, self.match_text) logger.info(f"匹配 {ratio:.0%}(阈值 {self.threshold:.0%}):" f"{name} | {last_msg[:50]}") if ratio < self.threshold: self.stats["skipped"] += 1 return if self.dry_run: self.stats["sent"] += 1 logger.success(f"[试跑] 命中将发送:{name}") self._sleep(1, 2) return if self._send_reply(name): self.stats["sent"] += 1 self._sleep(5, 10) def _send_reply(self, name: str) -> bool: """定位输入框聚焦 → 可信输入 → 点发送按钮""" self.stats["current"] = f"发送激活消息:{name}" # 输入框(会话打开后才渲染,需等待) input_xy = None for _ in range(5): input_xy = self._sess.eval_js( "(() => { const ta = document.querySelector('.chat-conversation textarea')" " || document.querySelector('textarea.input');" " if (!ta || ta.offsetHeight <= 0) return null;" " const r = ta.getBoundingClientRect();" " return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2}); })()") if input_xy: break time.sleep(1) if not input_xy: logger.warning(f"未找到可用输入框,跳过:{name}") self.stats["skipped"] += 1 return False p = json.loads(input_xy) self._sess.human_click(p["x"], p["y"]) time.sleep(random.uniform(0.4, 0.8)) # 可信文本输入(浏览器级 input 事件,与真人键入无异) self._sess.call("Input.insertText", {"text": self.reply_message}) time.sleep(random.uniform(0.6, 1.2)) # 点击发送按钮(输入后 disabled 会解除) sent = False for _ in range(3): btn = self._sess.eval_js(_SEND_BTN_JS) if btn: q = json.loads(btn) if not q.get("disabled"): self._sess.human_click(q["x"], q["y"]) sent = True break time.sleep(1) if not sent: # 兜底:可信 Enter 键提交 logger.debug(f"发送按钮不可用,改用 Enter 提交:{name}") self._press_enter() time.sleep(1.5) logger.success(f"[{self.stats['sent'] + 1}] 已发送激活消息:{name}") return True def _press_enter(self) -> None: """可信 Enter 键(提交消息兜底)""" for evt_type in ("rawKeyDown", "keyUp"): self._sess.call("Input.dispatchKeyEvent", { "type": evt_type, "key": "Enter", "code": "Enter", "windowsVirtualKeyCode": 13, "nativeVirtualKeyCode": 13}) time.sleep(0.05)