wechat.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. """
  2. agentpaas wechat — 微信 ClawBot iLink 桥接模块
  3. 将微信消息转发到 AgentPaaS agent,回复自动发回微信。
  4. 流程:
  5. 微信用户发消息 → iLink 长轮询收到 → AgentPaaS agent 处理 → iLink 回复微信
  6. 用法:
  7. agentpaas wechat <agent_id> # 绑定 agent 并开始监听
  8. agentpaas wechat <agent_id> --daemon # 后台运行
  9. agentpaas wechat status # 查看连接状态
  10. agentpaas wechat stop # 停止后台进程
  11. """
  12. from __future__ import annotations
  13. import asyncio
  14. import json
  15. import os
  16. import signal
  17. import sys
  18. import time
  19. from pathlib import Path
  20. # ── 配置 ────────────────────────────────────────────────────
  21. CREDENTIALS_DIR = Path.home() / ".agentpaas" / "wechat"
  22. CREDENTIALS_FILE = CREDENTIALS_DIR / "credentials.json"
  23. PID_FILE = CREDENTIALS_DIR / "daemon.pid"
  24. DEFAULT_BASE_URL = "https://ilinkai.weixin.qq.com"
  25. DEFAULT_CDN_URL = "https://novac2c.cdn.weixin.qq.com/c2c"
  26. def _save_credentials(data):
  27. CREDENTIALS_DIR.mkdir(parents=True, exist_ok=True)
  28. CREDENTIALS_DIR.chmod(0o700)
  29. CREDENTIALS_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False))
  30. CREDENTIALS_FILE.chmod(0o600)
  31. def _load_credentials():
  32. if CREDENTIALS_FILE.exists():
  33. return json.loads(CREDENTIALS_FILE.read_text())
  34. return None
  35. # ── 登录 ────────────────────────────────────────────────────
  36. async def login():
  37. """扫码登录微信 ClawBot,返回凭证。"""
  38. from wechat_clawbot.auth.login_qr import (
  39. start_weixin_login_with_qr,
  40. wait_for_weixin_login,
  41. )
  42. print("🔗 微信 ClawBot 绑定")
  43. print(" 1. 打开微信 → 设置 → 插件 → 开启 ClawBot")
  44. print(" 2. 扫描下方二维码:\n")
  45. # 获取二维码
  46. qr_result = await start_weixin_login_with_qr(
  47. api_base_url=DEFAULT_BASE_URL,
  48. bot_type="3",
  49. )
  50. if qr_result.qrcode_url:
  51. try:
  52. import qrcode
  53. # 保存为图片并打开
  54. qr_img_path = CREDENTIALS_DIR / "login_qr.png"
  55. CREDENTIALS_DIR.mkdir(parents=True, exist_ok=True)
  56. qr = qrcode.QRCode(border=2, box_size=10)
  57. qr.add_data(qr_result.qrcode_url)
  58. qr.make(fit=True)
  59. img = qr.make_image(fill_color="black", back_color="white")
  60. img.save(str(qr_img_path))
  61. print(" 二维码已保存: {}".format(qr_img_path))
  62. # macOS 自动打开图片
  63. import platform, subprocess as sp
  64. if platform.system() == "Darwin":
  65. sp.Popen(["open", str(qr_img_path)])
  66. print(" (已自动打开图片,请用微信扫码)")
  67. else:
  68. print(" 请打开图片扫码: {}".format(qr_img_path))
  69. # 同时终端小尺寸显示
  70. qr_small = qrcode.QRCode(border=1, box_size=1)
  71. qr_small.add_data(qr_result.qrcode_url)
  72. qr_small.make(fit=True)
  73. qr_small.print_tty()
  74. except Exception:
  75. pass
  76. print("\n 备用链接: {}".format(qr_result.qrcode_url))
  77. else:
  78. print(" {}".format(qr_result.message))
  79. print("\n 等待扫码...", end="", flush=True)
  80. # 等待扫码确认
  81. login_result = await wait_for_weixin_login(
  82. session_key=qr_result.session_key,
  83. api_base_url=DEFAULT_BASE_URL,
  84. bot_type="3",
  85. timeout_ms=480_000, # 8 分钟超时
  86. verbose=False,
  87. )
  88. if not login_result.connected:
  89. print(" 失败")
  90. print(" {}".format(login_result.message))
  91. return None
  92. print(" 成功!")
  93. creds = {
  94. "bot_token": login_result.bot_token,
  95. "account_id": login_result.account_id,
  96. "base_url": login_result.base_url or DEFAULT_BASE_URL,
  97. "user_id": login_result.user_id,
  98. "login_time": time.strftime("%Y-%m-%dT%H:%M:%S"),
  99. }
  100. _save_credentials(creds)
  101. print(" 凭证已保存到 {}".format(CREDENTIALS_FILE))
  102. return creds
  103. # ── Agent 调用 ──────────────────────────────────────────────
  104. def call_agent_sync(agent_id, text):
  105. """同步调用 AgentPaaS agent (通过 HTTP API)。"""
  106. from agentpaas.__main__ import api
  107. try:
  108. data = api("POST", "/api/v1/agents/{}/run".format(agent_id),
  109. {"input": text})
  110. return data.get("output", "(无回复)")
  111. except SystemExit:
  112. return "(Agent 调用失败,请检查 PaaS 服务是否在运行)"
  113. _assistant = None
  114. def call_agent_claude_code_sync(text):
  115. """通过 Claude Code CLI 调用 agent (无需 API Key)。"""
  116. global _assistant
  117. if _assistant is None:
  118. from pathlib import Path as _P
  119. _project_root = _P(__file__).resolve().parent.parent
  120. _agent_dir = _project_root / "agentexample"
  121. if str(_agent_dir) not in sys.path:
  122. sys.path.insert(0, str(_agent_dir))
  123. if str(_project_root) not in sys.path:
  124. sys.path.insert(0, str(_project_root))
  125. from agent67.core.assistant import PersonalAssistant
  126. _assistant = PersonalAssistant(model="sonnet", use_api=False)
  127. return _assistant.chat(text)
  128. async def call_agent_async(agent_id, text, claude_code=False):
  129. """异步包装 agent 调用。"""
  130. loop = asyncio.get_event_loop()
  131. if claude_code:
  132. return await loop.run_in_executor(None, call_agent_claude_code_sync, text)
  133. return await loop.run_in_executor(None, call_agent_sync, agent_id, text)
  134. # ── 消息处理 ────────────────────────────────────────────────
  135. def _make_dispatch_handler(agent_id, base_url, bot_token, claude_code=False):
  136. """创建消息分发处理器。"""
  137. # 缓存每个用户的 context_token
  138. context_tokens = {}
  139. async def dispatch_reply(msg):
  140. """收到微信消息 → 调用 Agent → 回复微信。"""
  141. from wechat_clawbot.messaging.send import send_message_weixin
  142. from wechat_clawbot.api.client import WeixinApiOptions
  143. user_id = msg.from_user
  144. text = msg.body or ""
  145. media_info = ""
  146. # 保存 context_token
  147. if msg.context_token:
  148. context_tokens[user_id] = msg.context_token
  149. # 处理媒体消息
  150. if msg.media_type and msg.media_path:
  151. if msg.media_type.startswith("audio/"):
  152. media_info = " [语音消息]"
  153. elif msg.media_type.startswith("image/"):
  154. media_info = " [图片]"
  155. elif msg.media_type.startswith("video/"):
  156. media_info = " [视频]"
  157. else:
  158. media_info = " [文件: {}]".format(msg.media_type)
  159. if not text and not media_info:
  160. return
  161. input_text = text + media_info
  162. print(" 📩 {} → \"{}\"".format(user_id[:16], input_text[:80]))
  163. # 调用 Agent
  164. t0 = time.time()
  165. reply = await call_agent_async(agent_id, input_text, claude_code=claude_code)
  166. elapsed = time.time() - t0
  167. print(" 💬 ({:.1f}s) → \"{}\"".format(elapsed, reply[:80]))
  168. # 回复微信
  169. ctx_token = context_tokens.get(user_id, msg.context_token)
  170. if not ctx_token:
  171. print(" ⚠️ 无 context_token,无法回复")
  172. return
  173. try:
  174. await send_message_weixin(
  175. to=user_id,
  176. text=reply,
  177. opts=WeixinApiOptions(
  178. base_url=base_url,
  179. token=bot_token,
  180. context_token=ctx_token,
  181. ),
  182. )
  183. print(" ✓ 已回复")
  184. except Exception as e:
  185. print(" ✗ 回复失败: {}".format(e))
  186. return dispatch_reply
  187. # ── 主监听循环 ──────────────────────────────────────────────
  188. async def run_bridge(agent_id, creds, claude_code=False):
  189. """启动 iLink 长轮询桥接。"""
  190. from wechat_clawbot.monitor.monitor import MonitorOpts, monitor_weixin_provider
  191. base_url = creds["base_url"]
  192. bot_token = creds["bot_token"]
  193. account_id = creds["account_id"]
  194. backend = "Claude Code CLI (无需 API Key)" if claude_code else "PaaS API"
  195. print("\n🟢 微信 ↔ AgentPaaS 桥接已启动")
  196. print(" Agent: {}".format(agent_id))
  197. print(" 后端: {}".format(backend))
  198. print(" Account: {}".format(account_id))
  199. print(" API: {}".format(base_url))
  200. print(" 按 Ctrl+C 停止\n")
  201. stop_event = asyncio.Event()
  202. def _signal_handler():
  203. print("\n🔴 正在停止...")
  204. stop_event.set()
  205. loop = asyncio.get_event_loop()
  206. for sig in (signal.SIGINT, signal.SIGTERM):
  207. loop.add_signal_handler(sig, _signal_handler)
  208. dispatch = _make_dispatch_handler(agent_id, base_url, bot_token, claude_code=claude_code)
  209. opts = MonitorOpts(
  210. base_url=base_url,
  211. cdn_base_url=creds.get("cdn_base_url", DEFAULT_CDN_URL),
  212. token=bot_token,
  213. account_id=account_id,
  214. dispatch_reply=dispatch,
  215. log=lambda msg: print(" [iLink] {}".format(msg)),
  216. err_log=lambda msg: print(" [iLink ERROR] {}".format(msg)),
  217. )
  218. try:
  219. await monitor_weixin_provider(opts, stop_event)
  220. except Exception as e:
  221. print(" 桥接异常: {}".format(e))
  222. finally:
  223. from wechat_clawbot.api.client import close_shared_client
  224. await close_shared_client()
  225. print("🔴 桥接已停止")
  226. # ── 守护进程 ────────────────────────────────────────────────
  227. def _write_pid():
  228. CREDENTIALS_DIR.mkdir(parents=True, exist_ok=True)
  229. PID_FILE.write_text(str(os.getpid()))
  230. def _read_pid():
  231. if PID_FILE.exists():
  232. try:
  233. return int(PID_FILE.read_text().strip())
  234. except ValueError:
  235. pass
  236. return None
  237. def _remove_pid():
  238. if PID_FILE.exists():
  239. PID_FILE.unlink()
  240. # ── 公开入口 ────────────────────────────────────────────────
  241. def _check_wechat_deps():
  242. """检查 wechat-clawbot 是否已安装。"""
  243. try:
  244. import wechat_clawbot # noqa: F401
  245. return True
  246. except ImportError:
  247. print("wechat-clawbot 未安装。请运行:")
  248. print(" pip install wechat-clawbot>=0.2.0")
  249. return False
  250. def cmd_wechat_start(agent_id, daemon=False, claude_code=False):
  251. """启动微信桥接。"""
  252. if not _check_wechat_deps():
  253. return
  254. # 检查凭证
  255. creds = _load_credentials()
  256. if not creds or not creds.get("bot_token"):
  257. creds = asyncio.run(login())
  258. if not creds:
  259. print("登录失败,退出。")
  260. return
  261. # 关联 agent_id
  262. creds["agent_id"] = agent_id
  263. _save_credentials(creds)
  264. if daemon:
  265. pid = os.fork()
  266. if pid > 0:
  267. print("后台运行中,PID: {}".format(pid))
  268. print(" 查看状态: agentpaas wechat status")
  269. print(" 停止: agentpaas wechat stop")
  270. return
  271. os.setsid()
  272. _write_pid()
  273. log_file = CREDENTIALS_DIR / "daemon.log"
  274. sys.stdout = open(log_file, "a")
  275. sys.stderr = sys.stdout
  276. try:
  277. asyncio.run(run_bridge(agent_id, creds, claude_code=claude_code))
  278. finally:
  279. if daemon:
  280. _remove_pid()
  281. def cmd_wechat_status():
  282. """查看微信桥接状态。"""
  283. creds = _load_credentials()
  284. if not creds:
  285. print("未配置微信 ClawBot,请先运行: agentpaas wechat <agent_id>")
  286. return
  287. print("=== 微信 ClawBot 状态 ===")
  288. print(" Account: {}".format(creds.get("account_id", "未知")))
  289. print(" Agent: {}".format(creds.get("agent_id", "未绑定")))
  290. print(" 登录时间: {}".format(creds.get("login_time", "未知")))
  291. pid = _read_pid()
  292. if pid:
  293. try:
  294. os.kill(pid, 0)
  295. print(" 守护进程: 运行中 (PID {})".format(pid))
  296. except OSError:
  297. print(" 守护进程: 已停止 (PID {} 不存在)".format(pid))
  298. _remove_pid()
  299. else:
  300. print(" 守护进程: 未运行")
  301. def cmd_wechat_stop():
  302. """停止后台桥接进程。"""
  303. pid = _read_pid()
  304. if not pid:
  305. print("没有运行中的守护进程")
  306. return
  307. try:
  308. os.kill(pid, signal.SIGTERM)
  309. print("已发送停止信号到 PID {}".format(pid))
  310. # 等待退出
  311. for _ in range(10):
  312. try:
  313. os.kill(pid, 0)
  314. time.sleep(0.5)
  315. except OSError:
  316. break
  317. _remove_pid()
  318. print("守护进程已停止")
  319. except OSError:
  320. print("进程 {} 不存在".format(pid))
  321. _remove_pid()
  322. def cmd_wechat_relogin(agent_id=None):
  323. """重新扫码登录。"""
  324. creds = asyncio.run(login())
  325. if creds and agent_id:
  326. creds["agent_id"] = agent_id
  327. _save_credentials(creds)
  328. print("重新登录完成")