是否考虑猎头功能暂时隐藏
This commit is contained in:
+183
-26
@@ -7,6 +7,7 @@ Boss 激活自动化模块(单机功能,低痕迹 CDP 版)
|
||||
status-read=[已读] / status-delivery=[送达])与预览文本 .last-msg-text;
|
||||
- 点击联系人后右侧 .chat-conversation 渲染 .message-content,
|
||||
消息条目 li.message-item(我发出的带 .item-myself),正文 .text-content;
|
||||
- 输入:div#chat-input[contenteditable=true](.message-controls 内,非 textarea);
|
||||
- 发送:button.btn-send。
|
||||
合成 el.click() 对列表项无效,必须 Input.dispatchMouseEvent 可信点击。
|
||||
"""
|
||||
@@ -31,6 +32,14 @@ STATUS_MAP = {
|
||||
}
|
||||
# 视为"对方未读"的状态([送达]=对方还没看;页面若出现字面[未读]同样命中)
|
||||
UNREAD_STATUS = {"送达", "未读"}
|
||||
# 视为"已读"的状态
|
||||
READ_STATUS = {"已读"}
|
||||
# 消息状态过滤选项:值 → 允许通过的状态集合(None=不限)
|
||||
STATUS_FILTERS = {
|
||||
"unread": UNREAD_STATUS,
|
||||
"read": READ_STATUS,
|
||||
"all": None,
|
||||
}
|
||||
|
||||
# 读取左侧联系人列表(实测 DOM)
|
||||
_LIST_JS = """(() => [...new Set([...document.querySelectorAll('.friend-content-warp')]
|
||||
@@ -62,7 +71,7 @@ _LAST_MINE_JS = """(() => {
|
||||
return el ? el.innerText.trim() : '';
|
||||
})()"""
|
||||
|
||||
# 发送按钮坐标(实测:button.btn-send)
|
||||
# 发送按钮坐标(实测:button.btn-send,每次实时计算不缓存)
|
||||
_SEND_BTN_JS = """(() => {
|
||||
const b = document.querySelector('button.btn-send');
|
||||
if (!b || b.offsetHeight <= 0) return null;
|
||||
@@ -71,16 +80,92 @@ _SEND_BTN_JS = """(() => {
|
||||
disabled: !!b.disabled});
|
||||
})()"""
|
||||
|
||||
# 输入框定位(实测:聊天页真实输入框是 contenteditable 的 div#chat-input,
|
||||
# 位于 .message-controls > .chat-editor > .editor-container;
|
||||
# 页面上另有 0×0 的 textarea.input 属无关隐藏元素,不作首选;坐标每次实时计算)
|
||||
_INPUT_BOX_JS = """(() => {
|
||||
const ta = document.querySelector('#chat-input')
|
||||
|| document.querySelector('.chat-conversation [contenteditable="true"]')
|
||||
|| document.querySelector('.editor-container [contenteditable="true"]')
|
||||
|| [...document.querySelectorAll('[contenteditable="true"]')]
|
||||
.find(e => e.offsetHeight > 0)
|
||||
|| null;
|
||||
if (!ta) return null;
|
||||
const r = ta.getBoundingClientRect();
|
||||
return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2,
|
||||
visible: r.width > 0 && r.height > 0,
|
||||
kind: ta.tagName.toLowerCase()});
|
||||
})()"""
|
||||
|
||||
# 输入框不可见时的 JS 聚焦兜底(可信 insertText 只认焦点,不认尺寸)
|
||||
_FOCUS_INPUT_JS = """(() => {
|
||||
const ta = document.querySelector('#chat-input')
|
||||
|| document.querySelector('.chat-conversation [contenteditable="true"]')
|
||||
|| document.querySelector('.editor-container [contenteditable="true"]')
|
||||
|| [...document.querySelectorAll('[contenteditable="true"]')]
|
||||
.find(e => e.offsetHeight > 0)
|
||||
|| null;
|
||||
if (!ta) return false;
|
||||
ta.focus();
|
||||
return document.activeElement === ta;
|
||||
})()"""
|
||||
|
||||
# 左侧列表滚动(加载更多联系人)
|
||||
# 步长动态计算:取滚动容器自身可视高度的 80%(不同分辨率/缩放下均不会跳过头)
|
||||
_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;
|
||||
el.scrollTop += Math.max(240, Math.round(el.clientHeight * 0.8));
|
||||
return el.scrollTop;
|
||||
})()"""
|
||||
|
||||
# 按姓名在当前 DOM 重取联系人最新可点坐标(发送后列表会重排,快照坐标必失效;
|
||||
# inView=false 表示元素在可视区外,可信点击会落空,必须先滚入视口;
|
||||
# 可视范围动态取自滚动容器自身的 rect(顶部自动避开搜索栏/标签头,底部取容器高度),
|
||||
# 不依赖窗口分辨率,任何屏幕/缩放比下均成立;
|
||||
# 传入姓名由 Python 侧 json.dumps 拼接)
|
||||
_LOCATE_ITEM_JS = """(name) => {
|
||||
const lis = [...new Set([...document.querySelectorAll('.friend-content-warp')]
|
||||
.map(w => w.closest('li')).filter(Boolean))];
|
||||
const scroller = document.querySelector('.user-list-content')
|
||||
|| document.querySelector('.user-list');
|
||||
const sr = scroller ? scroller.getBoundingClientRect() : null;
|
||||
const top = sr ? Math.max(0, sr.top) : 0;
|
||||
const bottom = sr ? Math.min(window.innerHeight, sr.bottom) : window.innerHeight;
|
||||
for (const li of lis) {
|
||||
const nm = li.querySelector('.name-text');
|
||||
if (!nm || nm.innerText.trim() !== name) continue;
|
||||
const fc = li.querySelector('.friend-content');
|
||||
const r = fc ? fc.getBoundingClientRect() : null;
|
||||
if (!r || r.height <= 0) continue;
|
||||
return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2,
|
||||
inView: r.y >= top && r.y + r.height <= bottom});
|
||||
}
|
||||
return null;
|
||||
}"""
|
||||
|
||||
# 把指定联系人滚入可视区(列表一次性渲染全部条目,视口外坐标点击必落空)
|
||||
_BRING_INTO_VIEW_JS = """(name) => {
|
||||
const lis = [...new Set([...document.querySelectorAll('.friend-content-warp')]
|
||||
.map(w => w.closest('li')).filter(Boolean))];
|
||||
for (const li of lis) {
|
||||
const nm = li.querySelector('.name-text');
|
||||
if (!nm || nm.innerText.trim() !== name) continue;
|
||||
li.scrollIntoView({block: 'center'});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}"""
|
||||
|
||||
# 当前会话区头部姓名(点击后校验是否切到目标会话,防发错人)
|
||||
_CONV_NAME_JS = """(() => {
|
||||
const el = document.querySelector('.chat-conversation .top-info-content .name-text')
|
||||
|| document.querySelector('.chat-conversation .name-text');
|
||||
return el ? el.innerText.trim() : '';
|
||||
})()"""
|
||||
|
||||
|
||||
def similarity(a: str, b: str) -> float:
|
||||
"""两段文本的相似度(0~1,difflib 序列比对)"""
|
||||
@@ -110,7 +195,8 @@ class Activator:
|
||||
# 启停控制
|
||||
# ------------------------------------------------------------------
|
||||
def start(self, match_text: str, threshold: float, reply_message: str,
|
||||
max_count: int = 20, dry_run: bool = False) -> None:
|
||||
max_count: int = 20, dry_run: bool = False,
|
||||
status_filter: str = "unread") -> None:
|
||||
if self.is_running:
|
||||
logger.warning("已有激活任务在运行")
|
||||
return
|
||||
@@ -119,13 +205,16 @@ class Activator:
|
||||
self.reply_message = reply_message.strip()
|
||||
self.max_count = max_count
|
||||
self.dry_run = dry_run
|
||||
# 消息状态过滤(非法取值回退默认"仅未读",与原行为一致)
|
||||
self.status_filter = status_filter if status_filter in STATUS_FILTERS else "unread"
|
||||
|
||||
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%},"
|
||||
logger.success(f"Boss 激活任务已启动(状态过滤={self.status_filter},"
|
||||
f"阈值 {self.threshold:.0%},"
|
||||
f"上限 {self.max_count},试跑={self.dry_run})")
|
||||
|
||||
def stop(self) -> None:
|
||||
@@ -147,6 +236,9 @@ class Activator:
|
||||
# ------------------------------------------------------------------
|
||||
def _run(self):
|
||||
processed: set[str] = set()
|
||||
# 本次任务已发送过的联系人姓名(发送后列表重排、预览变化,
|
||||
# 同一人会被当成“新联系人”重新出现,按姓名排除防重复发送)
|
||||
self._sent_names: set[str] = set()
|
||||
try:
|
||||
self.manager.ensure_browser_started()
|
||||
self._tab = self.cdp.open_tab(CHAT_PAGE)
|
||||
@@ -160,7 +252,8 @@ class Activator:
|
||||
break
|
||||
items = self._read_list()
|
||||
candidates = [it for it in items
|
||||
if self._item_key(it) not in processed]
|
||||
if self._item_key(it) not in processed
|
||||
and (it.get("name") or "") not in self._sent_names]
|
||||
logger.debug(f"联系人列表读取:共 {len(items)} 条,待处理 {len(candidates)} 条")
|
||||
if not candidates:
|
||||
no_new += 1
|
||||
@@ -218,6 +311,50 @@ class Activator:
|
||||
"""联系人去重键:姓名 + 缩略预览"""
|
||||
return f"{it.get('name', '')}|{it.get('preview', '')[:20]}"
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 实时定位与会话校验(防点错人/读旧会话)
|
||||
# ------------------------------------------------------------------
|
||||
def _locate_fresh(self, name: str) -> dict | None:
|
||||
"""按姓名在当前 DOM 重取最新可点坐标与可视状态。
|
||||
列表在发送后会重排,快照坐标不可信,每次点击前必须重取。"""
|
||||
expr = f"({_LOCATE_ITEM_JS})({json.dumps(name)})"
|
||||
raw = self._sess.eval_js(expr)
|
||||
if not raw:
|
||||
return None
|
||||
return json.loads(raw)
|
||||
|
||||
def _bring_into_view(self, name: str) -> bool:
|
||||
"""把联系人滚入可视区(列表全量渲染,视口外点击必落空)"""
|
||||
expr = f"({_BRING_INTO_VIEW_JS})({json.dumps(name)})"
|
||||
return self._sess.eval_js(expr) is True
|
||||
|
||||
def _conv_name(self) -> str:
|
||||
"""当前会话区头部姓名"""
|
||||
return (self._sess.eval_js(_CONV_NAME_JS) or "").strip()
|
||||
|
||||
def _enter_conversation(self, name: str) -> bool:
|
||||
"""点击进入目标会话并校验切换成功(最多 3 次)。
|
||||
视口外的联系人先滚入可视区再点击;
|
||||
校验不通过绝不允许后续读消息/发送,从根源上防发错人。"""
|
||||
for attempt in range(3):
|
||||
loc = self._locate_fresh(name)
|
||||
if not loc:
|
||||
logger.debug(f"当前列表找不到联系人(第{attempt + 1}次):{name}")
|
||||
return False
|
||||
if not loc.get("inView"):
|
||||
# 视口外:滚入可视区后重取坐标(滚动会改变所有条目坐标)
|
||||
self._bring_into_view(name)
|
||||
time.sleep(random.uniform(0.6, 1.0))
|
||||
loc = self._locate_fresh(name) or loc
|
||||
self._sess.human_click(loc["x"], loc["y"])
|
||||
time.sleep(random.uniform(1.8, 2.8))
|
||||
cur = self._conv_name()
|
||||
if cur == name:
|
||||
return True
|
||||
logger.warning(f"会话未切到目标(第{attempt + 1}次,当前={cur or '空'}):{name}")
|
||||
time.sleep(random.uniform(0.8, 1.5))
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 单联系人处理:未读过滤 → 进入会话 → 最后一条消息 → 相似度 → 发送
|
||||
# ------------------------------------------------------------------
|
||||
@@ -227,15 +364,19 @@ class Activator:
|
||||
self.stats["scanned"] += 1
|
||||
self.stats["current"] = f"查看:{name}({status or '无状态'})"
|
||||
|
||||
# 条件1:最后一条消息必须是未读([已读]/对方发来的消息直接跳过)
|
||||
if status not in UNREAD_STATUS:
|
||||
# 条件1:最后一条消息状态须符合所选过滤(仅未读/仅已读/不限)
|
||||
allowed = STATUS_FILTERS[self.status_filter]
|
||||
if allowed is not None and status not in allowed:
|
||||
self.stats["skipped"] += 1
|
||||
logger.debug(f"状态[{status or '无'}]非未读,跳过:{name}")
|
||||
logger.debug(f"状态[{status or '无'}]不符合所选过滤"
|
||||
f"({self.status_filter}),跳过:{name}")
|
||||
return
|
||||
|
||||
# 条件2:点击进入会话,读取真实消息内容
|
||||
self._sess.human_click(item["x"], item["y"])
|
||||
time.sleep(random.uniform(1.8, 2.8))
|
||||
# 条件2:点击进入会话(实时重取坐标 + 校验会话切换,防点错人/读旧会话)
|
||||
if not self._enter_conversation(name):
|
||||
self.stats["skipped"] += 1
|
||||
logger.warning(f"无法进入目标会话,跳过:{name}")
|
||||
return
|
||||
last_msg = (self._sess.eval_js(_LAST_MINE_JS) or "").strip()
|
||||
if not last_msg:
|
||||
# 会话里没读到我发出的消息时退回缩略预览
|
||||
@@ -262,32 +403,48 @@ class Activator:
|
||||
|
||||
if self._send_reply(name):
|
||||
self.stats["sent"] += 1
|
||||
self._sent_names.add(name)
|
||||
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:
|
||||
# 输入框(会话打开后异步渲染,实测可能延迟 10s+,需充分等待)
|
||||
input_info = None
|
||||
for _ in range(15):
|
||||
if self._should_stop():
|
||||
return False
|
||||
input_info = self._sess.eval_js(_INPUT_BOX_JS)
|
||||
if input_info:
|
||||
break
|
||||
time.sleep(1)
|
||||
if not input_xy:
|
||||
if not input_info:
|
||||
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))
|
||||
p = json.loads(input_info)
|
||||
# 发送前二次确认:输入框可能等了十几秒才出现,期间会话若已变化,
|
||||
# 此处不拦就会把消息发到错误的人(防发错人最后一道闸)
|
||||
cur = self._conv_name()
|
||||
if cur and cur != name:
|
||||
logger.warning(f"发送前发现会话已变化(当前={cur}),放弃发送:{name}")
|
||||
self.stats["skipped"] += 1
|
||||
return False
|
||||
if p.get("visible"):
|
||||
# 可见:可信点击实时计算的坐标中心聚焦
|
||||
self._sess.human_click(p["x"], p["y"])
|
||||
time.sleep(random.uniform(0.4, 0.8))
|
||||
else:
|
||||
# 0×0 隐藏输入框(新版页面实测存在):JS 聚焦,
|
||||
# 后续 Input.insertText 仍为浏览器级可信输入
|
||||
focused = self._sess.eval_js(_FOCUS_INPUT_JS)
|
||||
if not focused:
|
||||
logger.warning(f"输入框无法聚焦,跳过:{name}")
|
||||
self.stats["skipped"] += 1
|
||||
return False
|
||||
time.sleep(random.uniform(0.3, 0.6))
|
||||
|
||||
# 可信文本输入(浏览器级 input 事件,与真人键入无异)
|
||||
self._sess.call("Input.insertText", {"text": self.reply_message})
|
||||
|
||||
Reference in New Issue
Block a user