docs: restructure markdown docs and publish the bridge
This commit is contained in:
+13
@@ -0,0 +1,13 @@
|
||||
# 运行时产物
|
||||
config.json
|
||||
*.log
|
||||
tmp/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.wav
|
||||
*.mp3
|
||||
*.png
|
||||
|
||||
# 本地敏感信息
|
||||
*.env
|
||||
secrets.json
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Create a git repo for the project and push it to the Gitea remote."""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from dulwich import porcelain
|
||||
from dulwich.repo import Repo
|
||||
|
||||
ROOT = r"C:\Users\GuoAn\Documents\rob-for-qq-vx"
|
||||
REMOTE = "http://xiaoan:guoan123@git.xiaoan.xyz/xiaoan/Rob-for-qq-VX.git"
|
||||
BRANCH = "refs/heads/main"
|
||||
|
||||
SKIP_DIRS = {".git", "__pycache__", "tmp"}
|
||||
SKIP_FILES = {"config.json"}
|
||||
SKIP_EXT = {".log", ".pyc", ".wav", ".mp3", ".png"}
|
||||
|
||||
|
||||
def walk():
|
||||
for dirpath, dirnames, filenames in os.walk(ROOT):
|
||||
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
||||
for name in filenames:
|
||||
if name in SKIP_FILES:
|
||||
continue
|
||||
if os.path.splitext(name)[1].lower() in SKIP_EXT:
|
||||
continue
|
||||
full = os.path.join(dirpath, name)
|
||||
yield os.path.relpath(full, ROOT).replace("\\", "/")
|
||||
|
||||
|
||||
def main():
|
||||
if not os.path.isdir(os.path.join(ROOT, ".git")):
|
||||
Repo.init(ROOT, mkdir=False)
|
||||
repo = Repo(ROOT)
|
||||
files = sorted(walk())
|
||||
print(f"files: {len(files)}")
|
||||
porcelain.add(repo, files)
|
||||
msg = "docs: restructure markdown docs and publish the bridge"
|
||||
try:
|
||||
porcelain.commit(repo, message=msg,
|
||||
author=b"xiaoan <xiaoan@xiaoan.xyz>",
|
||||
committer=b"xiaoan <xiaoan@xiaoan.xyz>")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print("commit skipped:", exc)
|
||||
porcelain.branch_create(repo, "main", force=True)
|
||||
print("pushing ...")
|
||||
porcelain.push(repo, REMOTE, f"refs/heads/main:{BRANCH}")
|
||||
print("pushed ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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)
|
||||
@@ -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
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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")
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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()))
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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())
|
||||
@@ -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")
|
||||
@@ -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 注入) |
|
||||
@@ -0,0 +1,44 @@
|
||||
# 人设与记忆
|
||||
|
||||
## 一个身份,两个平台
|
||||
|
||||
微信和 QQ 在 `obmux` 里被合并成一个 OneBot 端点,所以 DSH 只看到一个会话来源,
|
||||
人格卡、记忆、上下文都是同一份。
|
||||
|
||||
但**会话 ID 不同**(`onebot-private-<qq号>` / `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` 重新注入。
|
||||
+131
@@ -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://<TTS 机器>: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
|
||||
```
|
||||
@@ -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 <hwnd> %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` 只能拿到灰图。
|
||||
@@ -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'<err {ctypes.get_last_error()}>'
|
||||
|
||||
|
||||
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())
|
||||
@@ -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]))
|
||||
@@ -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)
|
||||
+100
@@ -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<string> List(int dataFlow)
|
||||
{
|
||||
return ListWithMask(dataFlow, 1);
|
||||
}
|
||||
|
||||
public static List<string> ListAll(int dataFlow)
|
||||
{
|
||||
// 0x0F: active | disabled | notpresent | unplugged
|
||||
return ListWithMask(dataFlow, 0x0F);
|
||||
}
|
||||
|
||||
public static List<string> ListWithMask(int dataFlow, int mask)
|
||||
{
|
||||
var result = new List<string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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_<uin>.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)
|
||||
})
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
"""Standalone STT entry point for dsh-onebot-qq.
|
||||
|
||||
Called by the plugin as its "custom" engine:
|
||||
|
||||
python stt.py --file <wav> --out <workdir>/out --model <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 <out>.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())
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
set QT_ACCESSIBILITY=1
|
||||
start "" "C:\Program Files\Tencent\Weixin\Weixin.exe"
|
||||
@@ -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])
|
||||
@@ -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))
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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]))
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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])
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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')
|
||||
@@ -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}")
|
||||
@@ -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))
|
||||
@@ -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}")
|
||||
@@ -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))
|
||||
Reference in New Issue
Block a user