wecom_setup.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #!/usr/bin/env python3
  2. """container-wecom-setup: idempotent WeCom channel writer for Hermes.
  3. Writes ONLY config.yaml (platforms.wecom) and .env (WECOM_*), per the
  4. channel iron rule: env + config.yaml platforms switches, nothing else.
  5. Pure stdlib; if PyYAML is importable the result is parse-validated.
  6. Works on Windows / Linux / macOS — all paths come from --home.
  7. """
  8. from __future__ import annotations
  9. import argparse
  10. from datetime import datetime
  11. from pathlib import Path
  12. import re
  13. import shutil
  14. import sys
  15. WS_DEFAULT = "wss://openws.work.weixin.qq.com"
  16. ENV_KEYS = ("WECOM_ENABLED", "WECOM_ALLOW_ALL_USERS", "WECOM_BOT_ID", "WECOM_SECRET", "WECOM_WEBSOCKET_URL")
  17. def fail(msg: str) -> "SystemExit":
  18. print("[REFUSE] " + msg)
  19. return SystemExit(20)
  20. def wecom_block(args: argparse.Namespace) -> str:
  21. return (
  22. " wecom:\n"
  23. " enabled: true\n"
  24. " extra:\n"
  25. " stream_keepalive_enabled: true\n"
  26. " stream_keepalive_interval_seconds: 120\n"
  27. f" bot_id: {args.bot_id}\n"
  28. f" secret: {args.secret}\n"
  29. f" websocket_url: {args.websocket_url}\n"
  30. f" dm_policy: {args.dm_policy}\n"
  31. f" group_policy: {args.group_policy}\n"
  32. " home_channel:\n"
  33. " platform: wecom\n"
  34. " chat_id: ''\n"
  35. )
  36. def update_config(config_path: Path, args: argparse.Namespace) -> str:
  37. text = config_path.read_text(encoding="utf-8") if config_path.is_file() else ""
  38. if text and not re.search(r"^platforms:\s*$", text, re.M):
  39. raise fail("config.yaml 缺少顶级 platforms: 段,拒绝猜测插入位置")
  40. if not text:
  41. text = "platforms:\n"
  42. # wecom 段 = " wecom:" 起,后续行要么 ≥4 空格缩进、要么是空行;遇到 2 空格缩进(下一个平台)即停
  43. existing = re.search(r"^ wecom:\n((?: {4,}[^\n]*|[ \t]*)\n)*", text, re.M)
  44. if args.disable:
  45. if not existing:
  46. return "unchanged"
  47. block = existing.group(0)
  48. new_block = re.sub(r"^ enabled:.*$", " enabled: false", block, count=1, flags=re.M)
  49. config_path.write_text(text.replace(block, new_block, 1), encoding="utf-8")
  50. return "disabled"
  51. block = wecom_block(args)
  52. if existing:
  53. config_path.write_text(text.replace(existing.group(0), block, 1), encoding="utf-8")
  54. return "updated"
  55. text = re.sub(r"^platforms:\s*$", "platforms:\n" + block.rstrip("\n"), text, count=1, flags=re.M)
  56. config_path.write_text(text, encoding="utf-8")
  57. return "created"
  58. def update_env(env_path: Path, args: argparse.Namespace) -> str:
  59. lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.is_file() else []
  60. # --disable 只翻开关,保留凭据以便再次开启
  61. values = {
  62. "WECOM_ENABLED": "false" if args.disable else "true",
  63. "WECOM_ALLOW_ALL_USERS": "true",
  64. "WECOM_BOT_ID": args.bot_id,
  65. "WECOM_SECRET": args.secret,
  66. "WECOM_WEBSOCKET_URL": args.websocket_url,
  67. }
  68. if args.disable:
  69. 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))}
  70. seen = set()
  71. out = []
  72. for line in lines:
  73. key = line.split("=", 1)[0]
  74. if key in values:
  75. if key in seen: # drop duplicate keys, last write wins below
  76. continue
  77. seen.add(key)
  78. out.append(f"{key}={values[key]}")
  79. else:
  80. out.append(line)
  81. for key in ENV_KEYS:
  82. if key not in seen and values.get(key):
  83. out.append(f"{key}={values[key]}")
  84. env_path.write_text("\n".join(out) + "\n", encoding="utf-8")
  85. return "updated"
  86. def validate(home: Path) -> None:
  87. try:
  88. import yaml # type: ignore
  89. except ImportError:
  90. print("[WARN] 无 PyYAML,跳过解析校验")
  91. return
  92. cfg = yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8"))
  93. wecom = (cfg.get("platforms") or {}).get("wecom") or {}
  94. extra = wecom.get("extra") or {}
  95. state = "enabled" if wecom.get("enabled") else "disabled"
  96. print(f"[CHECK] platforms.wecom: {state}, bot_id={str(extra.get('bot_id'))[:8]}…, "
  97. f"matrix 段保留={'matrix' in (cfg.get('platforms') or {})}")
  98. def main() -> None:
  99. ap = argparse.ArgumentParser(description="Hermes 企微渠道配置(只写 config.yaml + .env)")
  100. ap.add_argument("--home", required=True, help="Hermes 数据目录(容器 /opt/data,自托管 ~/.hermes)")
  101. ap.add_argument("--bot-id", default="")
  102. ap.add_argument("--secret", default="")
  103. ap.add_argument("--dm-policy", default="open", choices=["open", "pairing", "disabled"])
  104. ap.add_argument("--group-policy", default="open", choices=["open", "pairing", "disabled"])
  105. ap.add_argument("--websocket-url", default=WS_DEFAULT)
  106. ap.add_argument("--disable", action="store_true", help="显式关闭企微渠道(保留凭据)")
  107. ap.add_argument("--check", action="store_true", help="只读校验当前状态")
  108. args = ap.parse_args()
  109. home = Path(args.home).expanduser()
  110. if not home.is_dir():
  111. raise fail(f"home 目录不存在: {home}")
  112. if not args.check and not args.disable:
  113. for name, value in (("bot-id", args.bot_id), ("secret", args.secret)):
  114. if not value or value != value.strip() or any(c.isspace() for c in value):
  115. raise fail(f"{name} 为空或含空白字符")
  116. if args.bot_id and (args.bot_id != args.secret) and args.secret == "" and not args.check and not args.disable:
  117. raise fail("secret 缺失")
  118. if args.check:
  119. validate(home)
  120. return
  121. stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
  122. config_path, env_path = home / "config.yaml", home / ".env"
  123. for path in (config_path, env_path):
  124. if path.is_file():
  125. shutil.copy2(path, path.with_name(f"{path.name}.bak-wecom-{stamp}"))
  126. config_action = update_config(config_path, args)
  127. env_action = update_env(env_path, args)
  128. validate(home)
  129. masked = f"{args.bot_id[:8]}…" if args.bot_id else "(未改)"
  130. print(f"[DONE] config.yaml: {config_action}; .env: {env_action}; bot_id={masked}")
  131. print("[NEXT] 重启网关后查日志确认无 errcode 853000(详见 SKILL.md §4–§6)")
  132. if __name__ == "__main__":
  133. main()