commit 54490fab9f0d45f6f13f4238f56251bb91385d97 Author: xiaoan Date: Sat Nov 14 22:50:40 2026 +0800 docs: publish bridge with restructured markdown docs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fef1cc9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# 运行时产物 +config.json +*.log +tmp/ +__pycache__/ +*.pyc +*.wav +*.mp3 +*.png + +# 本地敏感信息 +*.env +secrets.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..835da33 --- /dev/null +++ b/README.md @@ -0,0 +1,89 @@ +# Rob for QQ / VX + +把本地已登录的 **QQ**(经 SnowLuma / OneBot v11)和 **微信 4.x PC 版** 接到同一个 +DSH 会话里,让一个角色(这里叫「小小糯」)同时在这两个平台收发文字、语音和表情。 + +- QQ 侧:SnowLuma 提供 OneBot v11 WebSocket,DSH 插件 `dsh-onebot-qq` 直连。 +- 微信侧:没有官方接口,也没有可用的无障碍树,所以由本仓库的 `bridge/` 用 + 「截图 + OCR 读消息、消息注入写消息」的方式模拟真人操作。 +- 两个平台在 `obmux` 里合并成**一个** OneBot 端点,DSH 只连一个地址, + 通过 ID 号段区分来源,于是人格、记忆、上下文天然是同一份。 + +``` + ┌───────────────┐ OneBot ws ┌──────────────┐ + QQ ──────▶│ SnowLuma │◀─────────────▶│ │ + └───────────────┘ │ obmux │◀── OneBot ws ──▶ DSH + │ (bridge/) │ (dsh-onebot-qq) + ┌───────────────┐ 截图 / 注入 │ │ + 微信 ─────▶│ WeChat 4.x PC │◀─────────────▶│ │ + └───────────────┘ └──────────────┘ +``` + +## 目录 + +| 路径 | 作用 | +| --- | --- | +| `bridge/obmux.py` | OneBot 多路复用器:对 DSH 暴露一个 WS,对内接 QQ 与微信 | +| `bridge/wechat_uia.py` | 微信通道:窗口定位、截图、OCR、点击/输入、语音条 | +| `bridge/wx_audio.py` | 把 wav 播到指定音频设备(虚拟声卡回灌用) | +| `bridge/wx_audio_default.py` | 用 IPolicyConfig 切换默认录音设备 | +| `bridge/probe*.py`、`smoke.py`、`voice_*.py` | 手工验证脚本(模拟 OneBot 客户端 / 单测语音链路) | +| `tools/` | 诊断与操作小工具:窗口枚举、截图、消息注入、STT、QQ 推送 | +| `docs/` | 架构、部署、排障、人设与记忆 | + +## 快速开始 + +1. **装依赖**(Windows,Python 3.10): + + ```powershell + pip install -i https://mirrors.aliyun.com/pypi/simple ` + uiautomation pywin32 pyperclip pygetwindow pyautogui comtypes psutil ` + pillow numpy rapidocr_onnxruntime winsdk requests websockets + ``` + +2. **准备配置**:复制 `bridge/config.example.json` 为 `bridge/config.json`, + 改掉 `token`,确认 `qq_url` 指向本机 SnowLuma 的 WS 端口。 + +3. **启动桥接**: + + ```powershell + python bridge/obmux.py + ``` + + 看到下面三行即正常: + + ``` + 微信通道已启动 (hwnd=...) + server listening on 127.0.0.1:3010 + QQ 已连接: ws://127.0.0.1:3001 + ``` + +4. **让 DSH 连过来**:在 DSH 桌面版的 `cordis.patch.yml` 里,把 `dsh-onebot` 的 + `url` 指向 `ws://127.0.0.1:3010`,`accessToken` 填 `bridge/config.json` 里的 + `token`,**并删掉 `accessTokenFile`**(否则插件会优先读那个文件里的 token)。 + +5. 微信窗口保持登录、不要最小化到托盘(托盘状态也能恢复,见排障文档)。 + +## 它能做什么 + +- 文字:收发正常,支持多气泡(模型输出多行 = 多条消息)。 +- 语音:微信侧按「按住右 Alt 录音、松开发送」,把 TTS 生成的 wav 播到虚拟声卡, + 经 RDP 回灌成麦克风,微信就会录成语音条。QQ 侧直接发 silk 语音。 +- 表情:`dsh-meme` 的表情包经 `qq_send_image`(QQ)或图片消息(微信)发出。 +- 图片:入站图片保存到磁盘并把路径交给模型,模型可用 `read_image` 真看图。 + +## 限制(务必先读) + +- 微信 PC 端**没有** API,也没有 UIA 树,一切依赖像素坐标;窗口大小、DPI、 + 缩放变了都要重新标定。 +- 读消息靠 OCR:`rapidocr_onnxruntime` 效果好但慢(1 核 CPU 上约 2.5s/次), + 偶尔仍会认错字。 +- 语音条依赖虚拟声卡 + RDP 音频重定向,链路长,见 `docs/setup.md`。 +- 仅供本地个人使用;不要拿它做群发、营销或任何自动化骚扰。 + +## 文档 + +- [架构与数据流](docs/architecture.md) +- [部署与自启](docs/setup.md) +- [排障手册](docs/troubleshooting.md) +- [人设与记忆](docs/persona.md) diff --git a/bridge/config.example.json b/bridge/config.example.json new file mode 100644 index 0000000..cbc7490 --- /dev/null +++ b/bridge/config.example.json @@ -0,0 +1,25 @@ +{ + "token": "change-me-bridge-token", + "listen_port": 3010, + "qq_url": "ws://127.0.0.1:3001", + "self_id": 1461220927, + "wechat": { + "nickname": "小小糯", + "self_id": 1461220927, + "poll_interval": 2, + "ignored": [ + "腾讯新闻", + "微信团队", + "文件传输助手", + "服务通知", + "订阅号", + "微信支付", + "折叠的群聊" + ], + "allow": [], + "voice": { + "tail_ms": 600, + "pre_ms": 900 + } + } +} diff --git a/bridge/obmux.py b/bridge/obmux.py new file mode 100644 index 0000000..1b615f8 --- /dev/null +++ b/bridge/obmux.py @@ -0,0 +1,248 @@ +"""obmux — OneBot v11 多路复用器. + +DSH 的 dsh-onebot-qq 插件只支持一个 OneBot 端点。obmux 对外暴露一个端点, +内部把 QQ(SnowLuma,WS 客户端)与微信(UIA 通道)合并成同一路事件流: + + DSH plugin ──WS client──▶ obmux :3010 ──WS client──▶ SnowLuma :3001 (QQ) + │ + └── WeChatChannel (UIA) (微信) + +事件:QQ/微信的事件都原样推给 DSH。 +动作:按 user_id / group_id 的号段判断是 QQ 还是微信,分别转发或本地处理。 +""" +from __future__ import annotations + +import asyncio +import itertools +import json +import logging +import os +import time +from pathlib import Path + +from websockets.asyncio.client import connect +from websockets.asyncio.server import serve +from websockets.exceptions import ConnectionClosed, InvalidStatus + +from wechat_uia import WeChatChannel + +BASE = Path(r"C:\Users\GuoAn\.dsh\wechat-bridge") +SNOWLUMA_CFG = Path(r"C:\Users\GuoAn\Desktop\SnowLuma-v2.4.0-win-x64\config\onebot_1461220927.json") +LOG_PATH = BASE / "obmux.log" +BASE.mkdir(parents=True, exist_ok=True) + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(message)s", + handlers=[ + logging.FileHandler(LOG_PATH, encoding="utf-8"), + logging.StreamHandler(), + ], +) +log = logging.getLogger("obmux") + +# 微信侧的 id 号段(远离 QQ 的真实号码) +WX_PRIVATE_BASE = 8_000_000_000_000 +WX_GROUP_BASE = 8_100_000_000_000 + + +def snowluma_token() -> str: + try: + raw = json.loads(SNOWLUMA_CFG.read_text(encoding="utf-8")) + except Exception as exc: # noqa: BLE001 + log.warning("读取 SnowLuma 配置失败: %s", exc) + return "" + for key in ("networks", "onebot"): + block = raw.get(key) or {} + for server in block.get("wsServers") or []: + token = server.get("accessToken") or "" + if token: + return token + for server in raw.get("wsServers") or []: + token = server.get("accessToken") or "" + if token: + return token + return "" + + +class Mux: + def __init__(self) -> None: + self.config = json.loads((BASE / "config.json").read_text(encoding="utf-8")) + self.clients: set = set() + self.qq_ws = None + self.qq_ready = asyncio.Event() + self.pending: dict[str, asyncio.Future] = {} + self.pending_events: list[dict] = [] + self.echo_seq = itertools.count(1) + self.wechat = WeChatChannel(self.emit, base_private=WX_PRIVATE_BASE, base_group=WX_GROUP_BASE, + config=self.config.get("wechat") or {}) + self.started_at = time.time() + + # ---------- 广播 ---------- + async def emit(self, event: dict) -> None: + if event.get("post_type") == "message": + text = "".join(seg.get("data", {}).get("text", "") for seg in event.get("message") or []) + log.info("收到消息 %s/%s: %s", event.get("message_type"), event.get("user_id"), text[:60]) + if not self.clients: + # DSH may be restarting: keep recent messages instead of dropping + # them, otherwise everything that arrives during a restart is lost + # (the chat pane has already consumed the text). + if event.get("post_type") == "message": + self.pending_events.append(event) + del self.pending_events[:-20] + log.info("无 DSH 连接,消息已缓存待补发(%d 条): %s", len(self.pending_events), text[:40]) + else: + log.info("无 DSH 连接,事件丢弃: %s", event.get("post_type")) + return + payload = json.dumps(event, ensure_ascii=False) + dead = [] + for ws in list(self.clients): + try: + await ws.send(payload) + except Exception: # noqa: BLE001 + dead.append(ws) + for ws in dead: + self.clients.discard(ws) + + # ---------- QQ 连接 ---------- + async def qq_loop(self) -> None: + url = self.config["qq_url"] + while True: + token = snowluma_token() + headers = {"Authorization": f"Bearer {token}"} if token else {} + try: + async with connect(url, additional_headers=headers, open_timeout=15, + max_size=64 * 1024 * 1024, ping_interval=20) as ws: + self.qq_ws = ws + self.qq_ready.set() + log.info("QQ 已连接: %s", url) + async for raw in ws: + try: + msg = json.loads(raw) + except Exception: # noqa: BLE001 + continue + echo = msg.get("echo") + if echo is not None and echo in self.pending: + fut = self.pending.pop(echo) + if not fut.done(): + fut.set_result(msg) + continue + await self.emit(msg) + except InvalidStatus as exc: + log.warning("QQ 握手被拒(token 可能过期): %s", exc) + except (OSError, ConnectionClosed, asyncio.TimeoutError) as exc: + log.warning("QQ 连接中断: %s", exc) + finally: + self.qq_ws = None + self.qq_ready.clear() + await asyncio.sleep(3) + + async def qq_action(self, action: str, params: dict, timeout: float = 30.0) -> dict: + if self.qq_ws is None: + return {"status": "failed", "retcode": 100, "data": None, "message": "QQ 未连接"} + echo = f"mx-{next(self.echo_seq)}" + fut = asyncio.get_running_loop().create_future() + self.pending[echo] = fut + try: + await self.qq_ws.send(json.dumps({"action": action, "params": params, "echo": echo}, ensure_ascii=False)) + return await asyncio.wait_for(fut, timeout) + except asyncio.TimeoutError: + return {"status": "failed", "retcode": 120, "data": None, "message": "QQ 响应超时"} + finally: + self.pending.pop(echo, None) + + # ---------- DSH 连接 ---------- + def authorized(self, ws) -> bool: + expected = self.config.get("token") or "" + if not expected: + return True + got = "" + try: + got = ws.request.headers.get("Authorization") or "" + except Exception: # noqa: BLE001 + got = "" + return got == f"Bearer {expected}" + + async def dsh_handler(self, ws) -> None: + if not self.authorized(ws): + log.warning("拒绝未授权的 DSH 连接") + await ws.close(code=1008, reason="bad token") + return + self.clients.add(ws) + log.info("DSH 已连接(当前 %d 个)", len(self.clients)) + if self.pending_events: + queued, self.pending_events = self.pending_events, [] + log.info("补发离线期间缓存的消息 %d 条", len(queued)) + for event in queued: + try: + await ws.send(json.dumps(event, ensure_ascii=False)) + except Exception: # noqa: BLE001 + self.pending_events = queued[queued.index(event):] + break + try: + await ws.send(json.dumps({ + "post_type": "meta_event", "meta_event_type": "lifecycle", "sub_type": "connect", + "time": int(time.time()), "self_id": self.config.get("self_id", 1461220927), + }, ensure_ascii=False)) + async for raw in ws: + try: + msg = json.loads(raw) + except Exception: # noqa: BLE001 + continue + asyncio.create_task(self.on_action(ws, msg)) + except ConnectionClosed: + pass + finally: + self.clients.discard(ws) + log.info("DSH 断开(剩余 %d 个)", len(self.clients)) + + def _ids(self, params: dict) -> tuple[int, int]: + def as_int(value): + try: + return int(value) + except (TypeError, ValueError): + text = str(value or "") + if text.startswith("private:"): + return int(text.split(":", 1)[1] or 0) + if text.startswith("group:"): + return int(text.split(":", 1)[1] or 0) + return 0 + return as_int(params.get("user_id")), as_int(params.get("group_id")) + + async def on_action(self, ws, msg: dict) -> None: + action = msg.get("action") or "" + params = msg.get("params") or {} + echo = msg.get("echo") + user_id, group_id = self._ids(params) + if action.startswith("send_msg"): + # chat_id / message_type 判断 + if params.get("message_type") == "private" or str(params.get("chat_id", "")).startswith("private:"): + user_id = user_id or int(str(params.get("chat_id", "")).split(":", 1)[1] or 0) + elif str(params.get("chat_id", "")).startswith("group:"): + group_id = group_id or int(str(params.get("chat_id", "")).split(":", 1)[1] or 0) + + if group_id >= WX_GROUP_BASE or user_id >= WX_PRIVATE_BASE: + result = await self.wechat.handle_action(action, params, user_id, group_id) + else: + result = await self.qq_action(action, params) + if result.get("retcode") not in (0, None): + log.warning("动作 %s user=%s group=%s 失败: %s", action, user_id, group_id, result.get("message")) + elif action.startswith("send"): + log.info("动作 %s → user=%s group=%s ok", action, user_id, group_id) + result["echo"] = echo + try: + await ws.send(json.dumps(result, ensure_ascii=False)) + except Exception: # noqa: BLE001 + pass + + async def run(self) -> None: + await self.wechat.start() + asyncio.create_task(self.qq_loop()) + port = int(self.config.get("listen_port", 3010)) + async with serve(self.dsh_handler, "127.0.0.1", port, max_size=64 * 1024 * 1024): + log.info("obmux 已启动: ws://127.0.0.1:%d", port) + await asyncio.Future() + + +if __name__ == "__main__": + asyncio.run(Mux().run()) diff --git a/bridge/probe.py b/bridge/probe.py new file mode 100644 index 0000000..26ed66f --- /dev/null +++ b/bridge/probe.py @@ -0,0 +1,39 @@ +"""Probe obmux: connect like DSH does, print events, optionally send a WeChat text.""" +import asyncio +import json +import sys +import zlib + +from websockets.asyncio.client import connect + +CONFIG = json.load(open(r"C:\Users\GuoAn\.dsh\wechat-bridge\config.json", encoding="utf-8")) + + +def uid_of(name: str) -> int: + return 8_000_000_000_000 + (zlib.crc32(name.encode("utf-8")) % 1_000_000) + + +async def main() -> None: + target = sys.argv[1] if len(sys.argv) > 1 else "" + text = sys.argv[2] if len(sys.argv) > 2 else "" + headers = {"Authorization": f"Bearer {CONFIG['token']}"} + async with connect(f"ws://127.0.0.1:{CONFIG['listen_port']}", additional_headers=headers) as ws: + print("connected") + if target and text: + payload = { + "action": "send_private_msg", + "params": {"user_id": uid_of(target), "message": [{"type": "text", "data": {"text": text}}]}, + "echo": "probe-1", + } + await ws.send(json.dumps(payload, ensure_ascii=False)) + deadline = asyncio.get_running_loop().time() + 12 + while asyncio.get_running_loop().time() < deadline: + try: + raw = await asyncio.wait_for(ws.recv(), timeout=deadline - asyncio.get_running_loop().time()) + except asyncio.TimeoutError: + break + msg = json.loads(raw) + print("<-", json.dumps(msg, ensure_ascii=False)[:300]) + + +asyncio.run(main()) diff --git a/bridge/probe_voice.py b/bridge/probe_voice.py new file mode 100644 index 0000000..dd6f1d3 --- /dev/null +++ b/bridge/probe_voice.py @@ -0,0 +1,43 @@ +"""Probe obmux with a record segment (voice message) to test the bridge path.""" +import asyncio +import base64 +import json +import sys +import zlib + +from websockets.asyncio.client import connect + +CONFIG = json.load(open(r"C:\Users\GuoAn\.dsh\wechat-bridge\config.json", encoding="utf-8")) +WAV = sys.argv[1] if len(sys.argv) > 1 else r"C:\Users\GuoAn\.dsh\wechat-bridge\tmp\tts_1794648113.wav" +TARGET = sys.argv[2] if len(sys.argv) > 2 else "文件传输助手" + + +def uid_of(name: str) -> int: + return 8_000_000_000_000 + (zlib.crc32(name.encode("utf-8")) % 1_000_000) + + +async def main() -> None: + raw = open(WAV, "rb").read() + b64 = "base64://" + base64.b64encode(raw).decode("ascii") + headers = {"Authorization": f"Bearer {CONFIG['token']}"} + async with connect(f"ws://127.0.0.1:{CONFIG['listen_port']}", additional_headers=headers) as ws: + print("connected, sending voice", len(raw), "bytes") + payload = { + "action": "send_private_msg", + "params": {"user_id": uid_of(TARGET), "message": [{"type": "record", "data": {"file": b64}}]}, + "echo": "probe-voice", + } + await ws.send(json.dumps(payload, ensure_ascii=False)) + deadline = asyncio.get_running_loop().time() + 90 + while asyncio.get_running_loop().time() < deadline: + try: + resp = await asyncio.wait_for(ws.recv(), timeout=deadline - asyncio.get_running_loop().time()) + except asyncio.TimeoutError: + break + msg = json.loads(resp) + print("<-", json.dumps(msg, ensure_ascii=False)[:300]) + if msg.get("echo") == "probe-voice": + break + + +asyncio.run(main()) diff --git a/bridge/smoke.py b/bridge/smoke.py new file mode 100644 index 0000000..e7ea8dd --- /dev/null +++ b/bridge/smoke.py @@ -0,0 +1,44 @@ +"""Smoke test for the WeChat channel: capture, list chats, read pane, send text.""" +import asyncio +import logging +import sys + +sys.path.insert(0, r"C:\Users\GuoAn\.dsh\wechat-bridge") + +from wechat_uia import WeChatChannel # noqa: E402 + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") + + +async def main() -> None: + events: list[dict] = [] + + async def emit(event: dict) -> None: + events.append(event) + print("EVENT:", event["message"][0]["data"]["text"]) + + channel = WeChatChannel(emit, base_private=8_000_000_000_000, base_group=8_100_000_000_000, + config={"self_id": 1461220927, "nickname": "小小糯"}) + channel._ocr = None + from winsdk.windows.globalization import Language + from winsdk.windows.media.ocr import OcrEngine + channel._ocr = OcrEngine.try_create_from_language(Language("zh-Hans-CN")) + channel._ensure_window() + img = await channel.snapshot() + print("window:", channel.hwnd, "image:", None if img is None else img.size) + + rows = await channel.chat_rows(img) + print("chats:", [(r["name"], r["y"]) for r in rows]) + print("title:", await channel.chat_title(img)) + print("badges:", channel.unread_rows(img)) + msgs = await channel.read_pane(img) + print("pane messages:", [(m["who"], m["text"][:30]) for m in msgs]) + + ok = await channel.open_chat("文件传输助手") + print("open 文件传输助手:", ok, "current:", channel.current) + + result = await channel.send_text("文件传输助手", "微信桥测试 ping") + print("send result:", result) + + +asyncio.run(main()) diff --git a/bridge/voice_alt.py b/bridge/voice_alt.py new file mode 100644 index 0000000..c4ba387 --- /dev/null +++ b/bridge/voice_alt.py @@ -0,0 +1,71 @@ +"""Hold Right Alt to record a WeChat voice message while playing a wav.""" +import ctypes +import sys +import time +from ctypes import wintypes + +import win32gui + +sys.path.insert(0, r"C:\Users\GuoAn\.dsh\wechat-bridge") +import wechat_uia as w # noqa: E402 +import wx_audio # noqa: E402 + +user32 = ctypes.WinDLL("user32", use_last_error=True) +VK_RMENU = 0xA5 +KEYEVENTF_KEYUP = 0x0002 +KEYEVENTF_EXTENDEDKEY = 0x0001 + + +class MOUSEINPUT(ctypes.Structure): + _fields_ = [("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD), + ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), + ("dwExtraInfo", ctypes.c_void_p)] + + +class KEYBDINPUT(ctypes.Structure): + _fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), + ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), + ("dwExtraInfo", ctypes.c_void_p)] + + +class _INPUTunion(ctypes.Union): + _fields_ = [("ki", KEYBDINPUT), ("mi", MOUSEINPUT)] + + +class INPUT(ctypes.Structure): + _anonymous_ = ("u",) + _fields_ = [("type", wintypes.DWORD), ("u", _INPUTunion)] + + +def key(vk, up=False): + inp = INPUT() + inp.type = 1 # INPUT_KEYBOARD + flags = KEYEVENTF_EXTENDEDKEY | (KEYEVENTF_KEYUP if up else 0) + inp.u.ki = KEYBDINPUT(vk, 0, flags, 0, None) + return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(INPUT)) + + +def grab(path): + img = w.capture(w_hwnd) + img.save(path) + return img + + +if __name__ == "__main__": + w_hwnd = int(sys.argv[1]) + wav = sys.argv[2] + w.focus_window(w_hwnd) + # focus the input box so the shortcut lands in the chat + w.real_down(w_hwnd, 601, 550) + time.sleep(0.06) + w.real_up() + time.sleep(0.4) + print("alt down", key(VK_RMENU)) + time.sleep(1.0) + grab(r"C:\Users\GuoAn\AppData\Local\Temp\alt_mid.png") + print("playing", wx_audio.play_wav(wav, None, True)) + time.sleep(0.5) + print("alt up", key(VK_RMENU, up=True)) + time.sleep(2.0) + grab(r"C:\Users\GuoAn\AppData\Local\Temp\alt_end.png") + print("done") diff --git a/bridge/voice_dbg.py b/bridge/voice_dbg.py new file mode 100644 index 0000000..7c4e7b8 --- /dev/null +++ b/bridge/voice_dbg.py @@ -0,0 +1,36 @@ +"""Step-by-step diagnostic for the WeChat talk button.""" +import asyncio +import sys + +sys.path.insert(0, r"C:\Users\GuoAn\.dsh\wechat-bridge") +import wechat_uia as w # noqa: E402 +from winsdk.windows.globalization import Language # noqa: E402 +from winsdk.windows.media.ocr import OcrEngine # noqa: E402 + +TMP = r"C:\Users\GuoAn\AppData\Local\Temp" + + +async def main() -> None: + ch = w.WeChatChannel(lambda e: None, 8_000_000_000_000, 8_100_000_000_000) + ch._ocr = OcrEngine.try_create_from_language(Language("zh-Hans-CN")) + ch._ensure_window() + img = await ch.snapshot() + img.save(rf"{TMP}\dbg1.png") + print("step1 title:", await ch.chat_title(img), "input:", await ch.input_text(img)) + mx, my = ch._mic_point(img) + print("mic point", mx, my) + ch._click(ch.hwnd, mx, my) + await asyncio.sleep(0.9) + img2 = await ch.snapshot() + img2.save(rf"{TMP}\dbg2.png") + print("step2 input:", await ch.input_text(img2)) + d = await ch._press_talk() + print("press diff:", d) + img3 = await ch.snapshot() + img3.save(rf"{TMP}\dbg3.png") + print("step3 input:", await ch.input_text(img3)) + w.real_up() + await asyncio.sleep(1.0) + + +asyncio.run(main()) diff --git a/bridge/voice_e2e.py b/bridge/voice_e2e.py new file mode 100644 index 0000000..e599e88 --- /dev/null +++ b/bridge/voice_e2e.py @@ -0,0 +1,91 @@ +"""One-shot end-to-end WeChat voice send (open chat -> talk -> play -> release).""" +import asyncio +import ctypes +import glob +import os +import sys +import time +from ctypes import wintypes + +sys.path.insert(0, r"C:\Users\GuoAn\.dsh\wechat-bridge") +import wechat_uia as w # noqa: E402 +import wx_audio # noqa: E402 +from winsdk.windows.globalization import Language # noqa: E402 +from winsdk.windows.media.ocr import OcrEngine # noqa: E402 + +TMP = r"C:\Users\GuoAn\AppData\Local\Temp" +user32 = ctypes.WinDLL("user32", use_last_error=True) + + +class MOUSEINPUT(ctypes.Structure): + _fields_ = [("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD), + ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), + ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong))] + + +class INPUT(ctypes.Structure): + class _I(ctypes.Union): + _fields_ = [("mi", MOUSEINPUT)] + + _anonymous_ = ("i",) + _fields_ = [("type", wintypes.DWORD), ("i", _I)] + + +def mouse(flag): + inp = INPUT() + inp.type = 0 + inp.mi = MOUSEINPUT(0, 0, 0, flag, 0, None) + return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(INPUT)) + + +async def main(): + wavs = sorted(glob.glob(r"C:\Users\GuoAn\.dsh\wechat-bridge\tmp\tts_*.wav"), key=os.path.getmtime) + wav = wavs[-1] + ch = w.WeChatChannel(lambda e: None, 8_000_000_000_000, 8_100_000_000_000) + ch._ocr = OcrEngine.try_create_from_language(Language("zh-Hans-CN")) + ch._ensure_window() + hwnd = ch.hwnd + print("hwnd", hwnd) + + img = await ch.snapshot() + rows = await ch.chat_rows(img) + target = next((r for r in rows if r["name"] == "文件传输助手"), None) + if not target: + print("row missing", [r["name"] for r in rows]) + return + ch._click(hwnd, min(ch._geo(img)["list_w"] - 20, target["x"] + 10), target["y"]) + await asyncio.sleep(1.4) + img = await ch.snapshot() + img.save(rf"{TMP}\e2e1.png") + print("pane lines:", len(await ch.read_pane(img))) + + for attempt in range(3): + mx, my = ch._mic_point(img) + ch._click(hwnd, mx, my) + await asyncio.sleep(1.0) + img = await ch.snapshot() + txt = await ch.input_text(img) + print("attempt", attempt, "input:", repr(txt)) + if "长按" in txt or "鼠标" in txt: + break + + g = ch._geo(img) + bx = (g["pane_x0"] + g["pane_right"]) // 2 + by = int(g["h"] * 0.86) + print("press at", bx, by) + w.real_down(hwnd, bx, by) + await asyncio.sleep(1.0) + mid = await ch.snapshot() + mid.save(rf"{TMP}\e2e2.png") + print("mid input:", repr(await ch.input_text(mid))) + dur = wx_audio.play_wav(wav, None, True) + print("played", dur) + await asyncio.sleep(1.8) + w.real_up() + await asyncio.sleep(2.0) + img = await ch.snapshot() + img.save(rf"{TMP}\e2e3.png") + print("done") + + +asyncio.run(main()) diff --git a/bridge/voice_run.py b/bridge/voice_run.py new file mode 100644 index 0000000..a703afa --- /dev/null +++ b/bridge/voice_run.py @@ -0,0 +1,49 @@ +"""Send a TTS voice message through WeChat: focus, voice mode, real hold, play, release.""" +import asyncio +import sys +import time + +sys.path.insert(0, r"C:\Users\GuoAn\.dsh\wechat-bridge") +import wechat_uia as w # noqa: E402 +import wx_audio # noqa: E402 +from winsdk.windows.globalization import Language # noqa: E402 +from winsdk.windows.media.ocr import OcrEngine # noqa: E402 + +TMP = r"C:\Users\GuoAn\AppData\Local\Temp" +WAV = sys.argv[1] if len(sys.argv) > 1 else r"C:\Users\GuoAn\.dsh\wechat-bridge\tmp\tts_1794648113.wav" + + +async def main(): + ch = w.WeChatChannel(lambda e: None, 8_000_000_000_000, 8_100_000_000_000) + ch._ocr = OcrEngine.try_create_from_language(Language("zh-Hans-CN")) + ch._ensure_window() + w.focus_window(ch.hwnd) + print("focus fg=", w.user32.GetForegroundWindow()) + img = await ch.snapshot() + print("input:", repr(await ch.input_text(img))) + if not await ch.voice_ready(): + mx, my = ch._mic_point(img) + ch._click(ch.hwnd, mx, my) + await asyncio.sleep(1.0) + img = await ch.snapshot() + print("after mic:", repr(await ch.input_text(img))) + g = ch._geo(img) + bx = (g["pane_x0"] + g["pane_right"]) // 2 + by = int(g["h"] * 0.86) + w.focus_window(ch.hwnd) + w.real_down(ch.hwnd, bx, by) + await asyncio.sleep(0.9) + img = await ch.snapshot() + mid = await ch.input_text(img) + img.save(rf"{TMP}\v_mid.png") + print("mid:", repr(mid)) + await asyncio.to_thread(wx_audio.play_wav, WAV, None, True) + await asyncio.sleep(1.2) + w.real_up() + await asyncio.sleep(2.0) + img = await ch.snapshot() + img.save(rf"{TMP}\v_end.png") + print("end:", repr(await ch.input_text(img))) + + +asyncio.run(main()) diff --git a/bridge/voice_states.py b/bridge/voice_states.py new file mode 100644 index 0000000..053eed8 --- /dev/null +++ b/bridge/voice_states.py @@ -0,0 +1,39 @@ +"""Capture the four states around a WeChat talk-button press.""" +import asyncio +import sys + +sys.path.insert(0, r"C:\Users\GuoAn\.dsh\wechat-bridge") +import wechat_uia as w # noqa: E402 +from winsdk.windows.globalization import Language # noqa: E402 +from winsdk.windows.media.ocr import OcrEngine # noqa: E402 + +TMP = r"C:\Users\GuoAn\AppData\Local\Temp" + + +async def main(): + ch = w.WeChatChannel(lambda e: None, 8_000_000_000_000, 8_100_000_000_000) + ch._ocr = OcrEngine.try_create_from_language(Language("zh-Hans-CN")) + ch._ensure_window() + img = await ch.snapshot() + img.save(rf"{TMP}\s_A.png") + mx, my = ch._mic_point(img) + ch._click(ch.hwnd, mx, my) + await asyncio.sleep(1.0) + img = await ch.snapshot() + img.save(rf"{TMP}\s_B.png") + g = ch._geo(img) + bx = (g["pane_x0"] + g["pane_right"]) // 2 + by = int(g["h"] * 0.86) + w.real_down(ch.hwnd, bx, by) + await asyncio.sleep(1.0) + img = await ch.snapshot() + img.save(rf"{TMP}\s_C.png") + await asyncio.sleep(2.0) + w.real_up() + await asyncio.sleep(2.0) + img = await ch.snapshot() + img.save(rf"{TMP}\s_D.png") + print("saved A-D") + + +asyncio.run(main()) diff --git a/bridge/voice_test.py b/bridge/voice_test.py new file mode 100644 index 0000000..4f0f9d0 --- /dev/null +++ b/bridge/voice_test.py @@ -0,0 +1,60 @@ +"""End-to-end voice test: TTS -> wav -> WeChat voice bubble. + +Usage: python voice_test.py ["文本"] ["联系人"] +""" +from __future__ import annotations + +import asyncio +import json +import sys +import time +from pathlib import Path + +import requests + +BRIDGE = Path(r"C:\Users\GuoAn\.dsh\wechat-bridge") +sys.path.insert(0, str(BRIDGE)) + +import wechat_uia as w # noqa: E402 + +TTS = "http://192.168.1.17:8080/api/tts" + + +def synthesize(text: str) -> Path: + resp = requests.post(TTS, json={"text": text}, timeout=120, + headers={"Content-Type": "application/json"}) + resp.raise_for_status() + out = BRIDGE / "tmp" / f"tts_{int(time.time())}.wav" + out.parent.mkdir(parents=True, exist_ok=True) + out.write_bytes(resp.content) + print("tts bytes:", len(resp.content), "->", out) + return out + + +async def main() -> int: + text = sys.argv[1] if len(sys.argv) > 1 else "你好呀,这是一条测试语音。" + contact = sys.argv[2] if len(sys.argv) > 2 else "Always" + wav = synthesize(text) + + from winsdk.windows.globalization import Language + from winsdk.windows.media.ocr import OcrEngine + + events = [] + + async def emit(ev): + events.append(ev) + + ch = w.WeChatChannel(emit, 8_000_000_000_000, 8_100_000_000_000) + ch._ocr = OcrEngine.try_create_from_language(Language("zh-Hans-CN")) + ch._ensure_window() + if ch.hwnd is None: + print("no main window") + return 2 + print("hwnd", ch.hwnd) + result = await ch.send_voice(contact, str(wav)) + print(json.dumps(result, ensure_ascii=False)) + return 0 if result.get("status") == "ok" else 1 + + +if __name__ == "__main__": + raise SystemExit(asyncio.run(main())) diff --git a/bridge/wechat_uia.py b/bridge/wechat_uia.py new file mode 100644 index 0000000..26c4d47 --- /dev/null +++ b/bridge/wechat_uia.py @@ -0,0 +1,1416 @@ +"""WeChat channel for obmux: message injection (PostMessage) + OCR reading. + +Why this shape: + +* WeChat 4.2's main window is custom drawn. It exposes no UIA tree below the + top-level window (`EnumChildWindows` = 0) and this RDP session has no + foreground window, so `SendInput`/UIA `Invoke` do not work either. But the + window DOES accept posted `WM_CHAR` / `WM_LBUTTONDOWN` messages and + `PrintWindow` gives us a picture. So the channel is: + + send -> click the input box, post WM_CHAR per character, post Enter + read -> PrintWindow -> Windows.Media.Ocr (zh-Hans) -> parse bubbles + watch -> poll the chat list for unread badges, open the chat, diff text + +* OCR of WeChat's 12px UI font is imperfect, so every name goes through a + canonicalisation table (fuzzy match) before it is used as a chat identity. +""" +from __future__ import annotations + +import asyncio +import base64 +import ctypes +import difflib +from ctypes import wintypes +import logging +import re +import time +import zlib +from pathlib import Path +from typing import Any, Awaitable, Callable + +import win32api +import win32gui +import win32process +import win32ui +from PIL import Image, ImageStat +from winsdk.windows.globalization import Language +from winsdk.windows.media.ocr import OcrEngine +from winsdk.windows.storage import FileAccessMode, StorageFile + +log = logging.getLogger("wechat") + +user32 = ctypes.WinDLL("user32", use_last_error=True) + +WM_CHAR = 0x0102 +WM_KEYDOWN = 0x0100 +WM_KEYUP = 0x0101 +WM_MOUSEMOVE = 0x0200 +WM_LBUTTONDOWN = 0x0201 +WM_LBUTTONUP = 0x0202 +MK_LBUTTON = 0x0001 + +VK_RETURN = 0x0D +VK_BACK = 0x08 + +MAIN_CLASS = "Qt51514QWindowIcon" +TMP = Path(r"C:\Users\GuoAn\.dsh\wechat-bridge\tmp") +TMP.mkdir(parents=True, exist_ok=True) + +IGNORED_DEFAULT = ["腾讯新闻", "微信团队", "文件传输助手", "服务通知", "订阅号", "微信支付", "折叠的群聊"] +TIME_RE = re.compile(r"^\d{1,2}\s*[::]\s*\d{2}$") +NOISE_RE = re.compile(r"^[\d::..\-+ ]+$") + +# Windows OCR likes to break a dense CJK glyph into its radicals when the +# rendering is small ("你" -> "亻尔", "掉" -> "扌卓"). These are not real +# characters in chat, so folding them back is safe and fixes most of the +# remaining typos without a second OCR engine. +GLYPH_FIXUPS = { + "亻尔": "你", "亻尔们": "你们", "亻也": "他", "亻门": "们", "亻本": "体", + "扌卓": "掉", "扌我": "找", "扌丁": "打", "扌旨": "指", "扌是": "提", + "氵肖": "消", "氵去": "法", "氵舌": "活", "氵呙": "涡", "氵且": "沮", + "讠兑": "说", "讠己": "记", "讠果": "课", "讠十": "计", "讠人": "认", + "纟工": "红", "纟合": "给", "纟巠": "经", "纟至": "织", + "忄青": "情", "忄夬": "快", "忄曼": "慢", "忄白": "怕", + "牜勿": "物", "犭苗": "猫", "犭句": "狗", "王求": "球", "王里": "理", + "日寸": "时", "日免": "晚", "日乍": "昨", "月半": "胖", "月土": "肚", + "石卒": "碎", "石更": "硬", "禾口": "和", "禾中": "种", "米分": "粉", +} + + +def repair_glyphs(text: str) -> str: + if not text: + return text + for broken, good in GLYPH_FIXUPS.items(): + if broken in text: + text = text.replace(broken, good) + return text + + +# --------------------------------------------------------------------------- win32 +def _main_candidates() -> list[dict]: + out: list[dict] = [] + + def cb(hwnd, _): + try: + if win32gui.GetClassName(hwnd) != MAIN_CLASS: + return True + left, top, right, bottom = win32gui.GetWindowRect(hwnd) + except Exception: + return True + out.append({"hwnd": hwnd, "iconic": bool(win32gui.IsIconic(hwnd)), + "area": (right - left) * (bottom - top)}) + return True + + win32gui.EnumWindows(cb, None) + return out + + +def restore_window(hwnd: int) -> None: + if win32gui.IsIconic(hwnd): + user32.ShowWindow(hwnd, 9) # SW_RESTORE + else: + user32.ShowWindow(hwnd, 5) # SW_SHOW + time.sleep(0.25) + user32.ShowWindow(hwnd, 9) + time.sleep(0.25) + + +def find_main_window() -> int | None: + cands = _main_candidates() + if not cands: + return None + big = [c for c in cands if not c["iconic"] and c["area"] >= 500 * 400] + if big: + big.sort(key=lambda c: -c["area"]) + return big[0]["hwnd"] + # minimised to tray (rect is off-screen); restore the largest candidate + cands.sort(key=lambda c: -c["area"]) + hwnd = cands[0]["hwnd"] + restore_window(hwnd) + return hwnd + + +def capture(hwnd: int) -> Image.Image: + left, top, right, bottom = win32gui.GetWindowRect(hwnd) + w, h = right - left, bottom - top + hwnd_dc = win32gui.GetWindowDC(hwnd) + mfc = win32ui.CreateDCFromHandle(hwnd_dc) + save = mfc.CreateCompatibleDC() + bmp = win32ui.CreateBitmap() + bmp.CreateCompatibleBitmap(mfc, w, h) + save.SelectObject(bmp) + ctypes.windll.user32.PrintWindow(hwnd, save.GetSafeHdc(), 2) + info = bmp.GetInfo() + bits = bmp.GetBitmapBits(True) + img = Image.frombuffer("RGB", (info["bmWidth"], info["bmHeight"]), bits, "raw", "BGRX", 0, 1).copy() + win32gui.DeleteObject(bmp.GetHandle()) + save.DeleteDC() + mfc.DeleteDC() + win32gui.ReleaseDC(hwnd, hwnd_dc) + return img + + +# --------------------------------------------------------------------------- +# real (SendInput) mouse control: WeChat only starts recording when the +# physical left button is down, so pressing the talk area cannot be faked with +# PostMessage. SendInput needs a foreground window, so focus() must run first. +MOUSEEVENTF_LEFTDOWN = 0x0002 +MOUSEEVENTF_LEFTUP = 0x0004 + + +class _MOUSEINPUT(ctypes.Structure): + _fields_ = [("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD), + ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), + ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong))] + + +class _INPUT(ctypes.Structure): + class _I(ctypes.Union): + _fields_ = [("mi", _MOUSEINPUT)] + + _anonymous_ = ("i",) + _fields_ = [("type", wintypes.DWORD), ("i", _I)] + + +def _send_mouse(flag: int) -> int: + inp = _INPUT() + inp.type = 0 + inp.mi = _MOUSEINPUT(0, 0, 0, flag, 0, None) + return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(_INPUT)) + + +def focus_window(hwnd: int) -> bool: + """Make `hwnd` the foreground window (needed before SendInput works).""" + if user32.GetForegroundWindow() == hwnd: + return True + try: + win32gui.ShowWindow(hwnd, 9) # SW_RESTORE + win32gui.BringWindowToTop(hwnd) + user32.SetForegroundWindow(hwnd) + except Exception: + pass + time.sleep(0.2) + return user32.GetForegroundWindow() == hwnd + + +def real_down(hwnd: int, img_x: int, img_y: int) -> bool: + """Move the physical cursor over the window point and press the button.""" + focus_window(hwnd) + left, top, _, _ = win32gui.GetWindowRect(hwnd) + cx, cy = win32gui.ClientToScreen(hwnd, (0, 0)) + ox, oy = cx - left, cy - top + user32.SetCursorPos(cx + (img_x - ox), cy + img_y - oy) + time.sleep(0.15) + return _send_mouse(MOUSEEVENTF_LEFTDOWN) == 1 + + +def real_up() -> bool: + return _send_mouse(MOUSEEVENTF_LEFTUP) == 1 + + +# WeChat's voice button advertises "发语音(按住右alt)", so holding Right Alt +# records and releasing it sends — far more reliable than hitting the circle. +VK_RMENU = 0xA5 +KEYEVENTF_KEYUP = 0x0002 +KEYEVENTF_EXTENDEDKEY = 0x0001 + + +class _KEYBDINPUT(ctypes.Structure): + _fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), + ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), + ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong))] + + +class _INPUTK(ctypes.Structure): + class _I(ctypes.Union): + _fields_ = [("ki", _KEYBDINPUT), ("mi", _MOUSEINPUT)] + + _anonymous_ = ("i",) + _fields_ = [("type", wintypes.DWORD), ("i", _I)] + + +def _send_key(vk: int, up: bool = False) -> int: + inp = _INPUTK() + inp.type = 1 + flags = KEYEVENTF_EXTENDEDKEY | (KEYEVENTF_KEYUP if up else 0) + inp.ki = _KEYBDINPUT(vk, 0, flags, 0, None) + return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(_INPUTK)) + + +def hold_alt(hwnd: int) -> bool: + """Focus the window (with thread attach) and press Right Alt down.""" + focus_window(hwnd) + try: + tid_target = win32process.GetWindowThreadProcessId(hwnd)[0] + tid_self = win32api.GetCurrentThreadId() + user32.AttachThreadInput(tid_self, tid_target, True) + user32.SetForegroundWindow(hwnd) + except Exception: + pass + time.sleep(0.25) + return _send_key(VK_RMENU) == 1 + + +def release_alt() -> bool: + ok = _send_key(VK_RMENU, up=True) == 1 + try: + user32.AttachThreadInput(win32api.GetCurrentThreadId(), + win32api.GetCurrentThreadId(), False) + except Exception: + pass + return ok + + +def cancel_recording(hwnd: int) -> None: + """Throw away the clip WeChat is currently recording. + + WeChat's own hint is 「按下退格键(←)取消」: releasing Alt would *send* the + partial clip instead, which is how a retried voice send ended up as two + bubbles. + """ + try: + post_key(hwnd, VK_BACK) + time.sleep(0.3) + except Exception: + pass + release_alt() + time.sleep(0.4) + + +def client_origin(hwnd: int) -> tuple[int, int]: + left, top, _, _ = win32gui.GetWindowRect(hwnd) + cx, cy = win32gui.ClientToScreen(hwnd, (0, 0)) + return cx - left, cy - top + + +def post_click(hwnd: int, x: int, y: int) -> None: + lp = (y << 16) | (x & 0xFFFF) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp) + user32.PostMessageW(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, lp) + time.sleep(0.03) + user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp) + + +def post_text(hwnd: int, text: str) -> None: + for ch in text: + user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 1) + time.sleep(0.008) + + +def post_key(hwnd: int, vk: int) -> None: + user32.PostMessageW(hwnd, WM_KEYDOWN, vk, 1) + user32.PostMessageW(hwnd, WM_KEYUP, vk, 0xC0000001) + + +def post_down(hwnd: int, x: int, y: int) -> None: + lp = (y << 16) | (x & 0xFFFF) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp) + user32.PostMessageW(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, lp) + + +def post_up(hwnd: int, x: int, y: int) -> None: + lp = (y << 16) | (x & 0xFFFF) + user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp) + + +# --------------------------------------------------------------------------- utils +def similar(a: str, b: str) -> float: + if not a or not b: + return 0.0 + return difflib.SequenceMatcher(None, a, b).ratio() + + +def strip_marks(text: str) -> str: + return re.sub(r"[^\w\u4e00-\u9fff]", "", text) + + +# --------------------------------------------------------------------------- channel +class WeChatChannel: + def __init__(self, emit: Callable[[dict], Awaitable[None]], base_private: int, base_group: int, + config: dict | None = None) -> None: + self.emit = emit + self.base_private = base_private + self.base_group = base_group + cfg = config or {} + self.config = cfg + self.interval = float(cfg.get("poll_interval", 2.0)) + self.ignored = set(cfg.get("ignored", IGNORED_DEFAULT)) + self.allow = set(cfg.get("allow", [])) + self.self_id = int(cfg.get("self_id", 1461220927)) + self.nickname = cfg.get("nickname", "小小糯") + self.lock = asyncio.Lock() + self.ocr_lock = asyncio.Lock() + self.sent_recent: list[tuple[float, str]] = [] + self.voice_ui = False + self.hwnd: int | None = None + self.current: str | None = None + self.seen: dict[str, list[tuple[str, str]]] = {} + self.seen_total: dict[str, int] = {} + self._previews: list[tuple[int, str]] = [] + self.contacts: dict[str, int] = {} + self.canonical: list[str] = [] + self._ocr: Any = None + self._rr: Any = None + self._rr_error = "" + try: # PaddleOCR models on onnxruntime; much better than Windows OCR + from rapidocr_onnxruntime import RapidOCR # type: ignore + + self._rr = RapidOCR() + log.info("OCR 引擎: RapidOCR (PaddleOCR 模型)") + except Exception as exc: # noqa: BLE001 + self._rr = None + self._rr_error = str(exc) + log.warning("RapidOCR 不可用,回退 Windows OCR: %s", exc) + self._msg_seq = 0 + self.fresh = False + + # ---------------------------------------------------------------- lifecycle + async def start(self) -> None: + self._ocr = OcrEngine.try_create_from_language(Language("zh-Hans-CN")) + if self._ocr is None: + raise RuntimeError("Windows OCR 缺少 zh-Hans-CN 语言包") + self._ensure_window() + self.canonical = list(self.ignored) + list(self.allow) + asyncio.create_task(self._poll_loop()) + log.info("微信通道已启动 (hwnd=%s)", self.hwnd) + + def _ensure_window(self) -> int: + hwnd = find_main_window() + if hwnd is None: + raise RuntimeError("没找到微信主窗口(微信 4.x 需要已登录)") + if not win32gui.IsWindowVisible(hwnd): + user32.ShowWindow(hwnd, 9) + time.sleep(0.4) + user32.SetWindowPos(hwnd, 0, 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040) + time.sleep(0.4) + self.hwnd = hwnd + return hwnd + + async def _poll_loop(self) -> None: + while True: + try: + await self.tick() + except Exception as exc: # noqa: BLE001 + log.warning("轮询失败: %s", exc) + await asyncio.sleep(self.interval) + + # ---------------------------------------------------------------- capture / ocr + async def snapshot(self) -> Image.Image | None: + if self.hwnd is None or not win32gui.IsWindow(self.hwnd): + try: + self._ensure_window() + except Exception as exc: # noqa: BLE001 + log.warning("微信窗口不可用: %s", exc) + return None + elif not win32gui.IsWindowVisible(self.hwnd): + try: + self._ensure_window() + except Exception as exc: # noqa: BLE001 + log.warning("微信窗口无法显示: %s", exc) + return None + img = await asyncio.to_thread(capture, self.hwnd) + if ImageStat.Stat(img.convert("L")).stddev[0] >= 3.0: + return img + for _ in range(3): + user32.ShowWindow(self.hwnd, 9) + user32.SetWindowPos(self.hwnd, 0, 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040) + user32.PostMessageW(self.hwnd, WM_MOUSEMOVE, 0, (300 << 16) | 400) + await asyncio.sleep(0.5) + img = await asyncio.to_thread(capture, self.hwnd) + if ImageStat.Stat(img.convert("L")).stddev[0] >= 3.0: + return img + log.warning("截图仍然空白(窗口可能被隐藏)") + return None + + async def ocr(self, img: Image.Image, crop: tuple[int, int, int, int] | None = None, + scale: float = 3.0) -> list[dict]: + ox, oy = (crop[0], crop[1]) if crop else (0, 0) + if crop: + img = img.crop(crop) + if self._rr is not None: + lines = await asyncio.to_thread(self._ocr_rr, img, scale) + if lines: + # _ocr_rr already reports coordinates in the un-scaled crop + return [{ + "text": line["text"].replace(" ", ""), + "x": ox + int(line["x"]), + "y": oy + int(line["y"]), + "w": int(line["w"]), + "h": int(line["h"]), + } for line in lines] + up = img.convert("RGB").resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS) + import io + buf = io.BytesIO() + up.save(buf, format="PNG") + lines = await self._ocr_bytes(buf.getvalue()) + return [{ + "text": line["text"].replace(" ", ""), + "x": ox + int(line["x"] / scale), + "y": oy + int(line["y"] / scale), + "w": int(line["w"] / scale), + "h": int(line["h"] / scale), + } for line in lines] + + def _ocr_rr(self, img: Image.Image, scale: float) -> list[dict]: + """RapidOCR (PaddleOCR models on onnxruntime) - far better on CJK. + + Windows OCR splits dense glyphs into radicals on 12px text ("你" -> + "亻尔"); PaddleOCR's recogniser does not. Returns coordinates in the + *unscaled* crop space so callers stay engine agnostic. + """ + import numpy as np + + rgb = img.convert("RGB") + if scale != 1.0: + rgb = rgb.resize((max(8, int(rgb.width * scale)), max(8, int(rgb.height * scale))), + Image.LANCZOS) + arr = np.asarray(rgb)[:, :, ::-1] # RapidOCR expects BGR + result, _ = self._rr(arr) + out: list[dict] = [] + for box, text, score in result or []: + if not text or float(score) < 0.45: + continue + xs = [float(p[0]) for p in box] + ys = [float(p[1]) for p in box] + out.append({ + "text": str(text), + "x": min(xs) / scale, + "y": min(ys) / scale, + "w": (max(xs) - min(xs)) / scale, + "h": (max(ys) - min(ys)) / scale, + "score": float(score), + }) + return out + + async def _ocr_bytes(self, data: bytes) -> list[dict]: + """Recognise text straight from memory. + + Going through a temp file used to leave the file locked while WinRT + still had the stream open, which produced both `WinError -2003292336` + (component lookup failed) and `PermissionError` on unlink. + """ + from winsdk.windows.graphics.imaging import BitmapDecoder + from winsdk.windows.storage.streams import DataWriter, InMemoryRandomAccessStream + + stream = InMemoryRandomAccessStream() + writer = DataWriter(stream) + writer.write_bytes(data) + await writer.store_async() + writer.detach_stream() + stream.seek(0) + decoder = await BitmapDecoder.create_async(stream) + bitmap = await decoder.get_software_bitmap_async() + stream.close() + result = None + for attempt in range(3): + try: + async with self.ocr_lock: + result = await self._ocr.recognize_async(bitmap) + break + except OSError as exc: # E_ABORT when two recognitions overlap + log.debug("OCR 重试 %s: %s", attempt + 1, exc) + await asyncio.sleep(0.15) + if result is None: + raise RuntimeError("OCR 失败") + rows = [] + for line in result.lines: + words = list(line.words) + if not words: + continue + x0 = min(w.bounding_rect.x for w in words) + y0 = min(w.bounding_rect.y for w in words) + x1 = max(w.bounding_rect.x + w.bounding_rect.width for w in words) + y1 = max(w.bounding_rect.y + w.bounding_rect.height for w in words) + rows.append({"text": line.text, "x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0}) + return rows + + # ---------------------------------------------------------------- geometry + @staticmethod + def _geo(img: Image.Image) -> dict: + w, h = img.size + list_w = int(w * 0.35) + return {"w": w, "h": h, "list_w": list_w, "pane_x0": list_w + 4, + "pane_right": w - 10, "top": int(h * 0.13), "bottom": int(h * 0.77)} + + # ---------------------------------------------------------------- names + def canonical_name(self, raw: str) -> str: + best, score = raw, 0.0 + for known in self.canonical: + ratio = similar(raw, known) + if ratio > score: + best, score = known, ratio + if score >= 0.6: + return best + if raw not in self.canonical and len(raw) >= 2: + self.canonical.append(raw) + return raw + + # ---------------------------------------------------------------- chat list + def avatar_centers(self, img: Image.Image) -> list[int]: + """Chat rows are reliably found by their avatars (a square block of high contrast in the list).""" + g = self._geo(img) + x0, x1 = int(g["w"] * 0.10), int(g["w"] * 0.155) + y0, y1 = g["top"], int(g["h"] * 0.93) + band = img.crop((x0, y0, x1, y1)).convert("L") + px = band.load() + width = band.width + flags = [] + for y in range(band.height): + values = [px[x, y] for x in range(width)] + flags.append(max(values) - min(values) > 45) + centers: list[int] = [] + inside = False + start = 0 + for y, flag in enumerate(flags): + if flag and not inside: + inside, start = True, y + elif not flag and inside: + inside = False + if y - start >= 18: + centers.append(y0 + (start + y) // 2) + if inside and len(flags) - start >= 18: + centers.append(y0 + (start + len(flags)) // 2) + return centers + + async def chat_rows(self, img: Image.Image) -> list[dict]: + centers = self.avatar_centers(img) + rows = [] + x0, x1 = int(img.width * 0.13), int(img.width * 0.35) + for cy in centers: + lines = await self.ocr(img, (x0, max(0, cy - 24), x1, min(img.height, cy + 18)), 2.0) + best = None + for line in lines: + text = strip_marks(line["text"]) + if not text or TIME_RE.match(line["text"]) or NOISE_RE.match(text) or len(text) < 2: + continue + if best is None or line["h"] > best["h"]: + best = line + if best is not None: + rows.append({"name": self.canonical_name(strip_marks(best["text"])), + "raw": best["text"], "y": cy, "x": x0, + "selected": self._row_selected(img, cy)}) + return rows + + def row_previews(self, img: Image.Image) -> list[tuple[int, str]]: + """Cheap per-row fingerprint of the message preview line. + + Unread badges are unreliable (muted rows, badges that clear while the + window is in the background), so the list preview is a second, pixel + only signal that a conversation got a new message. + """ + g = self._geo(img) + centers = self.avatar_centers(img) + x0 = int(img.width * 0.13) + x1 = int(g["list_w"]) - 60 + out: list[tuple[int, str]] = [] + for cy in centers: + if x1 - x0 < 20: + continue + strip = img.crop((x0, max(0, cy + 4), x1, min(img.height, cy + 22))).convert("L") + strip = strip.resize((48, 9), Image.BILINEAR) + out.append((cy, strip.tobytes().hex()[:64])) + return out + + @staticmethod + def _row_selected(img: Image.Image, cy: int) -> bool: + """The open conversation's row is painted with the green highlight.""" + g = WeChatChannel._geo(img) + x = max(0, min(img.width - 1, int(g["list_w"]) - 80)) + y = max(0, min(img.height - 1, cy)) + r, gg, b = img.convert("RGB").getpixel((x, y)) + return gg > 130 and gg - r > 25 and gg - b > 25 + + def unread_rows(self, img: Image.Image) -> list[int]: + """Red unread badges sit at the right edge of each conversation row.""" + g = self._geo(img) + x0, x1 = int(g["list_w"]) - 46, int(g["list_w"]) - 4 + y0, y1 = g["top"], int(g["h"] * 0.93) + crop = img.crop((x0, y0, x1, y1)).convert("RGB") + px = crop.load() + hits = [] + for y in range(crop.height): + count = 0 + for x in range(crop.width): + r, gg, b = px[x, y] + if r > 185 and gg < 105 and b < 105: + count += 1 + if count >= 6: + hits.append(y) + if not hits: + return [] + clusters: list[list[int]] = [[hits[0]]] + for y in hits[1:]: + if y - clusters[-1][-1] <= 6: + clusters[-1].append(y) + else: + clusters.append([y]) + return [y0 + sum(c) // len(c) for c in clusters if len(c) >= 8] + + async def chat_title(self, img: Image.Image) -> str: + g = self._geo(img) + lines = await self.ocr(img, (g["pane_x0"] + 4, int(g["h"] * 0.062), g["pane_x0"] + 280, + int(g["h"] * 0.12)), 3.0) + for line in sorted(lines, key=lambda l: -l["h"]): + text = strip_marks(line["text"]) + if text and not TIME_RE.match(line["text"]) and not NOISE_RE.match(text): + return self.canonical_name(text) + return "" + + # ---------------------------------------------------------------- messages + def text_lines(self, img: Image.Image) -> list[tuple[int, int, int, int]]: + """Find tight bounding boxes of text lines inside the message pane. + + Windows OCR only behaves on crops that hug the text, so we locate dark + glyph pixels first and OCR each line on its own. + """ + g = self._geo(img) + x0 = g["pane_x0"] + 55 # skip avatars + y0, y1 = g["top"], g["bottom"] + x1 = g["pane_right"] + crop = img.crop((x0, y0, x1, y1)).convert("L") + px = crop.load() + width, height = crop.size + dark_rows = [] + for y in range(height): + xs = [x for x in range(width) if px[x, y] < 150] + dark_rows.append(xs) + boxes: list[tuple[int, int, int, int]] = [] + start = None + for y in range(height + 1): + has = bool(dark_rows[y]) if y < height else False + if has and start is None: + start = y + elif not has and start is not None: + if y - start >= 8: + xs_here = [x for row in dark_rows[start:y] for x in row] + if xs_here: + # generous right/bottom padding: the last glyph's + # anti-aliased edge is often lighter than the 150 cut + # and a tight box makes OCR drop that character + boxes.append((max(0, x0 + min(xs_here) - 10), y0 + start - 6, + min(img.width - 1, x0 + max(xs_here) + 16), + min(img.height - 1, y0 + y + 8))) + start = None + return boxes + + def _has_avatar(self, img: Image.Image, y0: int, y1: int) -> bool: + """An incoming bubble has the sender's avatar in the left column. + + WeChat draws every message with an avatar, so the presence of an + image-like patch left of the bubble is a far more reliable speaker + signal than the text's x position (wide/long bubbles start further + left and used to be mis-read as the peer's). + """ + g = self._geo(img) + left = g["pane_x0"] + 8 + right = g["pane_x0"] + 52 + top = max(g["top"], y0 - 20) + bottom = min(g["bottom"], y1 + 20) + if bottom - top < 12: + return False + patch = img.crop((left, top, right, bottom)).convert("L") + px = list(patch.getdata()) + if not px: + return False + mean = sum(px) / len(px) + var = sum((p - mean) ** 2 for p in px) / len(px) + return var ** 0.5 > 22 + + async def read_pane(self, img: Image.Image) -> list[dict]: + g = self._geo(img) + raw: list[dict] = [] + pane = (g["pane_x0"], g["top"], g["pane_right"], g["bottom"]) + if self._rr is not None: + # RapidOCR runs its own detection, so one pass over the whole pane + # replaces both the per-line and the per-bubble passes. + raw = await self.ocr(img, pane, 2.0) + else: + # Whole-pane OCR is far more reliable for the short bubbles ("你好") + # than per-line crops, so it runs first and per-line OCR only fills + # in the lines it missed. + for line in await self.ocr(img, pane, 3.0): + raw.append(line) + def covered(y: int) -> bool: + return any(abs(line["y"] - y) < 18 for line in raw) + for box in self.text_lines(img): + if box[3] - box[1] < 8 or covered(box[1]): + continue + got = await self.ocr(img, box, 3.0) + if not got: + for pad_x, pad_y, scale in ((6, 4, 5.0), (10, 6, 6.0), (14, 8, 2.0)): + wide = (max(0, box[0] - pad_x), max(0, box[1] - pad_y), + min(img.width - 1, box[2] + pad_x), min(img.height - 1, box[3] + pad_y)) + got = await self.ocr(img, wide, scale) + if got: + break + raw.extend(got) + lines = [] + for line in raw: + text = repair_glyphs(line["text"].strip()) + if not text or TIME_RE.match(text) or NOISE_RE.match(strip_marks(text)): + continue + if text in ("以下为新消息", "查看更多消息"): + continue + lines.append({"text": text, "x": line["x"], "y": line["y"], + "w": line["w"], "h": line["h"]}) + msgs: list[dict] = [] + for line in sorted(lines, key=lambda l: l["y"]): + who = "other" if self._has_avatar(img, line["y"], line["y"] + line["h"]) else "self" + if msgs and msgs[-1]["who"] == who and line["y"] - msgs[-1]["bottom"] < 26: + msgs[-1]["text"] += line["text"] + msgs[-1]["bottom"] = line["y"] + line["h"] + msgs[-1]["right"] = max(msgs[-1].get("right", 0), line["x"] + line["w"]) + else: + msgs.append({"who": who, "text": line["text"], "y": line["y"], + "bottom": line["y"] + line["h"], + "right": line["x"] + line["w"]}) + # Windows OCR clips the first/last glyph of a thin line crop ("你好" -> + # "亻尔好"); a second bubble-shaped pass fixes that. RapidOCR already + # reads whole text regions, so it does not need this. + for msg in ([] if self._rr is not None else msgs): + if msg["who"] != "other": + continue + x0 = g["pane_x0"] + 34 + x1 = min(g["pane_right"] - 2, msg.get("right", x0) + 34) + if x1 - x0 < 20: + continue + box = (x0, max(0, msg["y"] - 11), x1, min(img.height - 1, msg["bottom"] + 11)) + best = None + for scale in (4.0, 5.0): + got = await self.ocr(img, box, scale) + text = "".join(line["text"] for line in sorted(got, key=lambda l: l["y"])) + if text and (best is None or len(strip_marks(text)) > len(strip_marks(best))): + best = text + if best and len(strip_marks(best)) > len(strip_marks(msg["text"])): + msg["text"] = best + return msgs + + def new_messages(self, chat: str, msgs: list[dict]) -> list[dict]: + current = [(m["who"], m["text"]) for m in msgs] + prev = self.seen.get(chat) + if prev is None: + self.seen[chat] = current[-60:] + self.seen_total[chat] = len(current) + # First look at this chat. Emit the trailing incoming run when it is + # still unanswered (last bubble is the peer's) so a message that + # arrived before we started watching doesn't get swallowed; if the + # last bubble is ours the run is already handled, so stay quiet. + if not msgs or msgs[-1]["who"] != "other": + return [] + tail: list[dict] = [] + for msg in reversed(msgs): + if msg["who"] != "other": + break + tail.append(msg) + return list(reversed(tail)) + # Align on *content*, not on an index. The absolute-index scheme kept + # losing messages: whenever WeChat re-rendered or scrolled the pane the + # sanity check failed and we silently rebaselined, so the newest bubble + # was dropped exactly when a new message pushed history off the top. + # The pane starts right where the last one we saw ended, so the longest + # prefix of `current` that equals a suffix of `prev` is the overlap. + limit = min(len(prev), len(current)) + k = None + for size in range(limit, 0, -1): + if current[:size] == prev[-size:]: + k = size + break + if k is None: + # Nothing in common with what we last saw: the pane either scrolled + # past our window or was re-rendered. Keep at most the newest + # bubble rather than re-sending a whole screen of history. + k = max(0, len(current) - 1) + fresh_msgs = msgs[k:] + self.seen[chat] = current[-60:] + self.seen_total[chat] = len(current) + cutoff = time.time() - 180 + self.sent_recent = [(t0, txt) for t0, txt in self.sent_recent if t0 >= cutoff] + mine = {strip_marks(txt) for _, txt in self.sent_recent} + return [m for m in fresh_msgs if m["who"] == "other" and strip_marks(m["text"]) not in mine] + + # ---------------------------------------------------------------- actions + def _click(self, hwnd: int, img_x: int, img_y: int) -> None: + ox, oy = client_origin(hwnd) + post_click(hwnd, img_x - ox, img_y - oy) + + async def open_chat(self, name: str) -> bool: + if self.hwnd is None: + return False + img = await self.snapshot() + if img is None: + return False + if self.current and similar(name, self.current) > 0.75: + # trust the cached title only when the pane really still shows it + title_now = await self.chat_title(img) + if title_now and similar(name, title_now) > 0.6: + return True + rows = await self.chat_rows(img) + target = None + for row in rows: + if row["name"] == name: + target = row + break + if target is None: + scored = sorted(rows, key=lambda r: -similar(name, r["name"])) + if scored and similar(name, scored[0]["name"]) >= 0.55: + target = scored[0] + if target is None: + log.warning("会话列表没有 %s(现有 %s)", name, [r["name"] for r in rows][:8]) + return False + g = self._geo(img) + row_x = min(g["list_w"] - 20, target["x"] + 10) + row_y = max(g["top"], target["y"]) + # WeChat usually sits in the background and the first click on an + # inactive window only activates it: the row click is swallowed and the + # pane stays shut, which silently ate incoming messages. Raise the + # window first, then click the row (again if the pane did not open). + focus_window(self.hwnd) + await asyncio.sleep(0.2) + for attempt in range(3): + self._click(self.hwnd, row_x, row_y) + await asyncio.sleep(0.7) + img = await self.snapshot() + if img is None: + continue + now = await self.current_chat(img) + if now and similar(name, now) > 0.6: + self.current = now + return True + if attempt >= 1 and await self.read_pane(img): + self.current = name + return True + # the click is posted asynchronously and WeChat repaints late, so poll + # the title instead of trusting one fixed sleep (earlier version read a + # stale frame and concluded the pane was still empty) + for attempt in range(8): + await asyncio.sleep(0.4) + img = await self.snapshot() + if img is None: + continue + now = await self.current_chat(img) + if now and similar(name, now) > 0.6: + self.current = now + return True + if attempt == 1: + # the title crop OCRs poorly; a pane that already shows the + # conversation is proof enough that the click landed + lines = await self.read_pane(img) + if lines: + self.current = name + return True + return True + self.current = self.current or target["name"] + return False + + async def send_text(self, contact: str, text: str) -> dict: + # DSH message references () and other control tags are not + # something a WeChat contact should ever see. + text = re.sub(r"", " ", str(text)) + # The model sometimes leaks chat-template / tool-call markup such as + # ""; nothing angle-bracketed with a pipe + # belongs in a WeChat message. + text = re.sub(r"<[^<>]*\|[^<>]*>", " ", text) + text = text.replace("DSLM", " ") + text = re.sub(r"\s+", " ", text).strip() + if not text: + return {"status": "ok", "retcode": 0, "data": {"message_id": 0}} + async with self.lock: + if self.hwnd is None or not win32gui.IsWindow(self.hwnd): + self._ensure_window() + if not await self.open_chat(contact): + return {"status": "failed", "retcode": 1404, "data": None, "message": f"找不到微信会话: {contact}"} + img = await self.snapshot() + if img is None: + return {"status": "failed", "retcode": 500, "data": None, "message": "微信窗口读不到画面"} + if self._bar_visible(img): + # a previous voice attempt left the recorder running; release it + # so the keyboard reaches the text box again + release_alt() + await asyncio.sleep(1.6) + img = await self.snapshot() + if img is None: + return {"status": "failed", "retcode": 500, "data": None, "message": "微信窗口读不到画面"} + # the input box remembers voice-input mode per chat; typing is only + # possible after switching back to text mode + if await self.voice_ready(img): + await self._set_voice_mode(False) + img = await self.snapshot() + if img is None: + return {"status": "failed", "retcode": 500, "data": None, "message": "微信窗口读不到画面"} + g = self._geo(img) + box_y = int(g["h"] * 0.86) + box_x = (g["pane_x0"] + g["pane_right"]) // 2 + probe = strip_marks(text)[-6:] + sent = False + for attempt in range(2): + self._click(self.hwnd, box_x, box_y) + await asyncio.sleep(0.2) + post_text(self.hwnd, text) + await asyncio.sleep(0.3) + post_key(self.hwnd, VK_RETURN) + await asyncio.sleep(0.8) + after = await self.snapshot() + if after is None: + continue + # The input box is the reliable witness: after a successful send + # it is empty again. Reading the bubble back through OCR is + # flaky and used to cause duplicate sends. + left = strip_marks(await self.input_text(after)) + if not left or (probe and probe not in left): + sent = True + break + msgs = await self.read_pane(after) + if any(m["who"] == "self" and probe and probe in strip_marks(m["text"]) + for m in msgs[-4:]): + sent = True + break + # The box may be sitting in voice-input mode (it remembers the + # last mode per chat) or the Enter key got swallowed: clear any + # leftovers, toggle the mic and try again. + log.debug("第 %d 次发送未生效,切换输入模式后重试", attempt + 1) + for _ in range(60): + post_key(self.hwnd, VK_BACK) + await asyncio.sleep(0.005) + await asyncio.sleep(0.2) + mx, my = self._mic_point(after) + self._click(self.hwnd, mx, my) + await asyncio.sleep(0.9) + if not sent: + log.warning("发送后没有在聊天里看到内容: %s", text[:24]) + self.sent_recent.append((time.time(), text)) + self._msg_seq += 1 + return {"status": "ok" if sent else "failed", "retcode": 0 if sent else 500, + "data": {"message_id": int(time.time() * 1000) % 10_000_000 + self._msg_seq, + "sent": sent}} + + # ------------------------------------------------------------- voice + def _mic_point(self, img: Image.Image) -> tuple[int, int]: + """The hold-to-talk toggle in the input toolbar (client coords).""" + g = self._geo(img) + return g["pane_x0"] + 180, int(g["h"] * 0.937) + + async def input_text(self, img: Image.Image | None = None) -> str: + """OCR the whole input strip at the bottom of the chat pane.""" + if img is None: + img = await self.snapshot() + if img is None: + return "" + g = self._geo(img) + # only the prompt line at the top-left of the input box carries text; + # a wide crop makes Windows OCR return nothing at all + try: + lines = await self.ocr(img, (g["pane_x0"] + 4, int(g["h"] * 0.775), + g["pane_x0"] + 300, int(g["h"] * 0.84)), 3.5) + except Exception: + return "" + return " ".join(str(l.get("text") or "") for l in lines) + + def hint_signature(self, img: Image.Image) -> list[int]: + """Coarse fingerprint of the prompt text inside the input box. + + Windows OCR reads the light-grey hint badly ("说话" -> "兑话"), so the + talk state is detected by comparing this fingerprint before/after the + press instead of by text. + """ + g = self._geo(img) + box = img.crop((g["pane_x0"] + 6, int(g["h"] * 0.755), g["pane_x0"] + 300, + int(g["h"] * 0.815))).convert("L").resize((32, 8)) + return list(box.getdata()) + + @staticmethod + def _signature_diff(a: list[int], b: list[int]) -> float: + if not a or not b or len(a) != len(b): + return 999.0 + return sum(abs(x - y) for x, y in zip(a, b)) / len(a) + + async def recording(self, img: Image.Image | None = None) -> bool: + """True while the talk button is held down and WeChat is recording.""" + if img is None: + img = await self.snapshot() + if img is None: + return False + return "松开" in await self.input_text(img) + + async def voice_ready(self, img: Image.Image | None = None) -> bool: + """True when the input box shows the 'hold to talk' prompt.""" + text = await self.input_text(img) + if any(k in text for k in ("松开", "结束")): + return False + # OCR mangles the light-grey hint ("说话" -> "兑话", "语音" -> "浯音"), + # so a single shared glyph plus the mouse hint is the reliable signal. + return any(k in text for k in ("话", "长按", "鼠标", "语音")) + + async def _set_voice_mode(self, want: bool) -> bool: + """Toggle between text and hold-to-talk; returns whether we got there.""" + for _ in range(3): + img = await self.snapshot() + if img is None: + return False + if await self.voice_ready(img) == want: + self.voice_ui = want + return True + mx, my = self._mic_point(img) + self._click(self.hwnd, mx, my) + await asyncio.sleep(0.9) + img = await self.snapshot() + ok = img is not None and await self.voice_ready(img) == want + self.voice_ui = ok + return ok + + async def _press_talk(self) -> float: + """Press the talk area and return how much the hint changed. + + A real press-and-hold is required: WeChat only records while the + physical left button is down, so PostMessage presses are ignored. + """ + img = await self.snapshot() + if img is None: + return 0.0 + g = self._geo(img) + bx = (g["pane_x0"] + g["pane_right"]) // 2 + by = int(g["h"] * 0.86) + before = self.hint_signature(img) + if not real_down(self.hwnd, bx, by): + return 0.0 + await asyncio.sleep(0.45) + after_img = await self.snapshot() + if after_img is None: + return 0.0 + text = await self.input_text(after_img) + if any(k in text for k in ("松开", "结束")): + return 99.0 + return self._signature_diff(before, self.hint_signature(after_img)) + + def _voice_bar_points(self, img: Image.Image) -> tuple[tuple[int, int], tuple[int, int], tuple[int, int]]: + """Return (round voice button, send-up, cancel-x) points in client coords.""" + g = self._geo(img) + y = int(g["h"] * 0.935) + return (g["w"] - 106, y), (g["w"] - 51, y), (g["w"] - 257, y) + + async def _real_click(self, px: int, py: int) -> None: + """A real (SendInput) click: we need a real press for several controls.""" + real_down(self.hwnd, int(px), int(py)) + await asyncio.sleep(0.06) + real_up() + + def _bar_visible(self, img: Image.Image) -> bool: + """True while WeChat is recording a voice message. + + Two different bars exist: the click-started one has a ✕ / green ↑ pair, + the Alt-started one is a pale green strip with 松开 发送. Both paint a + light green fill that an idle input box never has. + """ + g = self._geo(img) + rgb = img.convert("RGB") + green = 0 + y0, y1 = int(g["h"] * 0.895), int(g["h"] * 0.965) + for y in range(y0, y1, 2): + for x in range(g["pane_x0"] + 10, g["pane_right"] - 10, 3): + r, gg, b = rgb.getpixel((x, y)) + if gg > 150 and gg - r >= 5 and gg - b >= 3: + green += 1 + if green >= 30: + return True + cx = g["w"] - 51 + cy = int(g["h"] * 0.935) + try: + for dx in (-4, 0, 4): + for dy in (-4, 0, 4): + r, gg, b = rgb.getpixel((cx + dx, cy + dy)) + if gg > 120 and gg - r > 40 and gg - b > 20: + return True + except Exception: + return False + return False + + async def _open_pane(self, contact: str) -> bool: + """Open a chat and wait until its pane really is showing.""" + for _ in range(3): + if await self.open_chat(contact): + img = await self.snapshot() + if img is not None and await self.read_pane(img): + return True + await asyncio.sleep(0.6) + return False + + async def send_voice(self, contact: str, wav_path: str) -> dict: + """Record our TTS wav as a WeChat voice message. + + WeChat's own hint for the circle button is 「发语音(按住右alt)」, so the + reliable trigger is holding Right Alt (recording) and releasing it + (send). WeChat records from the session's default microphone; on this + host that is the RDP-redirected input, so playing the wav on the default + output feeds it straight back into the mic. `voice.output_device` may + name a specific MME output; empty = default. + """ + try: + from wx_audio import play_wav # type: ignore + except Exception as exc: # pragma: no cover - import guard + return {"status": "failed", "retcode": 500, "data": None, + "message": f"音频模块不可用: {exc}"} + # No dedupe here: the duplicate bubbles came from releasing Alt while + # cancelling a failed start, which is fixed at the source. Skipping a + # request that the plugin really made just loses a reply the user can + # see was generated on the TTS side. + voice_cfg = (self.config or {}).get("voice") or {} + device_name = str(voice_cfg.get("output_device") or "").strip() + tail = max(0.0, float(voice_cfg.get("tail_ms", 600)) / 1000.0) + async with self.lock: + if self.hwnd is None or not win32gui.IsWindow(self.hwnd): + self._ensure_window() + if not await self._open_pane(contact): + _img = await self.snapshot() + _rows = [r["name"] for r in (await self.chat_rows(_img) if _img else [])] + log.warning("open_chat 失败 %s,现有会话 %s", contact, _rows) + return {"status": "failed", "retcode": 1404, "data": None, + "message": f"找不到微信会话: {contact}(现有 {_rows})"} + img = await self.snapshot() + if img is None: + return {"status": "failed", "retcode": 500, "data": None, "message": "抓图失败"} + # clicking the input box gives the chat keyboard focus; the Alt + # shortcut then records into this conversation + g = self._geo(img) + self._click(self.hwnd, (g["pane_x0"] + g["pane_right"]) // 2, int(g["h"] * 0.86)) + await asyncio.sleep(0.3) + started = False + for attempt in range(3): + if not hold_alt(self.hwnd): + await asyncio.sleep(0.5) + continue + await asyncio.sleep(1.2) + img = await self.snapshot() + if img is not None and self._bar_visible(img): + started = True + record_started = time.time() + break + # Releasing Alt *sends* whatever was recorded, so a failed + # start must be cancelled the way WeChat documents it + # ("按下退格键取消") -- otherwise every retry left an extra + # short voice bubble behind, which is what made each reply + # arrive twice. + cancel_recording(self.hwnd) + log.debug("右 Alt 没有触发录音,取消后重试第 %d 次", attempt + 1) + await self._open_pane(contact) + img = await self.snapshot() + if img is not None: + g = self._geo(img) + self._click(self.hwnd, (g["pane_x0"] + g["pane_right"]) // 2, + int(g["h"] * 0.86)) + await asyncio.sleep(0.3) + if not started: + return {"status": "failed", "retcode": 500, "data": None, + "message": "右 Alt 没有进入录音状态"} + try: + duration = await asyncio.to_thread(play_wav, wav_path, device_name or None, True) + except Exception as exc: + log.warning("播放失败,取消录音: %s", exc) + cancel_recording(self.hwnd) + return {"status": "failed", "retcode": 500, "data": None, + "message": f"播放失败: {exc}"} + await asyncio.sleep(tail) + # WeChat silently discards a clip that is too short ("说话时间太短"), + # which looks exactly like "TTS generated the audio but nothing was + # sent". Pad the tail so the recorded clip is never < 1.5s. + recorded = time.time() - record_started + if recorded < 1.5: + await asyncio.sleep(1.5 - recorded) + recorded = time.time() - record_started + release_alt() + await asyncio.sleep(2.0) + self.sent_recent.append((time.time(), f"[voice {duration:.1f}s]")) + self._msg_seq += 1 + log.info("语音已发送: 音频 %.1fs,录音 %.1fs", duration, recorded) + return {"status": "ok", "retcode": 0, + "data": {"message_id": int(time.time() * 1000) % 10_000_000 + self._msg_seq, + "duration": round(float(duration), 2), + "recorded": round(recorded, 2)}} + + async def handle_action(self, action: str, params: dict, user_id: int, group_id: int) -> dict: + if action in ("send_msg", "send_private_msg", "send_group_msg", "send_voice"): + target = group_id or user_id + name = await self.name_for(target) + voice = self._voice_of(params) + if voice: + return await self.send_voice(name, voice) + text = self._text_of(params.get("message")) + if not text: + return {"status": "failed", "retcode": 100, "data": None, "message": "只支持文本消息"} + return await self.send_text(name, text) + if action == "get_login_info": + return {"status": "ok", "retcode": 0, "data": {"user_id": self.self_id, "nickname": self.nickname}} + if action in ("get_status", "can_send_image", "can_send_record"): + return {"status": "ok", "retcode": 0, + "data": {"online": True, "good": True, "yes": action.startswith("can_")}} + if action == "set_input_status": + return {"status": "ok", "retcode": 0, "data": None} + return {"status": "failed", "retcode": 1404, "data": None, "message": f"不支持的 action: {action}"} + + @staticmethod + def _text_of(message: Any) -> str: + if isinstance(message, str): + return message + if isinstance(message, list): + parts = [] + for seg in message: + if isinstance(seg, dict) and seg.get("type") == "text": + parts.append((seg.get("data") or {}).get("text") or "") + return "".join(parts) + return "" + + @staticmethod + def _voice_of(params: dict) -> str: + """Extract a record segment into a wav file and return its path.""" + message = params.get("message") + if not isinstance(message, list): + return "" + for seg in message: + if not (isinstance(seg, dict) and seg.get("type") == "record"): + continue + data = seg.get("data") or {} + src = data.get("file") or "" + if isinstance(src, str) and src.startswith("base64://"): + try: + raw = base64.b64decode(src[len("base64://"):], validate=False) + except Exception: + continue + path = TMP / f"voice_{time.time_ns()}.wav" + path.write_bytes(raw) + return str(path) + if isinstance(src, str) and src and Path(src).is_file(): + return src + return "" + + # ---------------------------------------------------------------- ids + def contact_id(self, name: str) -> int: + if name not in self.contacts: + self.contacts[name] = self.base_private + (zlib.crc32(name.encode("utf-8")) % 1_000_000) + return self.contacts[name] + + def name_of(self, uid: int) -> str: + for name, cid in self.contacts.items(): + if cid == uid: + return name + return str(uid) + + async def current_chat(self, img: Image.Image) -> str: + """Name of the conversation on screen: the title, else the highlighted row. + + The small title crop goes through OCR and often comes back empty, while + the highlighted row only needs a pixel probe plus the row's name. + """ + title = await self.chat_title(img) + if title: + return title + for row in await self.chat_rows(img): + if row.get("selected"): + return row["name"] + return "" + + async def name_for(self, uid: int) -> str: + """Resolve a OneBot user id back to a WeChat chat name (scan the list if unknown).""" + known = self.name_of(uid) + if not known.isdigit(): + return known + img = await self.snapshot() + if img is None: + return known + for row in await self.chat_rows(img): + if self.contact_id(row["name"]) == uid: + return row["name"] + return known + + # ---------------------------------------------------------------- watch loop + def watched(self, name: str) -> bool: + if not name or name in self.ignored: + return False + if self.allow and name not in self.allow: + return False + return True + + async def tick(self) -> None: + img = await self.snapshot() + if img is None: + return + badges = self.unread_rows(img) + if badges: + rows = await self.chat_rows(img) + for y in badges: + near = sorted(rows, key=lambda r: abs(r["y"] - y)) + if not near or abs(near[0]["y"] - y) > 30: + continue + name = near[0]["name"] + if not self.watched(name): + continue + if await self.open_chat(name): + log.info("打开未读会话: %s", name) + self.fresh = True + break + else: + # No badge is not proof of no news (muted rows, and WeChat clears + # the badge as soon as the row is hovered). Watch the pixel + # fingerprint of the list previews: if the top row changed and is + # not the open chat, that conversation just got a message. + sigs = self.row_previews(img) + prev_sigs = self._previews + self._previews = sigs + if (prev_sigs and sigs and len(prev_sigs) == len(sigs) + and sigs[0][1] != prev_sigs[0][1] + and not self._row_selected(img, sigs[0][0])): + rows = await self.chat_rows(img) + if rows: + near = sorted(rows, key=lambda r: abs(r["y"] - sigs[0][0])) + name = near[0]["name"] if near else "" + if name and self.watched(name) and name != self.current: + if await self.open_chat(name): + log.info("列表预览变化,打开会话: %s", name) + self.fresh = True + if not self.current: + # nothing opened yet: adopt whatever chat the window currently shows + title_now = await self.chat_title(img) + if title_now and self.watched(title_now): + self.current = title_now + else: + # the small title crop often fails OCR; the highlighted row in + # the list tells us the same thing far more reliably + for row in await self.chat_rows(img): + if row.get("selected") and self.watched(row["name"]): + self.current = row["name"] + log.info("当前会话按高亮行识别为: %s", row["name"]) + break + title = self.current or "" + if not self.watched(title): + return + img = await self.snapshot() + if img is None: + return + real_title = await self.chat_title(img) + if real_title and similar(real_title, title) < 0.6: + self.current = real_title + title = real_title + if not self.watched(title): + return + msgs = await self.read_pane(img) + if not msgs and self.current: # the conversation view got closed: reopen the chat we were watching + if await self.open_chat(self.current): + img = await self.snapshot() + if img is not None: + msgs = await self.read_pane(img) + if not msgs: + return + for msg in self.new_messages(title, msgs): + self._msg_seq += 1 + event = { + "post_type": "message", + "message_type": "private", + "sub_type": "friend", + "self_id": self.self_id, + "user_id": self.contact_id(title), + "message_id": int(time.time()) % 100000 + self._msg_seq, + "time": int(time.time()), + "message": [{"type": "text", "data": {"text": msg["text"]}}], + "raw_message": msg["text"], + "sender": {"user_id": self.contact_id(title), "nickname": title, "card": ""}, + } + log.info("收到微信 [%s]: %s", title, msg["text"][:40]) + await self.emit(event) diff --git a/bridge/wx_audio.py b/bridge/wx_audio.py new file mode 100644 index 0000000..bb36a36 --- /dev/null +++ b/bridge/wx_audio.py @@ -0,0 +1,141 @@ +"""Play a WAV file into a named MME output device (used to feed VB-CABLE). + +We need this because WeChat records from whatever capture device is default, +and the only way to get our TTS audio into that stream is to play it into +"CABLE Input" (the playback side of the virtual cable) while WeChat records +from "CABLE Output". +""" +from __future__ import annotations + +import ctypes +import time +import wave +from ctypes import wintypes + +winmm = ctypes.WinDLL("winmm") + +WAVE_MAPPER = wintypes.UINT(-1) +CALLBACK_NULL = 0x00000000 +WHDR_DONE = 0x00000001 + + +class WAVEFORMATEX(ctypes.Structure): + _fields_ = [ + ("wFormatTag", wintypes.WORD), + ("nChannels", wintypes.WORD), + ("nSamplesPerSec", wintypes.DWORD), + ("nAvgBytesPerSec", wintypes.DWORD), + ("nBlockAlign", wintypes.WORD), + ("wBitsPerSample", wintypes.WORD), + ("cbSize", wintypes.WORD), + ] + + +class WAVEHDR(ctypes.Structure): + _fields_ = [ + ("lpData", ctypes.c_void_p), + ("dwBufferLength", wintypes.DWORD), + ("dwBytesRecorded", wintypes.DWORD), + ("dwUser", ctypes.c_void_p), + ("dwFlags", wintypes.DWORD), + ("dwLoops", wintypes.DWORD), + ("lpNext", ctypes.c_void_p), + ("reserved", ctypes.c_void_p), + ] + + +class WAVEOUTCAPS(ctypes.Structure): + _fields_ = [ + ("wMid", wintypes.WORD), + ("wPid", wintypes.WORD), + ("vDriverVersion", wintypes.UINT), + ("szPname", wintypes.WCHAR * 32), + ("dwFormats", wintypes.DWORD), + ("wChannels", wintypes.WORD), + ("wReserved1", wintypes.WORD), + ("dwSupport", wintypes.DWORD), + ] + + +def output_devices() -> list[tuple[int, str]]: + n = winmm.waveOutGetNumDevs() + out = [] + for i in range(n): + caps = WAVEOUTCAPS() + if winmm.waveOutGetDevCapsW(i, ctypes.byref(caps), ctypes.sizeof(caps)) == 0: + out.append((i, caps.szPname.strip())) + return out + + +def find_device(name_part: str) -> int | None: + want = name_part.lower() + for idx, name in output_devices(): + if want in name.lower(): + return idx + return None + + +def play_wav(path: str, device_name: str | None = None, blocking: bool = True) -> float: + """Play `path` into the MME output device whose name contains `device_name`. + + `device_name=None` (or a name that matches nothing) plays on the default + output device (WAVE_MAPPER). Returns the audio duration in seconds (0.0 + when nothing was played). + """ + with wave.open(path, "rb") as f: + channels = f.getnchannels() + rate = f.getframerate() + width = f.getsampwidth() + frames = f.readframes(f.getnframes()) + + if not frames: + return 0.0 + + fmt = WAVEFORMATEX() + fmt.wFormatTag = 1 # PCM + fmt.nChannels = channels + fmt.nSamplesPerSec = rate + fmt.wBitsPerSample = width * 8 + fmt.nBlockAlign = channels * width + fmt.nAvgBytesPerSec = rate * fmt.nBlockAlign + fmt.cbSize = 0 + + idx = find_device(device_name) if device_name else None + dev = WAVE_MAPPER if idx is None else idx + + handle = wintypes.HANDLE() + rc = winmm.waveOutOpen(ctypes.byref(handle), dev, ctypes.byref(fmt), 0, 0, CALLBACK_NULL) + if rc != 0: + raise RuntimeError(f"waveOutOpen rc={rc} (device={device_name!r}, idx={idx})") + + buf = ctypes.create_string_buffer(frames, len(frames)) + hdr = WAVEHDR() + hdr.lpData = ctypes.cast(buf, ctypes.c_void_p) + hdr.dwBufferLength = len(frames) + + try: + if winmm.waveOutPrepareHeader(handle, ctypes.byref(hdr), ctypes.sizeof(hdr)) != 0: + raise RuntimeError("waveOutPrepareHeader failed") + if winmm.waveOutWrite(handle, ctypes.byref(hdr), ctypes.sizeof(hdr)) != 0: + raise RuntimeError("waveOutWrite failed") + if blocking: + deadline = time.time() + len(frames) / max(1, fmt.nAvgBytesPerSec) + 10 + while not (hdr.dwFlags & WHDR_DONE): + if time.time() > deadline: + break + time.sleep(0.02) + duration = len(frames) / max(1, fmt.nAvgBytesPerSec) + return duration + finally: + winmm.waveOutUnprepareHeader(handle, ctypes.byref(hdr), ctypes.sizeof(hdr)) + winmm.waveOutClose(handle) + + +def capture_devices() -> list[str]: + n = winmm.waveInGetNumDevs() + return [str(i) for i in range(n)] + + +if __name__ == "__main__": + print("outputs:", output_devices()) + print("inputs:", capture_devices()) diff --git a/bridge/wx_audio_default.py b/bridge/wx_audio_default.py new file mode 100644 index 0000000..52b24c6 --- /dev/null +++ b/bridge/wx_audio_default.py @@ -0,0 +1,110 @@ +"""Make a named capture device the Windows default (all three roles). + +WeChat records from the default microphone, so after creating the VB-CABLE +virtual cable we point the default capture at "CABLE Output" — then whatever +we play into "CABLE Input" is what WeChat hears. + +Only the registry is used to resolve the endpoint id; the actual switch goes +through IPolicyConfig (the same COM object the Sound control panel uses). +""" +from __future__ import annotations + +import ctypes +import winreg +from ctypes import POINTER, byref, c_int, c_ulong, c_ushort, c_void_p, c_wchar_p + +GUID_DEVINTERFACE = "{0.0.1.00000000}" +FRIENDLY = "{a45c254e-df1c-4efd-8020-67d146a850e0},2" +MMDEV = r"SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture" + + +class GUID(ctypes.Structure): + _fields_ = [ + ("Data1", c_ulong), + ("Data2", c_ushort), + ("Data3", c_ushort), + ("Data4", ctypes.c_ubyte * 8), + ] + + +def _guid(text: str) -> GUID: + clsid = GUID() + ctypes.oledll.ole32.CLSIDFromString(text, byref(clsid)) + return clsid + + +CLSID_POLICY = "{870AF99C-171D-4F9E-AF0D-E63DF40C2BC9}" +IID_POLICY = "{F8679F50-850A-41CF-9C72-430F290290C8}" + +# IPolicyConfig vtable: IUnknown(3) + GetMixFormat(3) ... SetDefaultEndpoint at 13 +# IUnknown 0..2, GetMixFormat 3, GetDeviceFormat 4, ResetDeviceFormat 5, +# SetDeviceFormat 6, GetProcessingPeriod 7, SetProcessingPeriod 8, +# GetShareMode 9, SetShareMode 10, GetPropertyValue 11, SetPropertyValue 12, +# SetDefaultEndpoint 13, SetEndpointVisibility 14 +SET_DEFAULT_INDEX = 13 + + +def capture_devices() -> list[tuple[str, str]]: + """[(endpoint_id, friendly_name)] for every registered capture endpoint.""" + out: list[tuple[str, str]] = [] + try: + root = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, MMDEV) + except OSError: + return out + with root: + i = 0 + while True: + try: + sub = winreg.EnumKey(root, i) + except OSError: + break + i += 1 + name = "" + try: + with winreg.OpenKey(root, sub + r"\Properties") as props: + name, _ = winreg.QueryValueEx(props, FRIENDLY) + except OSError: + pass + out.append((f"{GUID_DEVINTERFACE}.{sub}", name)) + return out + + +def find_capture(name_part: str) -> str | None: + want = name_part.lower() + for device_id, name in capture_devices(): + if want in (name or "").lower(): + return device_id + return None + + +def set_default(device_id: str, roles: tuple[int, ...] = (0, 1, 2)) -> None: + ole32 = ctypes.windll.ole32 + ole32.CoInitialize(None) + policy = c_void_p() + clsid = _guid(CLSID_POLICY) + iid = _guid(IID_POLICY) + hr = ole32.CoCreateInstance(byref(clsid), None, 1, byref(iid), byref(policy)) + if hr != 0: + raise RuntimeError(f"CoCreateInstance(IPolicyConfig) failed: 0x{hr & 0xFFFFFFFF:08X}") + + vtbl = ctypes.cast(policy, POINTER(POINTER(c_void_p)))[0] + fn = ctypes.WINFUNCTYPE(c_int, c_void_p, c_wchar_p, c_int)(vtbl[SET_DEFAULT_INDEX]) + try: + for role in roles: + rc = fn(policy, device_id, role) + if rc != 0: + raise RuntimeError(f"SetDefaultEndpoint(role={role}) failed: 0x{rc & 0xFFFFFFFF:08X}") + finally: + # Release + rel = ctypes.WINFUNCTYPE(c_ulong, c_void_p)(vtbl[2]) + rel(policy) + + +if __name__ == "__main__": + for device_id, name in capture_devices(): + print(device_id, "|", name) + target = find_capture("CABLE Output") + print("target:", target) + if target: + set_default(target) + print("default capture updated") diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..aba67ca --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,92 @@ +# 架构与数据流 + +## 1. 为什么长这样 + +微信 PC 版(4.x)的主界面是 Qt 自绘: + +- `Qt51514QWindowIcon` 窗口下 `EnumChildWindows` 返回 0; +- UIA 树只有顶层,登录窗口例外(`mmui::LoginWindow` 有完整树); +- 所以既不能用 UIA 读控件,也不能用 UIA 点按钮。 + +同时这台机器是 RDP 会话,`GetForegroundWindow()` 常为 0,`SendInput` 直接返回 +`ACCESS_DENIED`。最终方案是: + +| 能力 | 手段 | +| --- | --- | +| 读屏幕 | `PrintWindow(hwnd, hdc, 2)` → PIL | +| 读文字 | `rapidocr_onnxruntime`(失败回退 Windows.Media.Ocr) | +| 点按钮 | `SendInput`(先把窗口设成前台)+ `SetCursorPos` | +| 打字 | `PostMessage(WM_CHAR)`(不依赖前台) | +| 快捷键 | `SendInput` + 右 Alt(语音条) | + +## 2. 进程与端点 + +``` +obmux.py + ├─ WS server 127.0.0.1:3010 ← DSH 插件 dsh-onebot-qq 连这里(Bearer token) + ├─ WS client ws://127.0.0.1:3001 → SnowLuma(QQ 的 OneBot) + └─ WeChatChannel → 微信窗口(截图/OCR/注入) +``` + +`obmux` 是一个 **OneBot v11 多路复用器**:DSH 只看到「一个机器人」, +但动作会按目标 ID 分流到 QQ 或微信。 + +### ID 号段 + +| 来源 | 号段 | +| --- | --- | +| QQ | 真实 QQ 号(如 `419177984`、`1461220927`) | +| 微信私聊 | `8_000_000_000_000 + crc32(昵称) % 1_000_000` | +| 微信群 | `8_100_000_000_000 + …` | + +分流规则:`id >= 8_000_000_000_000` 走微信,否则转发给 SnowLuma。 + +### 事件 + +微信侧轮询(默认 2s): + +``` +截图 → 找未读红点 / 列表预览变化 → 打开会话 → OCR 消息区 + → 与上次结果做「内容对齐」→ 只把新增的对方消息 emit 成 OneBot 事件 +``` + +QQ 侧是事件推送,`obmux` 原样转发;DSH 未连接时消息进 `pending_events` +(最多 20 条),连上后补发,避免重启窗口丢消息。 + +## 3. 发消息 + +### 文字 + +1. `open_chat(昵称)`:点会话行(窗口非活动时第一次点击只激活窗口,所以最多点 3 次), + 用标题 OCR / 高亮行 / 面板有内容 三者之一确认已打开; +2. 点输入框拿焦点; +3. `PostMessage` 逐字输入; +4. `VK_RETURN` 发送。 + +### 语音条 + +1. 点击输入框,`SendInput` 按住 **右 Alt**(微信的「发语音(按住右alt)」); +2. 出现「松开 发送 / 按下退格键取消」录音条后开始播放 TTS wav; +3. 播放结束 + `tail_ms`(默认 600ms)后松开右 Alt → 微信生成语音条; +4. 录音不足 1.5s 会补齐(微信会静默丢弃过短的语音)。 + +**取消**用退格键(微信自己的提示),不能直接松开 Alt——松开等于发送。 + +## 4. 语音回灌(TTS → 微信语音条) + +``` +TTS 服务 (HTTP) → wav → 播放到虚拟声卡 CABLE Input + → 同机 CABLE Output 变成麦克风 → 经 RDP 录音重定向回到服务器 + → 微信录音条捕获 → 松开发送 +``` + +客户端需要装 VB-CABLE 并勾选 mstsc 的「从此计算机播放 / 录制」。 + +## 5. 关键代码位置 + +| 文件 | 关键函数 | +| --- | --- | +| `bridge/wechat_uia.py` | `WeChatChannel.start/tick/read_pane/new_messages/send_text/send_voice` | +| `bridge/obmux.py` | `on_action`(动作分流)、`pending_events`(离线补发) | +| `bridge/wx_audio.py` | `play_wav(path, device_name)` | +| `tools/wx_post.py` | `post_click/post_text/post_key`(PostMessage 注入) | diff --git a/docs/persona.md b/docs/persona.md new file mode 100644 index 0000000..9ab4abe --- /dev/null +++ b/docs/persona.md @@ -0,0 +1,44 @@ +# 人设与记忆 + +## 一个身份,两个平台 + +微信和 QQ 在 `obmux` 里被合并成一个 OneBot 端点,所以 DSH 只看到一个会话来源, +人格卡、记忆、上下文都是同一份。 + +但**会话 ID 不同**(`onebot-private-` / `onebot-private-8xxxxxxxxxxxxx`), +如果 DSH 插件按会话建 agent,就会出现「两个小小糯」。解决办法是在 DSH 的 +`soul-md` 里用**一张人设卡 + 一个记忆目录**,让所有会话共享: + +```yaml +- id: soul-md + name: dsh-soul-md + config: + active: 小小糯 + cards: + 小小糯: |- + ... +``` + +记忆目录:`~/.dsh/soul-md/memory/<卡名>/`,`core.md` + `topics/*.md`。 + +## 人设文件与热更新 + +- 人设原文:`~/.bili-ai/persona.md`(B站养鱼插件读同一份,保证两个身份一致); +- 人设卡:写在 `cordis.patch.yml` 的 `soul-md` 行里; +- 两者要一起改,改完用脚本核对「卡片字符数 == 文件字符数」,再等 + `settings/document-updated` 热加载(`watch: true`,约 300ms)。 + +同步脚本的核心:只替换 ` 小小糯: |-` 这个块标量的内容行, +**缩进必须比 key 行多两格**,否则 YAML 会崩。 + +## 输出节奏(和 QQ/微信的桥接约定) + +- 一条气泡 = 一行字,换行即分条,最多 4 条; +- 语音条也是同样规则,但语音慢,更适合短句; +- 空回复 = 什么都不发(桥接不会发空消息),这是「保持安静」的正确做法。 + +## 记忆卫生 + +- 不要把人设原文抄进记忆,记忆里只留「我是谁、边界、和对方的约定」; +- 两本日记(公开 / 私人)用硬链接映射进 `topics/`,读写同一份文件; +- 每次大改人设后重启一次 DSH,确保 `systemPrompt` 重新注入。 diff --git a/docs/setup.md b/docs/setup.md new file mode 100644 index 0000000..1996be2 --- /dev/null +++ b/docs/setup.md @@ -0,0 +1,131 @@ +# 部署与自启 + +## 前提 + +- Windows 10/11,屏幕分辨率 ≥ 1280x720(微信窗口 896x648 起) +- Python 3.10(本机为 `C:\Users\GuoAn\Python310\python.exe`) +- 微信 4.x PC 版,已登录小号 +- SnowLuma(QQ 侧)已登录,OneBot WS 端口默认 3001 + +## 1. Python 依赖 + +```powershell +pip install -i https://mirrors.aliyun.com/pypi/simple ` + uiautomation pywin32 pyperclip pygetwindow pyautogui comtypes psutil ` + pillow numpy rapidocr_onnxruntime winsdk requests websockets +``` + +> `numpy` 会升到 2.x;如果本机还有 matplotlib / numba / scikit-learn 等旧依赖, +> 会看到冲突告警,但本项目的 OCR 链路不受影响。 + +## 2. 微信侧准备 + +1. 打开微信并登录,**不要**最小化到托盘(最小化时 `PrintWindow` 出灰图; + 桥接会自动 `ShowWindow(9)` 尝试恢复)。 +2. 首次运行前允许麦克风权限(语音条需要): + + ```powershell + # 设置 → 隐私 → 麦克风:允许桌面应用访问 + Set-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\microphone' -Name Value -Value Allow + ``` + + 微信会缓存权限,改完要重启微信。 + +3. 语音条还需要虚拟声卡(见下)。 + +## 3. 语音条:虚拟声卡 + RDP 音频 + +微信 PC 端没有「发送语音文件」接口,语音条只能靠录音。做法: + +1. **在这台服务器上装 VB-CABLE 无效**(无物理声卡、纯 RDP 会话时驱动端点不进音频图), + 所以装在**客户端**电脑上; +2. 客户端安装 `VBCABLE_Driver_Pack43.zip` → `VBCABLE_Setup_x64.exe` → Install Driver → 重启; +3. 客户端声音设置:播放默认 `CABLE Input`,录制默认 `CABLE Output`; +4. mstsc → 显示选项 → 本地资源 → 远程音频 → 设置 → 勾选 + 「从此计算机播放」和「从此计算机录制」→ 重连; +5. 服务器上应出现第二个 `远程音频` 端点(capture),且 `waveInGetNumDevs() >= 1`。 + +自检: + +```powershell +python bridge/wx_audio.py # 列出可用输出设备 +python tools/wx_probe_popup.py # 点麦克风后抓微信的提示气泡 +``` + +## 4. 配置文件 + +```powershell +Copy-Item bridge/config.example.json bridge/config.json +notepad bridge/config.json +``` + +- `token`:DSH 连接桥接时用的 Bearer token,随便设一个长随机串; +- `listen_port`:默认 3010; +- `qq_url`:SnowLuma 的 OneBot WS 地址; +- `wechat.voice.tail_ms`:松开前额外等待(默认 600ms)。 + +## 5. 启动方式 + +### 手工 + +```powershell +python bridge/obmux.py +``` + +### 计划任务(推荐,登录即启动) + +```powershell +schtasks /Create /TN "WeChatBridge" /SC ONLOGON /RL LIMITED /F ` + /TR "\"C:\Users\GuoAn\Python310\python.exe\" \"C:\Users\GuoAn\.dsh\wechat-bridge\obmux.py\"" + +schtasks /Run /TN "WeChatBridge" +schtasks /End /TN "WeChatBridge" +``` + +> 用 `Start-Process` 启动的进程会随宿主退出被杀;计划任务不受影响。 + +### 微信自启 + +```powershell +schtasks /Create /TN "WeChatAutoStart" /SC ONLOGON /RL LIMITED /F ` + /TR "\"C:\Program Files\Tencent\Weixin\Weixin.exe\"" +``` + +## 6. DSH 侧 + +`cordis.patch.yml` 里 `dsh-onebot` 行: + +```yaml +- id: dsh-onebot + name: dsh-onebot-qq + config: + mode: forward + url: ws://127.0.0.1:3010 + accessToken: <与 config.json 的 token 一致> + botQQ: "1461220927" + adminUsers: ["<你的QQ号>"] + dmPolicy: open + groupPolicy: open + requireMention: false + interimMessages: false + tts: + enabled: true + baseUrl: http://:8080 + speechRatio: 0.5 +``` + +**注意**:不要同时保留 `accessTokenFile`——插件的 `resolveAccessToken()` +会优先读文件里的 token,导致连桥接时鉴权失败。 + +## 7. 验证清单 + +```powershell +# 桥接三行日志 +Get-Content C:\Users\GuoAn\.dsh\wechat-bridge\obmux.log -Tail 5 + +# 模拟 DSH 发一条文字 +python bridge/probe.py "文件传输助手" "hello" + +# 模拟 DSH 发一条语音(需要先有 wav) +python bridge/probe_voice.py +``` diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..30a9ab7 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,90 @@ +# 排障手册 + +按「现象 → 先看哪里 → 常见原因」组织。日志默认在 `bridge/obmux.log`。 + +## 桥接根本没起来 + +`schtasks /Query /TN WeChatBridge` 看不到进程,日志停在某一行。 + +- `没找到微信主窗口(微信 4.x 需要已登录)`:微信被最小化到托盘, + `find_main_window()` 会尝试 `ShowWindow(9)` 恢复;如果仍失败,手工点开微信。 +- 端口占用:`Get-NetTCPConnection -LocalPort 3010`。 +- 计划任务用 `Start-Process` 起过一版,进程会随宿主退出——统一改用 + `schtasks /Run`。 + +## DSH 连不上桥接 + +日志出现 `拒绝未授权的 DSH 连接`。 + +- 插件的 `accessTokenFile` 优先于 `accessToken`,删掉前者; +- 两边 token 不一致(注意 `config.json` 的 `token` 与 patch 行里的 `accessToken`)。 + +## 消息读不到 / 漏消息 + +1. 看日志有没有 `收到微信 [昵称]: …`。 +2. 没有的话,抓一张窗口图: + + ```powershell + python tools/wx_capture.py %TEMP%\shot.png + ``` + + 面板是灰/黑说明微信不渲染了,重启微信。 +3. OCR 认错:`read_pane` 已经用 RapidOCR + 整屏识别;如果某条特别短 + (「好」「嗯」)仍读不出,属已知限制。 +4. 漏消息的经典原因: + - 未读红点不可靠(静音、鼠标悬停会清掉)→ 已用「列表预览指纹」兜底; + - 去重逻辑按绝对下标对齐会吞掉最新一条 → 已改成按内容对齐。 + +## 回复发重复 + +同一句出现两三次。 + +- `send_text` 的「发送后核对」在 OCR 认不出自己刚发的气泡时会重发; + 新版本已改为「输入框清空即视为已发送」。 +- 语音重复的老原因:取消录音时错误地松开了右 Alt(松开=发送), + 现在用 `cancel_recording()`(按退格)取消。 +- `new_messages` 的绝对下标 bug 会让同一条消息被反复投递,改用内容对齐后消失。 + +## 语音条没发出去,但 TTS 后台显示已生成 + +按顺序排查: + +1. 日志有没有 `语音已发送: 音频 X s,录音 Y s` + - **没有**:请求没到桥接,检查插件是否走了 `record` 段、`tts.enabled` 是否为 true。 + - **有**:微信侧丢了,见下一条。 +2. 录音太短:微信会静默丢弃 <1s 的语音。桥接现在会补到 ≥1.5s。 +3. 录音条没出现:右 Alt 没有真正按下(窗口非前台)。 + `hold_alt()` 会先 `AttachThreadInput + SetForegroundWindow`, + 检查 `GetForegroundWindow()` 是否等于微信 hwnd。 +4. 麦克风没有音频:`waveInGetNumDevs()`、`wx_audio.py` 是否能列出 capture 设备; + RDP 音频重定向断开过一次就要重连客户端。 + +## 语音条变成文字 + +- 插件侧 TTS 合成失败 / 超时(`tts.timeoutMs`)会降级成文字; +- `speechRatio` 是按条独立掷骰的概率,不是全部语音。 + +## 麦克风权限 + +点麦克风图标没反应时,微信会弹一个独立小窗(主窗口截图看不到): + +```powershell +python tools/wx_probe_popup.py +``` + +抓到「麦克风权限未开启」就改注册表并重启微信: + +```powershell +Set-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\microphone' -Name Value -Value Allow +``` + +## 窗口坐标全错 + +DPI 或窗口尺寸变了。所有坐标都是相对 `_geo(img)` 的比例(`list_w = 0.35*w` 等), +改窗口大小通常不用改代码;但如果改了系统缩放,请重新截图核对 +`pane_x0 / top / bottom / 0.935h` 这些锚点。 + +## 抓图全灰/全黑 + +- 微信最小化或隐藏到托盘 → `ShowWindow(9)` 后等 1s 再抓; +- 息屏/锁屏 → 远程会话没有桌面,`PrintWindow` 只能拿到灰图。 diff --git a/tools/desk_diag.py b/tools/desk_diag.py new file mode 100644 index 0000000..0a5e6cc --- /dev/null +++ b/tools/desk_diag.py @@ -0,0 +1,30 @@ +"""Report desktop / window-station names and foreground window.""" +import ctypes +from ctypes import wintypes + +user32 = ctypes.WinDLL('user32', use_last_error=True) +kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) + +UOI_NAME = 2 +UOI_FLAGS = 1 + + +def obj_name(handle): + need = wintypes.DWORD(0) + user32.GetUserObjectInformationW(handle, UOI_NAME, None, 0, ctypes.byref(need)) + buf = ctypes.create_unicode_buffer(need.value) + ok = user32.GetUserObjectInformationW(handle, UOI_NAME, buf, need.value, ctypes.byref(need)) + return buf.value if ok else f'' + + +h = user32.GetThreadDesktop(kernel32.GetCurrentThreadId()) +print("thread desktop:", obj_name(h)) +ws = user32.GetProcessWindowStation() +print("window station:", obj_name(ws)) +print("OpenInputDesktop:", user32.OpenInputDesktop(0, False, 0x0100)) +input_desk = user32.OpenInputDesktop(0, False, 0x0100) +if input_desk: + print("input desktop name:", obj_name(input_desk)) +print("GetForegroundWindow:", user32.GetForegroundWindow()) +print("GetActiveWindow:", user32.GetActiveWindow()) +print("GetDesktopWindow:", user32.GetDesktopWindow()) diff --git a/tools/force_fg.py b/tools/force_fg.py new file mode 100644 index 0000000..103ebca --- /dev/null +++ b/tools/force_fg.py @@ -0,0 +1,31 @@ +"""Try forcing foreground via AttachThreadInput, then test SendInput.""" +import ctypes, sys, time +from ctypes import wintypes + +user32 = ctypes.WinDLL('user32', use_last_error=True) +kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) + +user32.AttachThreadInput.argtypes = [wintypes.DWORD, wintypes.DWORD, wintypes.BOOL] +user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)] +user32.GetWindowThreadProcessId.restype = wintypes.DWORD +kernel32.GetCurrentThreadId.restype = wintypes.DWORD + + +def force_foreground(hwnd): + tid_target = user32.GetWindowThreadProcessId(hwnd, None) + tid_self = kernel32.GetCurrentThreadId() + print('threads: target', tid_target, 'self', tid_self) + attached = user32.AttachThreadInput(tid_self, tid_target, True) + print('AttachThreadInput:', attached, 'err', ctypes.get_last_error()) + user32.ShowWindow(hwnd, 9) # SW_RESTORE + user32.BringWindowToTop(hwnd) + ok = user32.SetForegroundWindow(hwnd) + print('SetForegroundWindow:', ok, 'err', ctypes.get_last_error()) + user32.SetFocus(hwnd) + time.sleep(0.5) + print('foreground now:', user32.GetForegroundWindow(), 'active:', user32.GetActiveWindow()) + print('AttachThreadInput(detach):', user32.AttachThreadInput(tid_self, tid_target, False)) + + +if __name__ == '__main__': + force_foreground(int(sys.argv[1])) diff --git a/tools/input_diag.py b/tools/input_diag.py new file mode 100644 index 0000000..73cda49 --- /dev/null +++ b/tools/input_diag.py @@ -0,0 +1,69 @@ +"""Diagnose SendInput delivery.""" +import time, ctypes +from ctypes import wintypes + +user32 = ctypes.WinDLL('user32', use_last_error=True) +user32.SendInput.argtypes = [wintypes.UINT, ctypes.c_void_p, ctypes.c_int] +user32.SendInput.restype = wintypes.UINT + +ULONG_PTR = ctypes.c_size_t + + +class KEYBDINPUT(ctypes.Structure): + _fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD), + ("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)] + + +class MOUSEINPUT(ctypes.Structure): + _fields_ = [("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD), + ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)] + + +class HARDWAREINPUT(ctypes.Structure): + _fields_ = [("uMsg", wintypes.DWORD), ("wParamL", wintypes.WORD), ("wParamH", wintypes.WORD)] + + +class _I(ctypes.Union): + _fields_ = [("mi", MOUSEINPUT), ("ki", KEYBDINPUT), ("hi", HARDWAREINPUT)] + + +class INPUT(ctypes.Structure): + _fields_ = [("type", wintypes.DWORD), ("u", _I)] + + +KEYEVENTF_UNICODE = 0x0004 +KEYEVENTF_KEYUP = 0x0002 + + +def type_text(text): + evts = [] + for ch in text: + for flag in (KEYEVENTF_UNICODE, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP): + inp = INPUT() + inp.type = 1 + inp.u.ki = KEYBDINPUT(wVk=0, wScan=ord(ch), dwFlags=flag, time=0, dwExtraInfo=0) + evts.append(inp) + arr = (INPUT * len(evts))(*evts) + sent = user32.SendInput(len(evts), ctypes.cast(arr, ctypes.c_void_p), ctypes.sizeof(INPUT)) + err = ctypes.get_last_error() + return sent, err + + +if __name__ == '__main__': + import sys + hwnd = int(sys.argv[1]) + print("sizeof(INPUT) =", ctypes.sizeof(INPUT)) + print("foreground before:", user32.GetForegroundWindow(), "target:", hwnd) + user32.SetForegroundWindow(hwnd) + time.sleep(0.5) + fg = user32.GetForegroundWindow() + print("foreground after:", fg) + sent, err = type_text('hello') + print("SendInput sent:", sent, "last_error:", err) + # also try mouse move to see if input pipeline alive + p = wintypes.POINT(100, 100) + user32.SetCursorPos(100, 100) + time.sleep(0.2) + user32.GetCursorPos(ctypes.byref(p)) + print("cursor:", p.x, p.y) + time.sleep(1) diff --git a/tools/mmdev.cs b/tools/mmdev.cs new file mode 100644 index 0000000..ef7cd10 --- /dev/null +++ b/tools/mmdev.cs @@ -0,0 +1,100 @@ +using System; +using System.Runtime.InteropServices; +using System.Collections.Generic; + +public class MMDevices +{ + [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] + private class MMDeviceEnumeratorComObject { } + + [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IMMDeviceEnumerator + { + int EnumAudioEndpoints(int dataFlow, int stateMask, out IMMDeviceCollection devices); + int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device); + int GetDevice(string id, out IMMDevice device); + int RegisterEndpointNotificationCallback(IntPtr client); + int UnregisterEndpointNotificationCallback(IntPtr client); + } + + [Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IMMDeviceCollection + { + int GetCount(out int count); + int Item(int index, out IMMDevice device); + } + + [Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IMMDevice + { + int Activate(ref Guid iid, int clsCtx, IntPtr activationParams, out IntPtr iface); + int OpenPropertyStore(int access, out IPropertyStore store); + int GetId(out IntPtr id); + int GetState(out int state); + } + + [Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IPropertyStore + { + int GetCount(out int count); + int GetAt(int index, out PROPERTYKEY key); + int GetValue(ref PROPERTYKEY key, out PROPVARIANT value); + int SetValue(ref PROPERTYKEY key, ref PROPVARIANT value); + int Commit(); + } + + [StructLayout(LayoutKind.Sequential)] + private struct PROPERTYKEY { public Guid fmtid; public int pid; } + + [StructLayout(LayoutKind.Explicit)] + private struct PROPVARIANT + { + [FieldOffset(0)] public short vt; + [FieldOffset(8)] public IntPtr pointerValue; + } + + private static PROPERTYKEY PKEY_Device_FriendlyName = new PROPERTYKEY + { + fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), + pid = 14 + }; + + public static List List(int dataFlow) + { + return ListWithMask(dataFlow, 1); + } + + public static List ListAll(int dataFlow) + { + // 0x0F: active | disabled | notpresent | unplugged + return ListWithMask(dataFlow, 0x0F); + } + + public static List ListWithMask(int dataFlow, int mask) + { + var result = new List(); + var enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumeratorComObject()); + IMMDeviceCollection collection; + if (enumerator.EnumAudioEndpoints(dataFlow, mask, out collection) != 0) + { + result.Add("ERROR: EnumAudioEndpoints failed"); + return result; + } + int count; + collection.GetCount(out count); + for (int i = 0; i < count; i++) + { + IMMDevice device; + collection.Item(i, out device); + IPropertyStore store; + device.OpenPropertyStore(0, out store); + PROPVARIANT value; + store.GetValue(ref PKEY_Device_FriendlyName, out value); + string name = Marshal.PtrToStringUni(value.pointerValue); + int state; + device.GetState(out state); + result.Add(name + " | state=" + state); + } + return result; + } +} diff --git a/tools/msg_input.py b/tools/msg_input.py new file mode 100644 index 0000000..802ebd1 --- /dev/null +++ b/tools/msg_input.py @@ -0,0 +1,32 @@ +"""Message-based input (PostMessage) — works without a foreground/input desktop.""" +import ctypes, time +from ctypes import wintypes + +user32 = ctypes.WinDLL('user32', use_last_error=True) +WM_CHAR = 0x0102 +WM_KEYDOWN = 0x0100 +WM_KEYUP = 0x0101 +WM_LBUTTONDOWN = 0x0201 +WM_LBUTTONUP = 0x0202 +WM_SETCURSOR = 0x0020 + + +def post_char(hwnd, ch): + user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 0x00000001) + + +def post_text(hwnd, text): + for ch in text: + post_char(hwnd, ch) + time.sleep(0.01) + + +def post_key(hwnd, vk): + user32.PostMessageW(hwnd, WM_KEYDOWN, vk, 0x00000001) + user32.PostMessageW(hwnd, WM_KEYUP, vk, 0xC0000001) + + +def post_click(hwnd, x, y): + lparam = (y << 16) | (x & 0xFFFF) + user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lparam) + user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lparam) diff --git a/tools/msg_test_np.py b/tools/msg_test_np.py new file mode 100644 index 0000000..dd702af --- /dev/null +++ b/tools/msg_test_np.py @@ -0,0 +1,42 @@ +"""Test message-based input against Notepad (WM_CHAR to edit control).""" +import ctypes, sys, time +from ctypes import wintypes + +user32 = ctypes.WinDLL('user32', use_last_error=True) +WM_CHAR = 0x0102 +WM_KEYDOWN = 0x0100 +WM_KEYUP = 0x0101 + + +def find_child_edit(hwnd): + found = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def cb(h, lparam): + cls = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(h, cls, 64) + if cls.value == 'Edit': + found.append(h) + return False + return True + + user32.EnumChildWindows(hwnd, cb, 0) + return found[0] if found else None + + +def post_text(hwnd, text): + ok = 0 + for ch in text: + if user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 0x00000001): + ok += 1 + time.sleep(0.005) + return ok + + +if __name__ == '__main__': + hwnd = int(sys.argv[1]) + edit = find_child_edit(hwnd) + print('notepad:', hwnd, 'edit:', edit) + if edit: + print('posted chars:', post_text(edit, 'MSGOK')) + time.sleep(0.5) diff --git a/tools/qq-notify.cjs b/tools/qq-notify.cjs new file mode 100644 index 0000000..2daec4e --- /dev/null +++ b/tools/qq-notify.cjs @@ -0,0 +1,189 @@ +#!/usr/bin/env node +// qq-notify.cjs —— 把小肥鱼(dsh-bili-whale)的推送转成 QQ 消息(默认发语音条) +// +// 用法: node qq-notify.cjs "消息正文" +// 或 WHALE_NOTIFY_TEXT="消息正文" node qq-notify.cjs +// +// 它会被 dsh-bili-whale 的 notify.mjs 以 type=command 调起,正文作为最后一个参数传入。 +// 走 SnowLuma 的 OneBot HTTP 接口发私聊。token 每次从 SnowLuma 的账号配置里现读, +// 换了 token 也不用改这里。 +// +// 主动推送默认走语音:正文先交给自建 TTS 合成 wav,再以 record 段发出; +// 合成失败 / 太长(>58s)/ QQ_NOTIFY_VOICE=0 时退回文字。 +// +// 环境变量(都可选): +// QQ_NOTIFY_CONFIG_DIR SnowLuma 配置目录,默认 C:\Users\GuoAn\Desktop\SnowLuma-v2.4.0-win-x64\config +// QQ_NOTIFY_BASE OneBot HTTP 地址,默认 http://127.0.0.1:3000 +// QQ_NOTIFY_TARGET 收信人 QQ,默认 419177984 +// QQ_NOTIFY_TOKEN 手动指定 accessToken(跳过读配置) +// QQ_NOTIFY_TTS TTS 服务地址,默认 http://192.168.1.17:8080;置空则不发语音 +// QQ_NOTIFY_VOICE 0 = 强制发文字;默认发语音 + +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') + +const CONFIG_DIR = process.env.QQ_NOTIFY_CONFIG_DIR || 'C:\\Users\\GuoAn\\Desktop\\SnowLuma-v2.4.0-win-x64\\config' +const BASE = (process.env.QQ_NOTIFY_BASE || 'http://127.0.0.1:3000').replace(/\/+$/, '') +const TARGET = Number(process.env.QQ_NOTIFY_TARGET || 419177984) +const TTS_BASE = (process.env.QQ_NOTIFY_TTS ?? 'http://192.168.1.17:8080').replace(/\/+$/, '') +const VOICE_ON = process.env.QQ_NOTIFY_VOICE !== '0' && TTS_BASE !== '' +const LOG = path.join(os.homedir(), '.dsh', 'bin', 'qq-notify.log') + +/** 语音条上限 60s,留 2s 余量。 */ +const MAX_VOICE_SECONDS = 58 + +function log(line) { + try { + fs.mkdirSync(path.dirname(LOG), { recursive: true }) + fs.appendFileSync(LOG, `[${new Date().toISOString()}] ${line}\n`) + } catch {} +} + +/** 从 SnowLuma 的 onebot_.json 里找出 HTTP 服务的 accessToken。 */ +function findToken() { + if (process.env.QQ_NOTIFY_TOKEN) return process.env.QQ_NOTIFY_TOKEN + let files = [] + try { + files = fs.readdirSync(CONFIG_DIR).filter((f) => /^onebot_.*\.json$/.test(f)) + } catch (e) { + throw new Error(`读不到 SnowLuma 配置目录:${CONFIG_DIR}(${e.message})`) + } + // 优先取最近写过的那个账号 + files.sort((a, b) => { + try { + return fs.statSync(path.join(CONFIG_DIR, b)).mtimeMs - fs.statSync(path.join(CONFIG_DIR, a)).mtimeMs + } catch { return 0 } + }) + for (const f of files) { + try { + const cfg = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, f), 'utf8')) + // SnowLuma 的账号级快照把网络配置放在 networks 下面 + const servers = cfg?.httpServers || cfg?.networks?.httpServers || cfg?.onebot?.httpServers || [] + for (const s of servers) { + if (s && s.accessToken) return String(s.accessToken) + } + } catch {} + } + throw new Error('没在 SnowLuma 配置里找到 HTTP accessToken') +} + +/** 只留下能念出来的字:去代码块、行内码、链接、Markdown 符号、emoji。 */ +function speechText(text) { + return String(text ?? '') + .replace(/```[\s\S]*?```/g, ' ') + .replace(/`([^`]*)`/g, '$1') + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/https?:\/\/\S+/g, ' ') + .replace(/[*_~#>|]+/g, ' ') + .replace(/[\p{Extended_Pictographic}\u{FE0F}\u{200D}\u{20E3}]/gu, ' ') + .replace(/\s+/g, ' ') + .trim() +} + +/** 读 wav 头的时长(秒);不是 wav 或读不出来时返回 0。 */ +function wavDurationSeconds(bytes) { + if (!Buffer.isBuffer(bytes) || bytes.length < 44) return 0 + if (bytes.toString('ascii', 0, 4) !== 'RIFF' || bytes.toString('ascii', 8, 12) !== 'WAVE') return 0 + let offset = 12 + let byteRate = 0 + let dataSize = 0 + while (offset + 8 <= bytes.length) { + const id = bytes.toString('ascii', offset, offset + 4) + const size = bytes.readUInt32LE(offset + 4) + const body = offset + 8 + if (id === 'fmt ' && body + 16 <= bytes.length) { + byteRate = bytes.readUInt32LE(body + 8) + } else if (id === 'data') { + dataSize = size + break + } + offset = body + size + (size % 2) + } + if (byteRate <= 0 || dataSize <= 0) return 0 + return dataSize / byteRate +} + +/** 合成语音;失败返回 null(调用方退回文字)。 */ +async function synthesize(text) { + const spoken = speechText(text) + if (!spoken) return null + try { + const res = await fetch(`${TTS_BASE}/api/tts`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ text: spoken }), + signal: AbortSignal.timeout(120000), + }) + if (!res.ok) { + log(`TTS FAIL http=${res.status} ${(await res.text().catch(() => '')).slice(0, 200)}`) + return null + } + const bytes = Buffer.from(await res.arrayBuffer()) + if (bytes.length < 100) { + log('TTS FAIL empty audio') + return null + } + const seconds = wavDurationSeconds(bytes) + if (seconds > MAX_VOICE_SECONDS) { + log(`TTS SKIP ${seconds.toFixed(1)}s > ${MAX_VOICE_SECONDS}s`) + return null + } + log(`TTS OK ${bytes.length}B ${seconds.toFixed(1)}s`) + return bytes + } catch (e) { + log('TTS ERR ' + (e && e.message ? e.message : String(e))) + return null + } +} + +async function send(token, message) { + const res = await fetch(`${BASE}/send_private_msg`, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, + body: JSON.stringify({ user_id: TARGET, message }), + signal: AbortSignal.timeout(60000), + }) + const raw = await res.text().catch(() => '') + let data = null + try { data = JSON.parse(raw) } catch {} + return { ok: res.ok && !(data && data.retcode !== 0 && data.status !== 'ok'), raw, data, status: res.status } +} + +async function main() { + const text = (process.argv[2] ?? process.env.WHALE_NOTIFY_TEXT ?? '').trim() + if (!text) { + console.error('用法: node qq-notify.cjs "消息正文"') + process.exit(2) + } + const token = findToken() + const body = text.length > 3000 ? text.slice(0, 3000) + '\n…' : text + + if (VOICE_ON) { + const bytes = await synthesize(body) + if (bytes) { + const sent = await send(token, [{ type: 'record', data: { file: 'base64://' + bytes.toString('base64') } }]) + if (sent.ok) { + log(`OK-voice ${JSON.stringify(sent.data?.data ?? null).slice(0, 200)}`) + console.log('QQ 已送达(语音)✓', JSON.stringify(sent.data?.data ?? null)) + return + } + log(`VOICE SEND FAIL http=${sent.status} ${sent.raw.slice(0, 300)};改发文字`) + } + } + + const sent = await send(token, body) + if (!sent.ok) { + log(`FAIL http=${sent.status} ${sent.raw.slice(0, 300)}`) + console.error(`QQ 推送失败:HTTP ${sent.status} ${sent.raw.slice(0, 300)}`) + process.exit(1) + } + log(`OK ${JSON.stringify(sent.data?.data ?? null).slice(0, 200)}`) + console.log('QQ 已送达 ✓', JSON.stringify(sent.data?.data ?? null)) +} + +main().catch((e) => { + log('ERR ' + (e && e.message ? e.message : String(e))) + console.error('QQ 推送失败:' + (e && e.message ? e.message : String(e))) + process.exit(1) +}) diff --git a/tools/stt.py b/tools/stt.py new file mode 100644 index 0000000..fd5e2d5 --- /dev/null +++ b/tools/stt.py @@ -0,0 +1,129 @@ +"""Standalone STT entry point for dsh-onebot-qq. + +Called by the plugin as its "custom" engine: + + python stt.py --file --out /out --model + +The plugin hands over a 16 kHz mono WAV (already converted with ffmpeg) and +reads the first *.txt in the work dir, so this script writes .txt. + +Two backends: + * SenseVoice (sherpa-onnx) — used when --model points at a *.onnx file. + Fast on CPU and strong on short Chinese utterances. + * faster-whisper — used when --model is a whisper size or a local + CTranslate2 model directory. +""" + +from __future__ import annotations + +import argparse +import os +import re +import sys +import time +import wave +from pathlib import Path + +MODEL_ROOT = os.environ.get("STT_MODEL_ROOT") or str(Path.home() / ".dsh" / "stt-models") +TAG_RE = re.compile(r"<\|[^|]*\|>") + + +def log(msg: str) -> None: + sys.stderr.write(f"[stt] {msg}\n") + sys.stderr.flush() + + +def read_wav(path: Path) -> tuple["object", int]: + import numpy as np + + with wave.open(str(path), "rb") as wf: + channels = wf.getnchannels() + rate = wf.getframerate() + width = wf.getsampwidth() + frames = wf.readframes(wf.getnframes()) + if width != 2: + raise SystemExit(f"expected 16-bit PCM, got sample width {width}") + samples = np.frombuffer(frames, dtype=np.int16).astype("float32") / 32768.0 + if channels > 1: + samples = samples.reshape(-1, channels).mean(axis=1) + return samples, rate + + +def transcribe_sense_voice(wav: Path, model: Path, tokens: Path, language: str) -> str: + import sherpa_onnx + + if not tokens.is_file(): + raise SystemExit(f"missing sense-voice tokens file: {tokens}") + recognizer = sherpa_onnx.OfflineRecognizer.from_sense_voice( + model=str(model), + tokens=str(tokens), + num_threads=int(os.environ.get("STT_THREADS") or 1), + use_itn=True, + language=language or "zh", + debug=False, + ) + samples, rate = read_wav(wav) + stream = recognizer.create_stream() + stream.accept_waveform(rate, samples) + recognizer.decode_stream(stream) + return TAG_RE.sub("", stream.result.text or "").strip() + + +def transcribe_whisper(wav: Path, model: str, language: str, prompt: str) -> str: + # huggingface.co is unreachable here; hf-mirror serves the same repos. + os.environ["HF_ENDPOINT"] = os.environ.get("STT_HF_ENDPOINT") or "https://hf-mirror.com" + os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") + from faster_whisper import WhisperModel + + root = Path(model) + asr = WhisperModel( + str(root) if root.exists() else model, + device="cpu", + compute_type="int8", + download_root=MODEL_ROOT, + cpu_threads=int(os.environ.get("STT_THREADS") or 0), + ) + segments, _info = asr.transcribe( + str(wav), + language=language or None, + beam_size=1, + vad_filter=True, + condition_on_previous_text=False, + initial_prompt=prompt or None, + ) + return "".join(seg.text for seg in segments).strip() + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--file", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--model", default="small") + ap.add_argument("--tokens", default="") + ap.add_argument("--lang", default="") + ap.add_argument("--prompt", default="以下是普通话的句子,请用简体中文转写。") + args = ap.parse_args() + + wav = Path(args.file) + if not wav.is_file(): + log(f"missing input: {wav}") + return 2 + + started = time.time() + if args.model.lower().endswith(".onnx"): + tokens = Path(args.tokens) if args.tokens else Path(args.model).with_name("tokens.txt") + text = transcribe_sense_voice(wav, Path(args.model), tokens, args.lang) + backend = "sense-voice" + else: + text = transcribe_whisper(wav, args.model, args.lang, args.prompt) + backend = "whisper" + + out = Path(args.out + ".txt") + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(text, encoding="utf-8") + log(f"ok backend={backend} chars={len(text)} elapsed={time.time() - started:.1f}s") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/wechat-a11y.cmd b/tools/wechat-a11y.cmd new file mode 100755 index 0000000..5df819b --- /dev/null +++ b/tools/wechat-a11y.cmd @@ -0,0 +1,3 @@ +@echo off +set QT_ACCESSIBILITY=1 +start "" "C:\Program Files\Tencent\Weixin\Weixin.exe" diff --git a/tools/wx_capture.py b/tools/wx_capture.py new file mode 100644 index 0000000..c8fefcf --- /dev/null +++ b/tools/wx_capture.py @@ -0,0 +1,29 @@ +"""Capture a window via PrintWindow (works without screen access).""" +import sys, ctypes +from ctypes import wintypes +import win32gui, win32ui, win32con +from PIL import Image + +def capture(hwnd, out): + left, top, right, bottom = win32gui.GetWindowRect(hwnd) + w, h = right - left, bottom - top + hwnd_dc = win32gui.GetWindowDC(hwnd) + mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc) + save_dc = mfc_dc.CreateCompatibleDC() + bmp = win32ui.CreateBitmap() + bmp.CreateCompatibleBitmap(mfc_dc, w, h) + save_dc.SelectObject(bmp) + # PW_RENDERFULLCONTENT = 2 + ok = ctypes.windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 2) + info = bmp.GetInfo() + bits = bmp.GetBitmapBits(True) + img = Image.frombuffer('RGB', (info['bmWidth'], info['bmHeight']), bits, 'raw', 'BGRX', 0, 1) + img.save(out) + win32gui.DeleteObject(bmp.GetHandle()) + save_dc.DeleteDC() + mfc_dc.DeleteDC() + win32gui.ReleaseDC(hwnd, hwnd_dc) + print('PrintWindow ok=', ok, 'size=', img.size, '->', out) + +if __name__ == '__main__': + capture(int(sys.argv[1]), sys.argv[2]) diff --git a/tools/wx_children.py b/tools/wx_children.py new file mode 100644 index 0000000..ce86da0 --- /dev/null +++ b/tools/wx_children.py @@ -0,0 +1,28 @@ +"""List child windows of a given HWND (all descendants).""" +import sys +import win32gui + +def walk(hwnd, depth=0, max_depth=4, out=None): + out = out if out is not None else [] + if depth > max_depth: + return out + kids = [] + def cb(h, _): + kids.append(h) + return True + try: + win32gui.EnumChildWindows(hwnd, cb, None) + except Exception: + pass + for h in kids: + rect = win32gui.GetWindowRect(h) + out.append((depth, h, win32gui.GetClassName(h), win32gui.GetWindowText(h), rect, + bool(win32gui.IsWindowVisible(h)))) + return out + +if __name__ == '__main__': + hwnd = int(sys.argv[1]) + rows = walk(hwnd) + for depth, h, cls, title, rect, vis in rows[:80]: + print(f"{' '*depth}{h} cls={cls!r} title={title!r} rect={rect} vis={vis}") + print("total:", len(rows)) diff --git a/tools/wx_dropfile.py b/tools/wx_dropfile.py new file mode 100644 index 0000000..1f3a494 --- /dev/null +++ b/tools/wx_dropfile.py @@ -0,0 +1,54 @@ +"""Simulate dropping a file onto a window via WM_DROPFILES.""" +import ctypes +import sys +import time +from ctypes import wintypes + +import win32gui + +user32 = ctypes.WinDLL("user32", use_last_error=True) +user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, ctypes.c_size_t, ctypes.c_ssize_t] +user32.PostMessageW.restype = wintypes.BOOL +kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + + +class DROPFILES(ctypes.Structure): + _fields_ = [ + ("pFiles", wintypes.DWORD), + ("pt", wintypes.POINT), + ("fNC", wintypes.BOOL), + ("fWide", wintypes.BOOL), + ] + + +def drop(hwnd, path, x, y): + files = path.encode("utf-16-le") + b"\x00\x00\x00\x00" + header = DROPFILES() + header.pFiles = ctypes.sizeof(DROPFILES) + header.pt = wintypes.POINT(x, y) + header.fNC = False + header.fWide = True + payload = bytes(header) + files + size = len(payload) + kernel32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t] + kernel32.GlobalAlloc.restype = wintypes.HGLOBAL + kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL] + kernel32.GlobalLock.restype = ctypes.c_void_p + kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL] + kernel32.GlobalUnlock.restype = wintypes.BOOL + hglobal = kernel32.GlobalAlloc(0x0042, size) # GMEM_MOVEABLE | GMEM_ZEROINIT + ptr = kernel32.GlobalLock(hglobal) + ctypes.memmove(ptr, payload, size) + kernel32.GlobalUnlock(hglobal) + user32.PostMessageW(hwnd, 0x0233, hglobal, 0) # WM_DROPFILES + return hglobal + + +if __name__ == "__main__": + hwnd = int(sys.argv[1]) + path = sys.argv[2] + x, y = (int(sys.argv[3]), int(sys.argv[4])) if len(sys.argv) > 4 else (400, 300) + win32gui.SetForegroundWindow(hwnd) + h = drop(hwnd, path, x, y) + time.sleep(2.0) + print("dropped", path, "hglobal", h) diff --git a/tools/wx_input_test.py b/tools/wx_input_test.py new file mode 100644 index 0000000..a55baa0 --- /dev/null +++ b/tools/wx_input_test.py @@ -0,0 +1,69 @@ +"""Input automation test: focus WeChat, Ctrl+F, type a query, screenshot the window.""" +import sys, time, ctypes +from ctypes import wintypes + +user32 = ctypes.windll.user32 +ULONG_PTR = ctypes.POINTER(ctypes.c_ulong) + + +class KEYBDINPUT(ctypes.Structure): + _fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD), + ("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)] + + +class INPUT(ctypes.Structure): + class _I(ctypes.Union): + _fields_ = [("ki", KEYBDINPUT), ("padding", ctypes.c_byte * 32)] + _anonymous_ = ("i",) + _fields_ = [("type", wintypes.DWORD), ("i", _I)] + + +KEYEVENTF_KEYUP = 0x0002 +KEYEVENTF_UNICODE = 0x0004 +VK_CONTROL = 0x11 +VK_F = 0x46 +VK_RETURN = 0x0D + + +def send_inputs(*inputs): + n = len(inputs) + arr = (INPUT * n)(*inputs) + user32.SendInput(n, arr, ctypes.sizeof(INPUT)) + + +def key_down(vk): + i = INPUT(type=1) + i.ki = KEYBDINPUT(wVk=vk, wScan=0, dwFlags=0, time=0, dwExtraInfo=None) + return i + + +def key_up(vk): + i = INPUT(type=1) + i.ki = KEYBDINPUT(wVk=vk, wScan=0, dwFlags=KEYEVENTF_KEYUP, time=0, dwExtraInfo=None) + return i + + +def type_text(text): + for ch in text: + for flag in (KEYEVENTF_UNICODE, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP): + i = INPUT(type=1) + i.ki = KEYBDINPUT(wVk=0, wScan=ord(ch), dwFlags=flag, time=0, dwExtraInfo=None) + send_inputs(i) + time.sleep(0.01) + + +def ctrl_key(vk): + send_inputs(key_down(VK_CONTROL), key_down(vk), key_up(vk), key_up(VK_CONTROL)) + + +if __name__ == '__main__': + hwnd = int(sys.argv[1]) + query = sys.argv[2] if len(sys.argv) > 2 else '文件传输助手' + user32.ShowWindow(hwnd, 9) + user32.SetForegroundWindow(hwnd) + time.sleep(0.8) + ctrl_key(VK_F) + time.sleep(0.6) + type_text(query) + time.sleep(1.2) + print('typed:', query) diff --git a/tools/wx_msaa.py b/tools/wx_msaa.py new file mode 100644 index 0000000..0dde5e5 --- /dev/null +++ b/tools/wx_msaa.py @@ -0,0 +1,39 @@ +"""Probe MSAA (IAccessible) tree of a window — some Qt/custom UIs expose this instead of UIA.""" +import sys, ctypes +from ctypes import wintypes, POINTER, byref +import comtypes +from comtypes import GUID +import comtypes.client +from comtypes.automation import IDispatch + +oleacc = ctypes.oledll.oleacc +user32 = ctypes.windll.user32 + +OBJID_CLIENT = 0xFFFFFFFC +IID_IAccessible = GUID("{618736E0-3C3D-11CF-810C-00AA00389B71}") + +def main(hwnd): + ptr = ctypes.POINTER(IDispatch)() + hr = oleacc.AccessibleObjectFromWindow(wintypes.HWND(hwnd), wintypes.DWORD(OBJID_CLIENT), + byref(IID_IAccessible), byref(ptr)) + print("hr:", hr, "ptr:", bool(ptr)) + if not ptr: + return + acc = ptr.QueryInterface(comtypes.gen.Accessibility.IAccessible) if False else ptr + # via IDispatch, call properties through dispinterface is messy; use oleacc helpers on the pointer + # Simpler: use accessible accChildCount through vtable is unavailable; try dynamic dispatch + try: + dispatch = ptr.QueryInterface(IDispatch) + print("dispatch ok") + except Exception as exc: + print("dispatch fail", exc) + # Use ctypes to call vtable method 7 (get_accChildCount is 4th method after IUnknown: 3 + 4?). + # IAccessible vtable: IUnknown(0-2), get_accParent(3), get_accChildCount(4), get_accChild(5)... + vtable = ctypes.cast(ptr, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents + fn_getcount = ctypes.WINFUNCTYPE(ctypes.HRESULT, ctypes.c_void_p, ctypes.POINTER(ctypes.c_long))(vtable[4]) + count = ctypes.c_long(-1) + hr = fn_getcount(ptr, byref(count)) + print("accChildCount hr:", hr, "count:", count.value) + +if __name__ == '__main__': + main(int(sys.argv[1])) diff --git a/tools/wx_ocr.py b/tools/wx_ocr.py new file mode 100644 index 0000000..db99b64 --- /dev/null +++ b/tools/wx_ocr.py @@ -0,0 +1,54 @@ +"""OCR a PNG (optionally cropped/scaled) with Windows.Media.Ocr (zh-Hans-CN).""" +import asyncio +import sys + +from PIL import Image +from winsdk.windows.graphics.imaging import BitmapDecoder +from winsdk.windows.media.ocr import OcrEngine +from winsdk.windows.globalization import Language +from winsdk.windows.storage import StorageFile, FileAccessMode + +CACHE = None + + +async def ocr_png(path): + file = await StorageFile.get_file_from_path_async(path) + stream = await file.open_async(FileAccessMode.READ) + decoder = await BitmapDecoder.create_async(stream) + bitmap = await decoder.get_software_bitmap_async() + engine = OcrEngine.try_create_from_language(Language('zh-Hans-CN')) + result = await engine.recognize_async(bitmap) + out = [] + for line in result.lines: + words = list(line.words) + if not words: + continue + x0 = min(w.bounding_rect.x for w in words) + y0 = min(w.bounding_rect.y for w in words) + x1 = max(w.bounding_rect.x + w.bounding_rect.width for w in words) + y1 = max(w.bounding_rect.y + w.bounding_rect.height for w in words) + out.append({'text': line.text, 'x': int(x0), 'y': int(y0), 'w': int(x1 - x0), 'h': int(y1 - y0)}) + return out + + +def main(): + path = sys.argv[1] + scale = float(sys.argv[2]) if len(sys.argv) > 2 else 1.0 + crop = None + if len(sys.argv) > 6: + crop = tuple(int(v) for v in sys.argv[3:7]) + img = Image.open(path).convert('RGB') + if crop: + img = img.crop(crop) + if scale != 1.0: + img = img.resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS) + tmp = path + f'.ocr{scale}.png' + img.save(tmp) + lines = asyncio.run(ocr_png(tmp)) + for item in lines: + print(f"[{item['x']},{item['y']} {item['w']}x{item['h']}] {item['text']}") + print('lines:', len(lines)) + + +if __name__ == '__main__': + main() diff --git a/tools/wx_ocr2.py b/tools/wx_ocr2.py new file mode 100644 index 0000000..793d2f8 --- /dev/null +++ b/tools/wx_ocr2.py @@ -0,0 +1,77 @@ +"""OCR helper with preprocessing for WeChat bubbles (Windows.Media.Ocr, zh-Hans).""" +import asyncio +import sys + +from PIL import Image, ImageOps +from winsdk.windows.graphics.imaging import BitmapDecoder +from winsdk.windows.media.ocr import OcrEngine +from winsdk.windows.globalization import Language +from winsdk.windows.storage import StorageFile, FileAccessMode + +ENGINE = None + + +def engine(): + global ENGINE + if ENGINE is None: + ENGINE = OcrEngine.try_create_from_language(Language('zh-Hans-CN')) + return ENGINE + + +async def ocr_png(path): + file = await StorageFile.get_file_from_path_async(path) + stream = await file.open_async(FileAccessMode.READ) + decoder = await BitmapDecoder.create_async(stream) + bitmap = await decoder.get_software_bitmap_async() + result = await engine().recognize_async(bitmap) + out = [] + for line in result.lines: + words = list(line.words) + if not words: + continue + x0 = min(w.bounding_rect.x for w in words) + y0 = min(w.bounding_rect.y for w in words) + x1 = max(w.bounding_rect.x + w.bounding_rect.width for w in words) + y1 = max(w.bounding_rect.y + w.bounding_rect.height for w in words) + out.append({'text': line.text, 'x': int(x0), 'y': int(y0), 'w': int(x1 - x0), 'h': int(y1 - y0)}) + return out + + +def preprocess(img, scale=2.5, invert=False): + img = img.convert('L') + img = ImageOps.autocontrast(img, cutoff=1) + # push mid-tones apart so bubble background becomes white and glyphs black + lut = [] + for i in range(256): + if i < 110: + lut.append(0) + elif i > 175: + lut.append(255) + else: + lut.append(int((i - 110) * 255 / 65)) + img = img.point(lut) + if invert: + img = ImageOps.invert(img) + if scale != 1.0: + img = img.resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS) + return img.convert('RGB') + + +def main(): + path = sys.argv[1] + scale = float(sys.argv[2]) if len(sys.argv) > 2 else 2.5 + crop = tuple(int(v) for v in sys.argv[3:7]) if len(sys.argv) > 6 else None + img = Image.open(path).convert('RGB') + if crop: + img = img.crop(crop) + for invert in (False, True): + out = path + f'.{scale}.{"inv" if invert else "std"}.png' + preprocess(img, scale, invert).save(out) + lines = asyncio.run(ocr_png(out)) + print(f'--- invert={invert}') + for item in lines: + print(f"[{item['x']},{item['y']} {item['w']}x{item['h']}] {item['text']}") + + +if __name__ == '__main__': + main() diff --git a/tools/wx_post.py b/tools/wx_post.py new file mode 100644 index 0000000..3fd8afc --- /dev/null +++ b/tools/wx_post.py @@ -0,0 +1,46 @@ +"""Message-injection helpers for WeChat: click / type / key by PostMessage.""" +import ctypes, sys, time +from ctypes import wintypes + +user32 = ctypes.WinDLL('user32', use_last_error=True) +WM_CHAR = 0x0102 +WM_KEYDOWN = 0x0100 +WM_KEYUP = 0x0101 +WM_LBUTTONDOWN = 0x0201 +WM_LBUTTONUP = 0x0202 +WM_MOUSEMOVE = 0x0200 +MK_LBUTTON = 0x0001 + + +def post_click(hwnd, x, y): + lp = (y << 16) | (x & 0xFFFF) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp) + user32.PostMessageW(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, lp) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp) + time.sleep(0.2) + + +def post_text(hwnd, text): + for ch in text: + user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 1) + time.sleep(0.02) + + +def post_key(hwnd, vk): + user32.PostMessageW(hwnd, WM_KEYDOWN, vk, 1) + user32.PostMessageW(hwnd, WM_KEYUP, vk, 0xC0000001) + + +if __name__ == '__main__': + hwnd = int(sys.argv[1]) + cmd = sys.argv[2] + if cmd == 'click': + post_click(hwnd, int(sys.argv[3]), int(sys.argv[4])) + print('clicked', sys.argv[3], sys.argv[4]) + elif cmd == 'text': + post_text(hwnd, sys.argv[3]) + print('typed', sys.argv[3]) + elif cmd == 'key': + post_key(hwnd, int(sys.argv[3], 0)) + print('key', sys.argv[3]) diff --git a/tools/wx_probe.py b/tools/wx_probe.py new file mode 100644 index 0000000..c88d5e5 --- /dev/null +++ b/tools/wx_probe.py @@ -0,0 +1,63 @@ +"""Probe WeChat (Weixin 4.x) windows and their UI Automation tree.""" +import sys, ctypes, json +import win32gui, win32process + +def list_windows(): + out = [] + def cb(hwnd, _): + if not win32gui.IsWindowVisible(hwnd): + return True + title = win32gui.GetWindowText(hwnd) + cls = win32gui.GetClassName(hwnd) + _, pid = win32process.GetWindowThreadProcessId(hwnd) + try: + import psutil + name = psutil.Process(pid).name() + except Exception: + name = '?' + out.append(dict(hwnd=hwnd, cls=cls, title=title, pid=pid, proc=name, + rect=win32gui.GetWindowRect(hwnd))) + return True + win32gui.EnumWindows(cb, None) + return out + +def dump(ctrl, depth=0, max_depth=5, lines=None, max_lines=400): + lines = lines if lines is not None else [] + if depth > max_depth or len(lines) > max_lines: + return lines + try: + r = ctrl.BoundingRectangle + rect = f"({r.left},{r.top},{r.right - r.left}x{r.bottom - r.top})" + except Exception: + rect = "?" + child = ctrl.GetFirstChildControl() + nchild = 0 + while child: + nchild += 1 + child = child.GetNextSiblingControl() + lines.append(" " * depth + f"[{ctrl.ControlTypeName}] name={ctrl.Name!r} aid={ctrl.AutomationId!r} cls={ctrl.ClassName!r} children={nchild} {rect}") + child = ctrl.GetFirstChildControl() + while child: + dump(child, depth + 1, max_depth, lines, max_lines) + child = child.GetNextSiblingControl() + return lines + +if __name__ == '__main__': + mode = sys.argv[1] if len(sys.argv) > 1 else 'list' + if mode == 'list': + for w in list_windows(): + print(json.dumps(w, ensure_ascii=False)) + else: + hwnd = int(sys.argv[2]) + depth = int(sys.argv[3]) if len(sys.argv) > 3 else 5 + out = sys.argv[4] if len(sys.argv) > 4 else None + import uiautomation as auto + ctrl = auto.ControlFromHandle(hwnd) + lines = dump(ctrl, 0, depth) + text = "\n".join(lines) + if out: + with open(out, 'w', encoding='utf-8') as f: + f.write(text) + print(f"wrote {len(lines)} lines to {out}") + else: + print(text) diff --git a/tools/wx_probe_popup.py b/tools/wx_probe_popup.py new file mode 100644 index 0000000..3d2e631 --- /dev/null +++ b/tools/wx_probe_popup.py @@ -0,0 +1,80 @@ +"""Click a point in WeChat and grab any transient popup window that appears.""" +import ctypes +import sys +import time + +import win32con +import win32gui +import win32process +import win32ui +from PIL import Image + +H = 197792 +PID = 10800 + + +def click(px, py): + left, top, _, _ = win32gui.GetWindowRect(H) + cx, cy = win32gui.ClientToScreen(H, (0, 0)) + ox, oy = cx - left, cy - top + x, y = px - ox, py - oy + lp = (y << 16) | (x & 0xFFFF) + u = ctypes.windll.user32 + u.PostMessageW(H, win32con.WM_MOUSEMOVE, 0, lp) + time.sleep(0.04) + u.PostMessageW(H, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lp) + time.sleep(0.04) + u.PostMessageW(H, win32con.WM_LBUTTONUP, 0, lp) + + +def grab(hwnd, path): + left, top, right, bottom = win32gui.GetWindowRect(hwnd) + w, h = right - left, bottom - top + if w <= 0 or h <= 0: + return False + hwnd_dc = win32gui.GetWindowDC(hwnd) + mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc) + save_dc = mfc_dc.CreateCompatibleDC() + bmp = win32ui.CreateBitmap() + bmp.CreateCompatibleBitmap(mfc_dc, w, h) + save_dc.SelectObject(bmp) + ok = ctypes.windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 2) + info = bmp.GetInfo() + img = Image.frombuffer('RGB', (info['bmWidth'], info['bmHeight']), + bmp.GetBitmapBits(True), 'raw', 'BGRX', 0, 1) + if ok: + img.save(path) + mfc_dc.DeleteDC() + save_dc.DeleteDC() + win32gui.ReleaseDC(hwnd, hwnd_dc) + return bool(ok) + + +def popups(): + found = [] + def cb(h, _): + try: + _, pid = win32process.GetWindowThreadProcessId(h) + if pid == PID and win32gui.IsWindowVisible(h): + cls = win32gui.GetClassName(h) + if cls == 'Qt51514QWindowToolSaveBits': + found.append(h) + except Exception: + pass + return True + win32gui.EnumWindows(cb, None) + return found + + +if __name__ == '__main__': + px, py = int(sys.argv[1]), int(sys.argv[2]) + click(px, py) + for delay in (0.15, 0.3, 0.6): + time.sleep(delay) + hits = popups() + print('delay', delay, 'popups', hits, [win32gui.GetWindowRect(h) for h in hits]) + for i, h in enumerate(hits): + p = rf'C:\Users\GuoAn\AppData\Local\Temp\wx_popup_{i}.png' + print('grab', h, grab(h, p), p) + if hits: + break diff --git a/tools/wx_real_hold.py b/tools/wx_real_hold.py new file mode 100644 index 0000000..4df2b8c --- /dev/null +++ b/tools/wx_real_hold.py @@ -0,0 +1,74 @@ +"""Hold the WeChat voice button with real SendInput while capturing mid-hold.""" +import ctypes +import sys +import time +from ctypes import wintypes + +import win32gui +import win32ui +from PIL import Image + +H = 197792 +user32 = ctypes.WinDLL('user32', use_last_error=True) + + +class MOUSEINPUT(ctypes.Structure): + _fields_ = [('dx', wintypes.LONG), ('dy', wintypes.LONG), ('mouseData', wintypes.DWORD), + ('dwFlags', wintypes.DWORD), ('time', wintypes.DWORD), + ('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong))] + + +class INPUT(ctypes.Structure): + class _I(ctypes.Union): + _fields_ = [('mi', MOUSEINPUT)] + + _anonymous_ = ('i',) + _fields_ = [('type', wintypes.DWORD), ('i', _I)] + + +def mouse(flag): + inp = INPUT() + inp.type = 0 + inp.mi = MOUSEINPUT(0, 0, 0, flag, 0, None) + return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(INPUT)) + + +def grab(path): + left, top, right, bottom = win32gui.GetWindowRect(H) + w, h = right - left, bottom - top + dc = win32gui.GetWindowDC(H) + mfc = win32ui.CreateDCFromHandle(dc) + mem = mfc.CreateCompatibleDC() + bmp = win32ui.CreateBitmap() + bmp.CreateCompatibleBitmap(mfc, w, h) + mem.SelectObject(bmp) + ok = ctypes.windll.user32.PrintWindow(H, mem.GetSafeHdc(), 2) + info = bmp.GetInfo() + img = Image.frombuffer('RGB', (info['bmWidth'], info['bmHeight']), + bmp.GetBitmapBits(True), 'raw', 'BGRX', 0, 1) + if ok: + img.save(path) + mfc.DeleteDC() + mem.DeleteDC() + win32gui.ReleaseDC(H, dc) + + +if __name__ == '__main__': + px, py = int(sys.argv[1]), int(sys.argv[2]) + secs = float(sys.argv[3]) if len(sys.argv) > 3 else 3.0 + left, top, _, _ = win32gui.GetWindowRect(H) + cx, cy = win32gui.ClientToScreen(H, (0, 0)) + ox, oy = cx - left, cy - top + sx, sy = cx + (px - ox), cy + py + print('screen', sx, sy) + user32.SetCursorPos(sx, sy) + time.sleep(0.3) + print('down', mouse(0x0002)) + time.sleep(0.9) + grab(r'C:\Users\GuoAn\AppData\Local\Temp\wx_hold_mid.png') + print('mid captured') + time.sleep(max(0.0, secs - 0.9)) + print('up', mouse(0x0004)) + time.sleep(1.2) + grab(r'C:\Users\GuoAn\AppData\Local\Temp\wx_hold_end.png') + print('end captured') diff --git a/tools/wx_show.py b/tools/wx_show.py new file mode 100644 index 0000000..b6b63a4 --- /dev/null +++ b/tools/wx_show.py @@ -0,0 +1,54 @@ +"""Bring WeChat main window to front and dump its UIA tree.""" +import sys, time, ctypes +import win32gui, uiautomation as auto + +def find_main(): + hwnd = ctypes.windll.user32.FindWindowW('Qt51514QWindowIcon', None) + if hwnd: + return hwnd + hits = [] + def cb(h, _): + cls = win32gui.GetClassName(h) + if cls in ('Qt51514QWindowIcon', 'WeChatMainWndForPC'): + hits.append(h) + return True + win32gui.EnumWindows(cb, None) + return hits[0] if hits else 0 + +def dump(ctrl, depth=0, max_depth=6, lines=None, max_lines=600): + lines = lines if lines is not None else [] + if depth > max_depth or len(lines) > max_lines: + return lines + try: + r = ctrl.BoundingRectangle + rect = f"({r.left},{r.top},{r.right - r.left}x{r.bottom - r.top})" + except Exception: + rect = "?" + kids = [] + try: + child = ctrl.GetFirstChildControl() + while child: + kids.append(child) + child = child.GetNextSiblingControl() + except Exception: + pass + lines.append(" " * depth + f"[{ctrl.ControlTypeName}] name={ctrl.Name!r} aid={ctrl.AutomationId!r} cls={ctrl.ClassName!r} n={len(kids)} {rect}") + for child in kids: + dump(child, depth + 1, max_depth, lines, max_lines) + return lines + +if __name__ == '__main__': + hwnd = find_main() + print("hwnd:", hwnd) + if hwnd: + u = ctypes.windll.user32 + u.ShowWindow(hwnd, 9) + u.SetForegroundWindow(hwnd) + time.sleep(1.2) + print("visible:", bool(u.IsWindowVisible(hwnd)), "rect:", win32gui.GetWindowRect(hwnd)) + ctrl = auto.ControlFromHandle(hwnd) + lines = dump(ctrl, 0, int(sys.argv[1]) if len(sys.argv) > 1 else 6) + out = sys.argv[2] if len(sys.argv) > 2 else r'C:\Users\GuoAn\AppData\Local\Temp\wx_tree.txt' + with open(out, 'w', encoding='utf-8') as f: + f.write("\n".join(lines)) + print(f"wrote {len(lines)} lines to {out}") diff --git a/tools/wx_uia_click.py b/tools/wx_uia_click.py new file mode 100644 index 0000000..56e528e --- /dev/null +++ b/tools/wx_uia_click.py @@ -0,0 +1,39 @@ +"""Click a UIA element by name inside a window (fallback: PostMessage click at center).""" +import sys, time +import uiautomation as auto + + +def main(hwnd, name): + win = auto.ControlFromHandle(hwnd) + if win is None: + print('no window for hwnd', hwnd) + return 1 + target = None + for ctl in win.GetChildren(): + if name in (ctl.Name or ''): + target = ctl + break + if target is None: + # search deeper + for ctl, depth in auto.WalkControl(win, maxDepth=6): + if name in (ctl.Name or ''): + target = ctl + break + if target is None: + print('not found:', name) + return 2 + rect = target.BoundingRectangle + print('found:', target.ControlTypeName, repr(target.Name), rect) + try: + target.Click() + print('clicked via UIA') + except Exception as exc: + print('uia click failed:', exc) + return 3 + return 0 + + +if __name__ == '__main__': + hwnd = int(sys.argv[1]) + name = sys.argv[2] + sys.exit(main(hwnd, name)) diff --git a/tools/wx_watch.py b/tools/wx_watch.py new file mode 100644 index 0000000..510a551 --- /dev/null +++ b/tools/wx_watch.py @@ -0,0 +1,74 @@ +"""Wait for WeChat main window (post-login) and dump its UIA tree.""" +import sys, time, ctypes, json +import win32gui, win32process, psutil, uiautomation as auto + +def weixin_pids(): + pids = set() + for p in psutil.process_iter(['pid', 'name']): + try: + if p.info['name'] and p.info['name'].lower() == 'weixin.exe': + pids.add(p.info['pid']) + except Exception: + pass + return pids + +def windows(): + rows = [] + def cb(h, _): + _, pid = win32process.GetWindowThreadProcessId(h) + if pid in weixin_pids(): + rect = win32gui.GetWindowRect(h) + rows.append(dict(hwnd=h, pid=pid, cls=win32gui.GetClassName(h), + title=win32gui.GetWindowText(h), + w=rect[2] - rect[0], h=rect[3] - rect[1])) + return True + win32gui.EnumWindows(cb, None) + return rows + +def dump(ctrl, depth=0, max_depth=8, lines=None, max_lines=1500): + lines = lines if lines is not None else [] + if depth > max_depth or len(lines) > max_lines: + return lines + try: + r = ctrl.BoundingRectangle + rect = f"({r.left},{r.top},{r.right - r.left}x{r.bottom - r.top})" + except Exception: + rect = "?" + kids = [] + try: + child = ctrl.GetFirstChildControl() + while child: + kids.append(child) + child = child.GetNextSiblingControl() + except Exception: + pass + lines.append(" " * depth + f"[{ctrl.ControlTypeName}] name={ctrl.Name!r} aid={ctrl.AutomationId!r} cls={ctrl.ClassName!r} n={len(kids)} {rect}") + for child in kids: + dump(child, depth + 1, max_depth, lines, max_lines) + return lines + +if __name__ == '__main__': + deadline = time.time() + int(sys.argv[1] if len(sys.argv) > 1 else 600) + out = sys.argv[2] if len(sys.argv) > 2 else r'C:\Users\GuoAn\AppData\Local\Temp\wx_main_tree.txt' + target = None + while time.time() < deadline: + for w in windows(): + if w['w'] >= 600 and 'Login' not in w['cls']: + target = w + break + if target: + break + time.sleep(5) + if not target: + print("TIMEOUT: main window not found") + sys.exit(2) + print("main window:", json.dumps(target, ensure_ascii=False)) + u = ctypes.windll.user32 + u.ShowWindow(target['hwnd'], 9) + u.SetForegroundWindow(target['hwnd']) + time.sleep(1.5) + ctrl = auto.ControlFromHandle(target['hwnd']) + lines = dump(ctrl) + with open(out, 'w', encoding='utf-8') as f: + f.write("\n".join(lines)) + print(f"wrote {len(lines)} lines to {out}") diff --git a/tools/wx_windows.py b/tools/wx_windows.py new file mode 100644 index 0000000..44e182d --- /dev/null +++ b/tools/wx_windows.py @@ -0,0 +1,26 @@ +"""List all windows (visible or not) belonging to Weixin processes.""" +import win32gui, win32process, psutil, json, sys + +target_pids = {} +for p in psutil.process_iter(['pid', 'name']): + try: + if p.info['name'] and p.info['name'].lower() in ('weixin.exe', 'wechat.exe'): + target_pids[p.info['pid']] = p.info['name'] + except Exception: + pass + +rows = [] +def cb(hwnd, _): + _, pid = win32process.GetWindowThreadProcessId(hwnd) + if pid in target_pids: + rows.append(dict(hwnd=hwnd, pid=pid, cls=win32gui.GetClassName(hwnd), + title=win32gui.GetWindowText(hwnd), + visible=bool(win32gui.IsWindowVisible(hwnd)), + iconic=bool(win32gui.IsIconic(hwnd)), + rect=win32gui.GetWindowRect(hwnd))) + return True + +win32gui.EnumWindows(cb, None) +print("pids:", target_pids) +for r in rows: + print(json.dumps(r, ensure_ascii=False))