docs: restructure markdown docs and publish the bridge

This commit is contained in:
xiaoan
2026-11-14 22:50:21 +08:00
commit 38dccd9a9f
45 changed files with 4353 additions and 0 deletions
+25
View File
@@ -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
}
}
}
+248
View File
@@ -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())
+39
View File
@@ -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())
+43
View File
@@ -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())
+44
View File
@@ -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())
+71
View File
@@ -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")
+36
View File
@@ -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())
+91
View File
@@ -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())
+49
View File
@@ -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())
+39
View File
@@ -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())
+60
View File
@@ -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()))
+1416
View File
File diff suppressed because it is too large Load Diff
+141
View File
@@ -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())
+110
View File
@@ -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")