| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
- #!/usr/bin/env python3
- """container-wecom-setup: idempotent WeCom channel writer for Hermes.
- Writes ONLY config.yaml (platforms.wecom) and .env (WECOM_*), per the
- channel iron rule: env + config.yaml platforms switches, nothing else.
- Pure stdlib; if PyYAML is importable the result is parse-validated.
- Works on Windows / Linux / macOS — all paths come from --home.
- """
- from __future__ import annotations
- import argparse
- from datetime import datetime
- from pathlib import Path
- import re
- import shutil
- import sys
- WS_DEFAULT = "wss://openws.work.weixin.qq.com"
- ENV_KEYS = ("WECOM_ENABLED", "WECOM_ALLOW_ALL_USERS", "WECOM_BOT_ID", "WECOM_SECRET", "WECOM_WEBSOCKET_URL")
- def fail(msg: str) -> "SystemExit":
- print("[REFUSE] " + msg)
- return SystemExit(20)
- def wecom_block(args: argparse.Namespace) -> str:
- return (
- " wecom:\n"
- " enabled: true\n"
- " extra:\n"
- " stream_keepalive_enabled: true\n"
- " stream_keepalive_interval_seconds: 120\n"
- f" bot_id: {args.bot_id}\n"
- f" secret: {args.secret}\n"
- f" websocket_url: {args.websocket_url}\n"
- f" dm_policy: {args.dm_policy}\n"
- f" group_policy: {args.group_policy}\n"
- " home_channel:\n"
- " platform: wecom\n"
- " chat_id: ''\n"
- )
- def update_config(config_path: Path, args: argparse.Namespace) -> str:
- text = config_path.read_text(encoding="utf-8") if config_path.is_file() else ""
- if text and not re.search(r"^platforms:\s*$", text, re.M):
- raise fail("config.yaml 缺少顶级 platforms: 段,拒绝猜测插入位置")
- if not text:
- text = "platforms:\n"
- # wecom 段 = " wecom:" 起,后续行要么 ≥4 空格缩进、要么是空行;遇到 2 空格缩进(下一个平台)即停
- existing = re.search(r"^ wecom:\n((?: {4,}[^\n]*|[ \t]*)\n)*", text, re.M)
- if args.disable:
- if not existing:
- return "unchanged"
- block = existing.group(0)
- new_block = re.sub(r"^ enabled:.*$", " enabled: false", block, count=1, flags=re.M)
- config_path.write_text(text.replace(block, new_block, 1), encoding="utf-8")
- return "disabled"
- block = wecom_block(args)
- if existing:
- config_path.write_text(text.replace(existing.group(0), block, 1), encoding="utf-8")
- return "updated"
- text = re.sub(r"^platforms:\s*$", "platforms:\n" + block.rstrip("\n"), text, count=1, flags=re.M)
- config_path.write_text(text, encoding="utf-8")
- return "created"
- def update_env(env_path: Path, args: argparse.Namespace) -> str:
- lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.is_file() else []
- # --disable 只翻开关,保留凭据以便再次开启
- values = {
- "WECOM_ENABLED": "false" if args.disable else "true",
- "WECOM_ALLOW_ALL_USERS": "true",
- "WECOM_BOT_ID": args.bot_id,
- "WECOM_SECRET": args.secret,
- "WECOM_WEBSOCKET_URL": args.websocket_url,
- }
- if args.disable:
- values = {k: v for k, v in values.items() if k == "WECOM_ENABLED" or (v and k in dict(l.split("=", 1) for l in lines if "=" in l))}
- seen = set()
- out = []
- for line in lines:
- key = line.split("=", 1)[0]
- if key in values:
- if key in seen: # drop duplicate keys, last write wins below
- continue
- seen.add(key)
- out.append(f"{key}={values[key]}")
- else:
- out.append(line)
- for key in ENV_KEYS:
- if key not in seen and values.get(key):
- out.append(f"{key}={values[key]}")
- env_path.write_text("\n".join(out) + "\n", encoding="utf-8")
- return "updated"
- def validate(home: Path) -> None:
- try:
- import yaml # type: ignore
- except ImportError:
- print("[WARN] 无 PyYAML,跳过解析校验")
- return
- cfg = yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8"))
- wecom = (cfg.get("platforms") or {}).get("wecom") or {}
- extra = wecom.get("extra") or {}
- state = "enabled" if wecom.get("enabled") else "disabled"
- print(f"[CHECK] platforms.wecom: {state}, bot_id={str(extra.get('bot_id'))[:8]}…, "
- f"matrix 段保留={'matrix' in (cfg.get('platforms') or {})}")
- def main() -> None:
- ap = argparse.ArgumentParser(description="Hermes 企微渠道配置(只写 config.yaml + .env)")
- ap.add_argument("--home", required=True, help="Hermes 数据目录(容器 /opt/data,自托管 ~/.hermes)")
- ap.add_argument("--bot-id", default="")
- ap.add_argument("--secret", default="")
- ap.add_argument("--dm-policy", default="open", choices=["open", "pairing", "disabled"])
- ap.add_argument("--group-policy", default="open", choices=["open", "pairing", "disabled"])
- ap.add_argument("--websocket-url", default=WS_DEFAULT)
- ap.add_argument("--disable", action="store_true", help="显式关闭企微渠道(保留凭据)")
- ap.add_argument("--check", action="store_true", help="只读校验当前状态")
- args = ap.parse_args()
- home = Path(args.home).expanduser()
- if not home.is_dir():
- raise fail(f"home 目录不存在: {home}")
- if not args.check and not args.disable:
- for name, value in (("bot-id", args.bot_id), ("secret", args.secret)):
- if not value or value != value.strip() or any(c.isspace() for c in value):
- raise fail(f"{name} 为空或含空白字符")
- if args.bot_id and (args.bot_id != args.secret) and args.secret == "" and not args.check and not args.disable:
- raise fail("secret 缺失")
- if args.check:
- validate(home)
- return
- stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
- config_path, env_path = home / "config.yaml", home / ".env"
- for path in (config_path, env_path):
- if path.is_file():
- shutil.copy2(path, path.with_name(f"{path.name}.bak-wecom-{stamp}"))
- config_action = update_config(config_path, args)
- env_action = update_env(env_path, args)
- validate(home)
- masked = f"{args.bot_id[:8]}…" if args.bot_id else "(未改)"
- print(f"[DONE] config.yaml: {config_action}; .env: {env_action}; bot_id={masked}")
- print("[NEXT] 重启网关后查日志确认无 errcode 853000(详见 SKILL.md §4–§6)")
- if __name__ == "__main__":
- main()
|