Files

249 lines
10 KiB
Python

"""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())