1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
| import asyncio import json import os import re import subprocess import sys import time from pathlib import Path import aiohttp import websockets
BASE_DIR = Path(__file__).resolve().parent CONFIG_PATH = BASE_DIR / "config.json"
def load_config() -> dict: if not CONFIG_PATH.exists(): print(f"[Config] 未找到配置文件,请确认后重新启动服务") sys.exit(1)
try: with open(CONFIG_PATH, "r", encoding="utf-8") as f: cfg = json.load(f) print("[Config] 配置文件加载成功") return cfg except Exception as e: print(f"[Config] 配置文件解析失败: {e}") sys.exit(1)
CONFIG = load_config()
QQ_APP_ID = str(CONFIG["qq_bot"]["app_id"]) QQ_APP_SECRET = str(CONFIG["qq_bot"]["app_secret"]) DST_SCREEN_NAME = CONFIG["dst"]["screen_name"] DST_LOG_PATH = Path(CONFIG["dst"]["chat_log_path"]) MAX_MSG_LEN = int(CONFIG["dst"].get("max_msg_len", 60)) MAX_AUTHOR_LEN = int(CONFIG["dst"].get("max_author_len", 16))
_bind_file = Path(CONFIG["storage"].get("group_bind_file", "group_bind.txt")) CONFIG_FILE = _bind_file if _bind_file.is_absolute() else BASE_DIR / _bind_file
_nicks_file = Path(CONFIG["storage"].get("user_nicks_file", "user_nicks.json")) NICKS_FILE = _nicks_file if _nicks_file.is_absolute() else BASE_DIR / _nicks_file
TEMPLATES = CONFIG.get("templates", {}) QQ_ANNOUNCE_PREFIX = TEMPLATES.get("qq_to_game_announce", "").split("{")[0].strip() GAME_MSG_PREFIX = TEMPLATES.get("game_to_qq_chat", "").split("{")[0].strip()
def render_template(tpl_key: str, **kwargs) -> str: """根据模板 key 渲染内容,如果模板为空则返回空字符串(用于禁用该提示)""" tpl = TEMPLATES.get(tpl_key, "") if not tpl: return "" try: return tpl.format(**kwargs) except Exception as e: print(f"[Template] 模板 {tpl_key} 渲染失败: {e}") return ""
initial_group_id = None if CONFIG_FILE.exists(): try: initial_group_id = CONFIG_FILE.read_text(encoding="utf-8").strip() or None if initial_group_id: print(f"[Bridge] 从持久化文件恢复绑定的群: {initial_group_id}") except Exception as e: print(f"[Bridge] 读取群绑定文件失败: {e}")
state = { "access_token": "", "token_expires_at": 0, "group_openid": initial_group_id, "last_seq": 0, "user_nicks": {}, "nicks_file_mtime": 0, }
def load_nicks_from_disk(force: bool = False): """从磁盘加载昵称映射,支持检测文件修改后自动热更新""" if not NICKS_FILE.exists(): try: NICKS_FILE.write_text("{}", encoding="utf-8") except Exception: pass return
try: current_mtime = NICKS_FILE.stat().st_mtime if force or current_mtime > state["nicks_file_mtime"]: content = NICKS_FILE.read_text(encoding="utf-8").strip() state["user_nicks"] = json.loads(content) if content else {} state["nicks_file_mtime"] = current_mtime print(f"[NickManager] 昵称配置已更新/热加载,当前已绑定 {len(state['user_nicks'])} 位成员") except Exception as e: print(f"[NickManager] 读取 user_nicks.json 异常: {e}")
def save_nick_to_disk(member_openid: str, nick: str): """保存新备注到本地文件""" load_nicks_from_disk() state["user_nicks"][member_openid] = nick try: NICKS_FILE.write_text(json.dumps(state["user_nicks"], ensure_ascii=False, indent=2), encoding="utf-8") state["nicks_file_mtime"] = NICKS_FILE.stat().st_mtime print(f"[NickManager] 成功写入备注: {member_openid} -> {nick}") except Exception as e: print(f"[NickManager] 写入 user_nicks.json 失败: {e}")
def resolve_author_nick(event_data: dict) -> str: """解析发送者昵称:支持热重载,优先自定义备注""" load_nicks_from_disk()
author_data = event_data.get("author", {}) member_openid = author_data.get("member_openid") or author_data.get("id", "")
if member_openid in state["user_nicks"]: return state["user_nicks"][member_openid]
raw_name = author_data.get("username", "").strip() if raw_name and raw_name != ".": return raw_name
return f"群友_{member_openid[:4]}"
QQ_FACE_PATTERN = re.compile(r"\[?<face(?:Type)?\b[^>\r\n]{1,200}?>\]?|\[?<face:\d+>\]?", re.IGNORECASE) EMOJI_PATTERN = re.compile( "[" "\U0001F300-\U0001F5FF" "\U0001F600-\U0001F64F" "\U0001F680-\U0001F6FF" "\U0001F900-\U0001F9FF" "\U0001FA70-\U0001FAFF" "\U0001F1E6-\U0001F1FF" "\U00002600-\U000026FF" "\U00002700-\U000027BF" "]+", flags=re.UNICODE ) URL_PATTERN = re.compile(r"https?://[^\s]+", re.IGNORECASE)
def summarize_qq_message(event_data: dict, app_id: str) -> str: """清洗 QQ 消息,格式化特殊实体与附件""" raw_content = event_data.get("content", "").strip()
clean_text = raw_content.replace(f"<@!{app_id}>", "").strip() clean_text = QQ_FACE_PATTERN.sub("[表情]", clean_text) clean_text = EMOJI_PATTERN.sub("[表情]", clean_text) clean_text = URL_PATTERN.sub("[链接]", clean_text)
attachments = event_data.get("attachments", []) if attachments: attach_tags = [] for att in attachments: content_type = str(att.get("content_type", "")).lower() if "face" in content_type or "sticker" in content_type: attach_tags.append("[表情]") elif "image" in content_type: attach_tags.append("[图片]") elif "video" in content_type: attach_tags.append("[视频]") elif "audio" in content_type or "voice" in content_type: attach_tags.append("[语音]") else: attach_tags.append("[文件]")
media_str = "".join(attach_tags) clean_text = f"{clean_text} {media_str}".strip() if clean_text else media_str
clean_text = re.sub(r"\[+表情\]+", "[表情]", clean_text) clean_text = re.sub(r"\[+图片\]+", "[图片]", clean_text) clean_text = re.sub(r"(\[表情\]\s*)+", "[表情]", clean_text) clean_text = re.sub(r"(\[图片\]\s*)+", "[图片]", clean_text)
return clean_text.strip()
async def get_access_token(): now = asyncio.get_event_loop().time() if state["access_token"] and now < state["token_expires_at"]: return state["access_token"]
url = "https://bots.qq.com/app/getAppAccessToken" payload = {"appId": QQ_APP_ID, "clientSecret": QQ_APP_SECRET} async with aiohttp.ClientSession() as session: async with session.post(url, json=payload) as resp: data = await resp.json() state["access_token"] = data["access_token"] state["token_expires_at"] = now + int(data.get("expires_in", 7200)) - 60 return state["access_token"]
async def send_to_qq_group(content: str, reply_msg_id: str = None): if not content: return if not state["group_openid"]: print("[Bridge] 未捕获到 group_openid,需群内先发送消息激活绑定") return
token = await get_access_token() url = f"https://api.sgroup.qq.com/v2/groups/{state['group_openid']}/messages" headers = { "Authorization": f"QQBot {token}", "Content-Type": "application/json" } payload = {"content": content, "msg_type": 0} if reply_msg_id: payload["msg_id"] = reply_msg_id
async with aiohttp.ClientSession() as session: async with session.post(url, json=payload, headers=headers) as resp: if resp.status != 200: print(f"[Bridge] 推送群消息失败 [{resp.status}]: {await resp.text()}")
def sanitize_dst_text(text: str, max_len: int) -> str: """清洗并截断传入饥荒控制台的文本,对 Lua 字符转义""" if not text: return ""
cleaned = text.replace("\r\n", " ").replace("\n", " ").replace("\r", " ").replace("\t", " ") cleaned = "".join(ch for ch in cleaned if ord(ch) >= 32) cleaned = re.sub(r"\s+", " ", cleaned).strip()
if len(cleaned) > max_len: cleaned = cleaned[:max_len] + "..."
cleaned = cleaned.replace("\\", "\\\\").replace('"', '\\"') return cleaned
def announce_to_dst(author: str, text: str): """向饥荒主世界控制台注入广播""" safe_author = sanitize_dst_text(author, max_len=MAX_AUTHOR_LEN) safe_text = sanitize_dst_text(text, max_len=MAX_MSG_LEN)
if not safe_text: return
dst_msg = render_template("qq_to_game_announce", author=safe_author, content=safe_text) if not dst_msg: return
lua_cmd = f'c_announce("{dst_msg}")\n' cmd_args = [ "screen", "-S", DST_SCREEN_NAME, "-p", "0", "-X", "stuff", lua_cmd ]
try: subprocess.run(cmd_args, check=True) except Exception as e: print(f"[Bridge] 注入饥荒控制台异常: {e}")
async def tail_server_log(): print(f"[LogWatcher] 开始监听饥荒全服聊天日志: {DST_LOG_PATH}") while not DST_LOG_PATH.exists(): print("[LogWatcher] 等待聊天日志生成...") await asyncio.sleep(2)
proc = await asyncio.create_subprocess_exec( "tail", "-n", "0", "-F", str(DST_LOG_PATH), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL )
say_pattern = re.compile(r"\[Say\]\s*\([^)]*\)\s*([^:]+):\s*(.*)") join_pattern = re.compile(r"\[Join Announcement\]\s*(.*)") leave_pattern = re.compile(r"\[Leave Announcement\]\s*(.*)") death_pattern = re.compile(r"\[Death Announcement\]\s*(.*)")
while True: line_bytes = await proc.stdout.readline() if not line_bytes: await asyncio.sleep(0.5) continue
line = line_bytes.decode("utf-8", errors="ignore").strip() if not line: continue
say_match = say_pattern.search(line) if say_match: player = say_match.group(1).strip() content = say_match.group(2).strip()
if QQ_ANNOUNCE_PREFIX and (content.startswith(QQ_ANNOUNCE_PREFIX) or QQ_ANNOUNCE_PREFIX in content): continue
print(f"[游戏公屏] {player}: {content}") msg = render_template("game_to_qq_chat", player=player, content=content) await send_to_qq_group(msg) continue
join_match = join_pattern.search(line) if join_match: player = join_match.group(1).strip() print(f"[玩家上线] {player}") msg = render_template("game_to_qq_join", player=player) await send_to_qq_group(msg) continue
leave_match = leave_pattern.search(line) if leave_match: player = leave_match.group(1).strip() print(f"[玩家下线] {player}") msg = render_template("game_to_qq_leave", player=player) await send_to_qq_group(msg) continue
death_match = death_pattern.search(line) if death_match: death_info = death_match.group(1).strip() print(f"[玩家阵亡] {death_info}") msg = render_template("game_to_qq_death", death_info=death_info) await send_to_qq_group(msg) continue
async def start_qq_gateway(): load_nicks_from_disk(force=True)
while True: try: token = await get_access_token() async with aiohttp.ClientSession() as session: async with session.get( "https://api.sgroup.qq.com/gateway", headers={"Authorization": f"QQBot {token}"} ) as resp: gw_data = await resp.json() gateway_url = gw_data["url"]
async with websockets.connect(gateway_url) as ws: identify_payload = { "op": 2, "d": { "token": f"QQBot {token}", "intents": 1 << 25, "shard": [0, 1] } } await ws.send(json.dumps(identify_payload)) print("[Gateway] 已连接至 QQ WebSocket 网关 (Intents: 1 << 25)")
async for raw_msg in ws: msg = json.loads(raw_msg) op = msg.get("op") t = msg.get("t") d = msg.get("d", {})
if op == 10: heartbeat_interval = d["heartbeat_interval"] / 1000 async def heartbeat(): while True: await asyncio.sleep(heartbeat_interval) await ws.send(json.dumps({"op": 1, "d": state["last_seq"]})) asyncio.create_task(heartbeat())
elif op == 0: state["last_seq"] = msg.get("s", state["last_seq"])
if t in ["GROUP_AT_MESSAGE_CREATE", "GROUP_MESSAGE_CREATE"]: print(f"[{CONFIG['qq_bot']['app_id']}] 收到群事件: {t}, msg_id: {d.get('id')}, content: {d.get('content')}") if d.get("author", {}).get("bot", False): continue
current_group = d.get("group_openid") if current_group and current_group != state["group_openid"]: state["group_openid"] = current_group try: CONFIG_FILE.write_text(current_group, encoding="utf-8") print(f"[Bridge] 自动同步群绑定: {current_group}") except Exception as e: print(f"[Bridge] 持久化群文件失败: {e}")
clean_content = summarize_qq_message(d, QQ_APP_ID) msg_id = d.get("id")
cmd_match = re.match(r"^[#/](改名|绑定|备注|角色|人物)\s+(.+)$", clean_content) if cmd_match: action_type = cmd_match.group(1) new_nick = cmd_match.group(2).strip() member_openid = d.get("author", {}).get("member_openid") or d.get("author", {}).get("id", "") if member_openid and new_nick: save_nick_to_disk(member_openid, new_nick) label = "角色/身份" if action_type in ["角色", "人物"] else "发言备注" reply_text = render_template("qq_nick_set_success", label=label, nick=new_nick) print(f"[NickManager] 用户自主绑定成功: {new_nick} ({member_openid})") await send_to_qq_group(reply_text, reply_msg_id=msg_id) continue
if GAME_MSG_PREFIX and clean_content.startswith(GAME_MSG_PREFIX): continue
if clean_content: author_name = resolve_author_nick(d) print(f"[QQ -> DST] {author_name}: {clean_content}") announce_to_dst(author_name, clean_content)
except Exception as e: print(f"[Gateway] 连接异常: {e},5秒后自动重连") await asyncio.sleep(5)
async def main(): await asyncio.gather( tail_server_log(), start_qq_gateway() )
if __name__ == '__main__': asyncio.run(main())
|