1417 lines
61 KiB
Python
1417 lines
61 KiB
Python
"""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 (<m00087/>) and other control tags are not
|
||
# something a WeChat contact should ever see.
|
||
text = re.sub(r"<m\d+\s*/?>", " ", str(text))
|
||
# The model sometimes leaks chat-template / tool-call markup such as
|
||
# "</ | | DSLM | | | parameter>"; 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)
|