Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: 支持企业微信channel对接

xiaowenzihwlaacb563b7ac6
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.py
index 1f2c53afc2..2c2b32f5d4 100644
--- a/jiuwenclaw/agentserver/interface.py
+++ b/jiuwenclaw/agentserver/interface.py
@@ -351,7 +351,9 @@ class JiuWenClaw:
evo_svc.auto_scan = _env_auto_scan.lower() in ("true", "1", "yes")
logger.info("[JiuWenClaw] 配置已热更新,未重启进程")
- async def _register_runtime_tools(self, session_id: str | None, mode="plan") -> None:
+ async def _register_runtime_tools(
+ self, session_id: str | None, mode="plan", channel_id: str | None = None
+ ) -> None:
"""Register per-request tools for current agent execution."""
if self._instance is None:
raise RuntimeError("JiuWenClaw 未初始化,请先调用 create_instance()")
@@ -364,15 +366,19 @@ class JiuWenClaw:
elif tool.name.startswith("cron_"):
self._instance.ability_manager.remove(tool.name)
- # 定时工具:按 channel 注册;仅当 resource_mgr 中尚未存在时 add_tool,避免重复添加触发 "resource already exist"
- channel = session_id.split('_')[0]
+ # 定时工具:按 channel 注册;优先用 channel_id,否则从 session_id 前缀推断
+ channel = (channel_id or "").strip() or (
+ (session_id or "").split("_")[0] if session_id else ""
+ )
logger.info(f"[JiuwenClaw] update tool and prompt for channel {channel}")
if channel not in ["heartbeat", "cron"]:
cron_controller = CronController.get_instance()
if channel == "feishu":
cron_controller.set_target_channel(CronTargetChannel.FEISHU)
- if channel == "sess":
+ elif channel == "wecom":
+ cron_controller.set_target_channel(CronTargetChannel.WECOM)
+ elif channel in ("web", "sess"):
cron_controller.set_target_channel(CronTargetChannel.WEB)
for cron_tool in cron_controller.get_tools():
@@ -793,7 +799,11 @@ class JiuWenClaw:
async def run_agent_task():
try:
- await self._register_runtime_tools(request.session_id, request.params.get("mode", "plan"))
+ await self._register_runtime_tools(
+ request.session_id,
+ request.params.get("mode", "plan"),
+ channel_id=request.channel_id,
+ )
return await Runner.run_agent(agent=self._instance, inputs=inputs)
except asyncio.CancelledError:
logger.info("[JiuWenClaw] Agent 任务被取消: request_id=%s session_id=%s", request.request_id, session_id)
@@ -930,7 +940,11 @@ class JiuWenClaw:
async def run_stream_task():
"""执行流式任务,将产生的 chunk 放入队列."""
try:
- await self._register_runtime_tools(request.session_id, request.params.get("mode", "plan"))
+ await self._register_runtime_tools(
+ request.session_id,
+ request.params.get("mode", "plan"),
+ channel_id=request.channel_id,
+ )
async for chunk in Runner.run_agent_streaming(self._instance, inputs):
parsed = self._parse_stream_chunk(chunk)
if parsed is None:
@@ -1037,9 +1051,9 @@ class JiuWenClaw:
if isinstance(output, dict)
else str(output)
)
- # Check if this is a chunked answer (first chunk)
+ # Check if this is a chunked/partial answer (streaming)
is_chunked = (
- output.get("chunked", False)
+ output.get("chunked", False) or output.get("partial", False)
if isinstance(output, dict)
else False
)
@@ -1101,6 +1115,14 @@ class JiuWenClaw:
"current_task": "thinking",
}
+ # llm_reasoning:模型推理/思考内容,不转为 chat.delta,避免发到企业微信
+ if chunk_type == "llm_reasoning":
+ return {
+ "event_type": "chat.processing_status",
+ "is_processing": True,
+ "current_task": "thinking",
+ }
+
if chunk_type == "todo.updated":
todos = (
payload.get("todos", [])
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index 2916e9a8c0..cba455f1eb 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -911,6 +911,57 @@ def _register_web_handlers(
except Exception as e: # noqa: BLE001
logger.exception("[channel.discord.set_conf] %s", e)
await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_wecom_get_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ try:
+ conf = cm.get_conf("wecom")
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.wecom.get_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
+
+ async def _channel_wecom_set_conf(ws, req_id, params, session_id):
+ cm = _resolve(channel_manager)
+ if cm is None:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="channel manager not available",
+ code="SERVICE_UNAVAILABLE",
+ )
+ return
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="params must be object",
+ code="BAD_REQUEST",
+ )
+ return
+ try:
+ await cm.set_conf("wecom", params)
+ conf = cm.get_conf("wecom")
+ try:
+ update_channel_in_config("wecom", conf)
+ _clear_agent_config_cache()
+ except Exception as e: # noqa: BLE001
+ logger.warning("[channel.wecom.set_conf] 写回 config.yaml 失败: %s", e)
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ except Exception as e: # noqa: BLE001
+ logger.exception("[channel.wecom.set_conf] %s", e)
+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
# ----- cron jobs -----
def _get_cron():
@@ -1095,6 +1146,8 @@ def _register_web_handlers(
channel.register_method("channel.whatsapp.set_conf", _channel_whatsapp_set_conf)
channel.register_method("channel.discord.get_conf", _channel_discord_get_conf)
channel.register_method("channel.discord.set_conf", _channel_discord_set_conf)
+ channel.register_method("channel.wecom.get_conf", _channel_wecom_get_conf)
+ channel.register_method("channel.wecom.set_conf", _channel_wecom_set_conf)
channel.register_method("cron.job.list", _cron_job_list)
channel.register_method("cron.job.get", _cron_job_get)
channel.register_method("cron.job.create", _cron_job_create)
@@ -1112,6 +1165,7 @@ async def _run() -> None:
from jiuwenclaw.channel.xiaoyi_channel import XiaoyiChannel, XiaoyiChannelConfig
from jiuwenclaw.channel.telegram_channel import TelegramChannel, TelegramChannelConfig
from jiuwenclaw.channel.discord_channel import DiscordChannel, DiscordChannelConfig
+ from jiuwenclaw.channel.wecom_channel import WecomChannel, WecomConfig
from jiuwenclaw.gateway import (
AgentWebSocketServer,
GatewayHeartbeatService,
@@ -1287,6 +1341,8 @@ async def _run() -> None:
discord_task = None
whatsapp_channel = None
whatsapp_task = None
+ wecom_channel = None
+ wecom_task = None
_last_channels_conf = {} # Store previous config to detect changes
@@ -1344,11 +1400,12 @@ async def _run() -> None:
nonlocal feishu_channel, feishu_task, xiaoyi_channel, xiaoyi_task
nonlocal dingtalk_channel, dingtalk_task, telegram_channel, telegram_task
nonlocal discord_channel, discord_task
- nonlocal whatsapp_channel, whatsapp_task, _last_channels_conf
+ nonlocal whatsapp_channel, whatsapp_task
+ nonlocal wecom_channel, wecom_task, _last_channels_conf
changed_channels = [
c
- for c in ["feishu", "xiaoyi", "dingtalk", "telegram", "whatsapp", "discord"]
+ for c in ["feishu", "xiaoyi", "dingtalk", "telegram", "whatsapp", "discord", "wecom"]
if _should_restart_channel(c, _last_channels_conf, conf)
]
_last_channels_conf = dict(conf or {})
@@ -1523,6 +1580,33 @@ async def _run() -> None:
else:
logger.info("[App] channels.whatsapp 未配置或格式错误,WhatsAppChannel 不启用")
+ # ----- WecomChannel -----
+ if "wecom" in changed_channels:
+ wecom_conf = conf.get("wecom") if isinstance(conf, dict) else None
+ await _stop_channel(wecom_channel, wecom_task, "wecom")
+ wecom_channel, wecom_task = None, None
+
+ if isinstance(wecom_conf, dict):
+ enabled, reason = _is_channel_enabled(wecom_conf, ["bot_id", "secret"])
+ if not enabled:
+ logger.info("[App] channels.wecom.%s,WecomChannel 未启用", reason)
+ else:
+ wecom_config = WecomConfig(
+ enabled=True,
+ bot_id=str(wecom_conf.get("bot_id") or "").strip(),
+ secret=str(wecom_conf.get("secret") or "").strip(),
+ ws_url=str(wecom_conf.get("ws_url") or "wss://openws.work.weixin.qq.com").strip(),
+ allow_from=wecom_conf.get("allow_from") or [],
+ enable_streaming=bool(wecom_conf.get("enable_streaming", True)),
+ send_thinking_message=bool(wecom_conf.get("send_thinking_message", True)),
+ )
+ wecom_channel = WecomChannel(wecom_config, _DummyBus())
+ channel_manager.register_channel(wecom_channel)
+ wecom_task = asyncio.create_task(wecom_channel.start(), name="wecom")
+ logger.info("[App] 已按 config.yaml.channels.wecom 注册 WecomChannel")
+ else:
+ logger.info("[App] channels.wecom 未配置或格式错误,WecomChannel 不启用")
+
# 将「配置更新时如何重新实例化 Channel」逻辑注册到 ChannelManager
channel_manager.set_config_callback(_apply_channel_config)
# 使用初始配置实例化一次(启动时,针对动态管理的各 Channel)
@@ -1594,6 +1678,13 @@ async def _run() -> None:
except asyncio.CancelledError:
pass
await whatsapp_channel.stop()
+ if wecom_channel is not None and wecom_task is not None:
+ wecom_task.cancel()
+ try:
+ await wecom_task
+ except asyncio.CancelledError:
+ pass
+ await wecom_channel.stop()
await cron_scheduler.stop()
await channel_manager.stop_dispatch()
await heartbeat_service.stop()
diff --git a/jiuwenclaw/channel/__init__.py b/jiuwenclaw/channel/__init__.py
index 7cfe1b994d..65493d823b 100644
--- a/jiuwenclaw/channel/__init__.py
+++ b/jiuwenclaw/channel/__init__.py
@@ -9,6 +9,7 @@ from jiuwenclaw.channel.telegram_channel import TelegramChannel, TelegramChannel
from jiuwenclaw.channel.discord_channel import DiscordChannel, DiscordChannelConfig
from jiuwenclaw.channel.dingding import DingTalkChannel, DingTalkConfig
from jiuwenclaw.channel.whatsapp_channel import WhatsAppChannel, WhatsAppChannelConfig
+from jiuwenclaw.channel.wecom_channel import WecomChannel, WecomConfig
__all__ = [
"BaseChannel",
@@ -24,4 +25,6 @@ __all__ = [
"DingTalkConfig",
"WhatsAppChannel",
"WhatsAppChannelConfig",
+ "WecomChannel",
+ "WecomConfig",
]
diff --git a/jiuwenclaw/channel/base.py b/jiuwenclaw/channel/base.py
index e620eefc6e..2ed73389c4 100644
--- a/jiuwenclaw/channel/base.py
+++ b/jiuwenclaw/channel/base.py
@@ -15,7 +15,7 @@ if TYPE_CHECKING:
class ChannelType(str, Enum):
- """<UNK>"""
+ """Channel 类型枚举."""
WEB = "web"
FEISHU = "feishu"
XIAOYI = "xiaoyi"
@@ -23,6 +23,7 @@ class ChannelType(str, Enum):
TELEGRAM = "telegram"
DISCORD = "discord"
WHATSAPP = "whatsapp"
+ WECOM = "wecom"
@dataclass
diff --git a/jiuwenclaw/channel/wecom_channel.py b/jiuwenclaw/channel/wecom_channel.py
new file mode 100644
index 0000000000..c4424036b2
--- /dev/null
+++ b/jiuwenclaw/channel/wecom_channel.py
@@ -0,0 +1,497 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""WecomChannel - 企业微信 AI 机器人通道(WebSocket 长连接)。"""
+
+from __future__ import annotations
+
+import asyncio
+import re
+import time
+from typing import Any, Callable
+
+from pydantic import BaseModel, Field
+
+from jiuwenclaw.utils import logger
+from jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouter
+from jiuwenclaw.schema.message import Message, ReqMethod, EventType
+
+try:
+ from wecom_aibot_sdk import WSClient
+ from wecom_aibot_sdk.utils import generate_req_id
+
+ WECOM_AVAILABLE = True
+except ImportError:
+ WECOM_AVAILABLE = False
+ WSClient = None
+ generate_req_id = None
+
+
+class WecomConfig(BaseModel):
+ """企业微信通道配置(WebSocket 长连接)。"""
+
+ enabled: bool = False
+ bot_id: str = ""
+ secret: str = ""
+ ws_url: str = "wss://openws.work.weixin.qq.com"
+ allow_from: list[str] = Field(default_factory=list)
+ enable_streaming: bool = True
+ send_thinking_message: bool = True
+
+
+class WecomChannel(BaseChannel):
+ """
+ 企业微信 AI 机器人通道,基于 WebSocket 长连接。
+
+ 依赖:
+ - 企业微信后台创建 AI 机器人,获取 bot_id 和 secret
+ """
+
+ name = "wecom"
+
+ def __init__(self, config: WecomConfig, router: RobotMessageRouter):
+ super().__init__(config, router)
+ self.config: WecomConfig = config
+ self._ws_client: Any = None
+ self._message_callback: Callable[[Message], None] | None = None
+ self._connect_task: asyncio.Task | None = None
+ # 流式回复:wecom_req_id -> {frame, stream_id, accumulated_content}
+ self._pending_streams: dict[str, dict[str, Any]] = {}
+
+ @property
+ def channel_id(self) -> str:
+ return self.name
+
+ def on_message(self, callback: Callable[[Message], None]) -> None:
+ """注册消息回调,供 ChannelManager 使用。"""
+ self._message_callback = callback
+
+ @staticmethod
+ def _looks_like_msgid(val: str) -> bool:
+ """过滤 msgid(长数字),避免误作 chatid 导致 93006。"""
+ if not val or not isinstance(val, str):
+ return True
+ s = val.strip()
+ if len(s) < 10:
+ return False
+ return s.isdigit()
+
+ def _extract_frame_info(self, frame: dict) -> tuple[str, str, str]:
+ """从 SDK frame 提取 chatid、req_id、content。
+
+ 企业微信消息结构(wecom-aibot-sdk):
+ - frame 含 cmd/headers/body;body 含 msgtype、from、text 等
+ - 单聊 chattype=single 时 chatid 为 from.userid
+ - 群聊时为 body.chatid 或 from.chatid
+ - 兼容 frame 直接为 body 的扁平结构(部分回调场景)
+ """
+ body = frame.get("body") or {}
+ if not isinstance(body, dict):
+ body = {}
+ # 若 frame 无 body 但含 msgtype,则 frame 本身即消息体(扁平结构)
+ if not body and frame.get("msgtype"):
+ body = frame
+
+ text = body.get("text") or {}
+ content = (
+ (text.get("content", "") if isinstance(text, dict) else str(text) if text else "")
+ or body.get("content", "")
+ or ""
+ )
+ headers = frame.get("headers") or {}
+ if not isinstance(headers, dict):
+ headers = {}
+ req_id = (
+ headers.get("req_id")
+ or headers.get("reqId")
+ or frame.get("req_id")
+ or body.get("msgid")
+ or body.get("req_id")
+ or ""
+ )
+
+ # chatid: 单聊用 from.userid,群聊用 chatid 或 from.chatid;过滤 msgid(长数字)
+ from_obj = body.get("from") or frame.get("from") or {}
+ if not isinstance(from_obj, dict):
+ from_obj = {}
+
+ def _pick_chatid(*candidates: str) -> str:
+ for c in candidates:
+ s = str(c or "").strip()
+ if s and not self._looks_like_msgid(s):
+ return s
+ return ""
+
+ chatid = _pick_chatid(
+ body.get("chatid"),
+ body.get("chat_id"),
+ from_obj.get("chatid"),
+ from_obj.get("chat_id"),
+ from_obj.get("userid"),
+ from_obj.get("user_id"),
+ frame.get("chatid"),
+ frame.get("chat_id"),
+ )
+ return chatid, req_id, str(content or "").strip()
+
+ async def _handle_incoming_message(self, frame: dict) -> None:
+ """处理 SDK 收到的消息,转换为 jiuwenclaw Message 并分发。"""
+ chatid, req_id, content = self._extract_frame_info(frame)
+ if not content:
+ logger.debug("WecomChannel 收到空内容,跳过")
+ return
+ if not chatid:
+ # 调试:打印 frame 结构以便排查
+ body_preview = frame.get("body") or frame
+ if isinstance(body_preview, dict):
+ keys = ("msgtype", "chatid", "chat_id", "from", "msgid")
+ preview = {k: body_preview.get(k) for k in keys if k in body_preview}
+ else:
+ preview = str(body_preview)[:200]
+ logger.warning(
+ "WecomChannel 无法从 frame 提取 chatid,跳过消息。frame.body 预览: %s",
+ preview,
+ )
+ return
+
+ # allow_from 校验:chatid 可为 userid 或 groupid
+ if not self.is_allowed(chatid):
+ logger.warning("WecomChannel 发送者 %s 未被允许", chatid)
+ return
+
+ logger.info("WecomChannel 收到消息: chatid=%s content=%s", chatid, content[:50])
+
+ # 写入 last_chat_id 供 cron/心跳推送使用
+ if chatid and not self._looks_like_msgid(chatid):
+ try:
+ from jiuwenclaw.config import update_channel_in_config
+
+ update_channel_in_config("wecom", {"last_chat_id": chatid or ""})
+ except Exception as e:
+ logger.warning("WecomChannel 写入 last_chat_id 失败: %s", e)
+
+ req_id_final = req_id or f"wecom_{int(time.time() * 1000)}"
+ # 流式回复:存储 frame,可选首帧发送「...」
+ if (
+ self.config.enable_streaming
+ and self._ws_client
+ and getattr(self._ws_client, "is_connected", False)
+ ):
+ stream_id = (
+ generate_req_id("stream")
+ if generate_req_id
+ else f"stream_{int(time.time()*1000)}_{req_id_final}"
+ )
+ self._pending_streams[req_id_final] = {
+ "frame": frame,
+ "stream_id": stream_id,
+ "accumulated": "",
+ }
+ # 无论流式/思考开关如何,始终发送等待占位
+ await self._send_stream_placeholder(req_id_final)
+
+ msg = Message(
+ id=req_id_final,
+ type="req",
+ channel_id=self.name,
+ session_id=chatid,
+ params={"content": content, "query": content},
+ timestamp=time.time(),
+ ok=True,
+ req_method=ReqMethod.CHAT_SEND,
+ is_stream=True,
+ metadata={
+ "wecom_chat_id": chatid,
+ "wecom_req_id": req_id_final,
+ },
+ )
+
+ if self._message_callback:
+ self._message_callback(msg)
+ else:
+ await self.bus.route_user_message(msg)
+
+ def _extract_chatid(self, msg: Message) -> str | None:
+ """从出站消息提取 chatid;心跳/定时等系统消息从 config 取 last_chat_id 或 default_chat_id。"""
+ meta = getattr(msg, "metadata", None) or {}
+ chatid = (meta.get("wecom_chat_id") or "").strip()
+ if chatid:
+ return chatid
+ sid = getattr(msg, "session_id", None) or msg.id
+ sid_str = str(sid) if sid else ""
+ # 系统会话(心跳、cron 等)无有效 chatid,使用 config 中的 last_chat_id
+ system_session_prefixes = ("__", "heartbeat_", "cron")
+ if sid_str and not any(sid_str.startswith(p) for p in system_session_prefixes):
+ if not self._looks_like_msgid(sid_str):
+ return sid_str
+ try:
+ from jiuwenclaw.config import get_config
+ ch_cfg = (get_config().get("channels") or {}).get("wecom") or {}
+ # last_chat_id:用户聊天时自动写入;default_chat_id:可手动配置,用于心跳/定时推送
+ last = str(ch_cfg.get("last_chat_id") or ch_cfg.get("default_chat_id") or "").strip()
+ if last and not self._looks_like_msgid(last):
+ return last
+ return None
+ except Exception:
+ return None
+
+ def _extract_content(self, msg: Message) -> str:
+ """从出站消息中提取文本内容。"""
+ payload = getattr(msg, "payload", None) or {}
+ params = getattr(msg, "params", None) or {}
+ content = (
+ params.get("content")
+ or payload.get("content")
+ or ""
+ )
+ if isinstance(content, dict):
+ content = content.get("output", str(content))
+ return str(content or "").strip()
+
+ @staticmethod
+ def _strip_think_tags(text: str) -> str:
+ """移除 <think>...</think> 块及未闭合的 <think>...,避免将 Agent 的思考过程展示给用户。"""
+ if not text or not isinstance(text, str):
+ return text or ""
+ # 1. 移除完整的 <think>...</think> 块
+ text = re.sub(r"<think>[\s\S]*?</think>", "", text, flags=re.IGNORECASE | re.DOTALL)
+ # 2. 移除未闭合的 <think>...(流式场景下可能先收到 <think> 后收到 </think>)
+ text = re.sub(r"<think>[\s\S]*$", "", text, flags=re.IGNORECASE | re.DOTALL)
+ return text
+
+ @staticmethod
+ def _is_thinking_only_content(text: str) -> bool:
+ """判断内容是否为空或仅为占位符(纯省略号等),不应视为有效回复。
+ 思考过程(llm_reasoning/thinking)已在 interface 转为 chat.processing_status,不会以 content 到达。"""
+ if not text or not isinstance(text, str):
+ return True
+ t = text.strip()
+ if not t:
+ return True
+ # 纯省略号、纯点
+ if re.match(r"^[..。…\s]+$", t):
+ return True
+ return False
+
+ def _extract_content_from_payload(self, msg: Message) -> str | None:
+ """从 chat.delta / chat.final 的 payload 提取 content,无则返回 None。"""
+ payload = getattr(msg, "payload", None) or {}
+ if not isinstance(payload, dict):
+ return None
+ content = payload.get("content")
+ if content is None:
+ return None
+ return str(content)
+
+ async def _send_stream_placeholder(self, req_id: str) -> None:
+ """发送流式首帧占位。PHP SDK 用 <think></think> 显示加载动画,企业微信 Markdown 可能支持。"""
+ entry = self._pending_streams.get(req_id)
+ if not entry or not self._ws_client or not getattr(self._ws_client, "is_connected", False):
+ return
+ try:
+ # 尝试 <think></think>(PHP SDK 用法,可能渲染为加载动画);若不支持则显示为 ...
+ placeholder = "<think></think>"
+ await self._ws_client.reply_stream(
+ entry["frame"],
+ entry["stream_id"],
+ placeholder,
+ finish=False,
+ )
+ logger.debug("WecomChannel 已发送流式占位: req_id=%s", req_id)
+ except Exception as e:
+ logger.debug("WecomChannel 发送流式占位失败: %s", e)
+
+ def _get_req_id_for_stream(self, msg: Message) -> str | None:
+ """从出站消息中提取 wecom_req_id,用于查找 pending stream。"""
+ meta = getattr(msg, "metadata", None) or {}
+ return (meta.get("wecom_req_id") or "").strip() or None
+
+ async def send(self, msg: Message) -> None:
+ """通过企业微信发送消息。支持流式(reply_stream)与非流式(send_message)。"""
+ if not self._ws_client or not getattr(self._ws_client, "is_connected", False):
+ logger.warning("WecomChannel 未连接,跳过发送")
+ return
+
+ # 不向企业微信发送 chat.processing_status(思考状态事件),避免展示思考过程
+ if msg.event_type == EventType.CHAT_PROCESSING_STATUS:
+ return
+
+ # 心跳/系统事件
+ if msg.event_type == EventType.HEARTBEAT_RELAY:
+ chatid = self._extract_chatid(msg)
+ if chatid:
+ payload = getattr(msg, "payload", None) or {}
+ if isinstance(payload, dict) and payload.get("heartbeat"):
+ try:
+ body = {"msgtype": "markdown", "markdown": {"content": str(payload.get("heartbeat"))}}
+ await self._ws_client.send_message(chatid, body)
+ logger.debug("WecomChannel 心跳已发送至 chatid=%s", chatid)
+ except Exception as e:
+ logger.warning("WecomChannel 心跳发送失败: %s", e)
+ else:
+ logger.warning(
+ "WecomChannel 心跳未发送:无有效 chatid。请先在企业微信中与机器人对话一次,以写入 last_chat_id"
+ )
+ return
+
+ # 流式回复:CHAT_DELTA / CHAT_FINAL 通过 reply_stream 发送,替换首帧「...」
+ req_id = self._get_req_id_for_stream(msg)
+ if req_id and self.config.enable_streaming:
+ entry = self._pending_streams.get(req_id)
+ if entry:
+ content = self._extract_content_from_payload(msg)
+ if content is not None:
+ entry["accumulated"] = (entry.get("accumulated") or "") + content
+ # 移除 <think>...</think> 块,不将 Agent 思考过程展示给用户
+ to_send = self._strip_think_tags(entry["accumulated"]).strip()
+ if not to_send or self._is_thinking_only_content(to_send):
+ if msg.event_type == EventType.CHAT_FINAL:
+ self._pending_streams.pop(req_id, None)
+ return
+ try:
+ is_final = msg.event_type == EventType.CHAT_FINAL
+ await self._ws_client.reply_stream(
+ entry["frame"],
+ entry["stream_id"],
+ to_send,
+ finish=is_final,
+ )
+ logger.debug(
+ "WecomChannel 流式发送: req_id=%s finish=%s len=%d",
+ req_id,
+ is_final,
+ len(entry["accumulated"]),
+ )
+ if is_final:
+ self._pending_streams.pop(req_id, None)
+ except Exception as e:
+ logger.error("WecomChannel 流式发送失败: %s", e)
+ if msg.event_type == EventType.CHAT_FINAL:
+ self._pending_streams.pop(req_id, None)
+ return
+
+ # chat.error:清理 pending,发送错误提示
+ if msg.event_type == EventType.CHAT_ERROR:
+ if req_id:
+ self._pending_streams.pop(req_id, None)
+ payload = getattr(msg, "payload", None) or {}
+ err_text = payload.get("error", "处理出错") if isinstance(payload, dict) else "处理出错"
+ chatid = self._extract_chatid(msg)
+ if chatid:
+ try:
+ await self._ws_client.send_message(
+ chatid,
+ {"msgtype": "markdown", "markdown": {"content": f"⚠️ {err_text}"}},
+ )
+ except Exception as e:
+ logger.debug("WecomChannel 发送错误消息失败: %s", e)
+ return
+
+ # 非流式或无 pending:仅 CHAT_FINAL 用 send_message
+ if msg.event_type != EventType.CHAT_FINAL:
+ return
+ if req_id:
+ self._pending_streams.pop(req_id, None)
+ chatid = self._extract_chatid(msg)
+ if not chatid:
+ logger.warning("WecomChannel 无法确定回发目标 chatid")
+ return
+ content = self._strip_think_tags(self._extract_content(msg)).strip()
+ if not content or self._is_thinking_only_content(content):
+ logger.debug("WecomChannel 消息内容为空或仅为思考占位,跳过发送")
+ return
+ try:
+ body = {"msgtype": "markdown", "markdown": {"content": content}}
+ await self._ws_client.send_message(chatid, body)
+ logger.debug("WecomChannel 已发送: chatid=%s len=%d", chatid, len(content))
+ except Exception as e:
+ logger.error("WecomChannel 发送失败: %s", e)
+
+ async def _run_client(self) -> None:
+ """在后台运行 WebSocket 客户端。"""
+ if not WECOM_AVAILABLE or not WSClient:
+ logger.error("WecomChannel 依赖未安装,请运行: pip install wecom-aibot-sdk")
+ return
+
+ opts: dict[str, Any] = {
+ "bot_id": self.config.bot_id,
+ "secret": self.config.secret,
+ }
+ if self.config.ws_url:
+ opts["ws_url"] = self.config.ws_url
+ client = WSClient(**opts)
+
+ async def on_text(frame: dict) -> None:
+ await self._handle_incoming_message(frame)
+
+ client.on("message.text", on_text)
+
+ self._ws_client = client
+
+ try:
+ await client.connect()
+ logger.info("WecomChannel WebSocket 已连接")
+
+ while self._running and getattr(client, "is_connected", True):
+ await asyncio.sleep(1)
+ except asyncio.CancelledError:
+ pass
+ except Exception as e:
+ logger.error("WecomChannel WebSocket 异常: %s", e)
+ finally:
+ try:
+ await client.disconnect()
+ except Exception as e:
+ logger.warning("WecomChannel 断开连接时异常: %s", e)
+ self._ws_client = None
+
+ async def start(self) -> None:
+ """启动企业微信通道。"""
+ if not WECOM_AVAILABLE:
+ logger.error("WecomChannel 依赖未安装,请运行: pip install wecom-aibot-sdk")
+ return
+
+ if not self.config.bot_id or not self.config.secret:
+ logger.error("WecomChannel 未配置 bot_id 或 secret")
+ return
+
+ if self._running:
+ logger.warning("WecomChannel 已在运行")
+ return
+
+ self._running = True
+ self._connect_task = asyncio.create_task(self._run_client(), name="wecom-channel")
+ logger.info("WecomChannel 已启动(WebSocket 长连接)")
+
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """停止企业微信通道。"""
+ self._running = False
+
+ if self._connect_task:
+ self._connect_task.cancel()
+ try:
+ await self._connect_task
+ except asyncio.CancelledError:
+ pass
+ self._connect_task = None
+
+ if self._ws_client:
+ try:
+ await self._ws_client.disconnect()
+ except Exception as e:
+ logger.warning("WecomChannel 停止时断开异常: %s", e)
+ self._ws_client = None
+
+ logger.info("WecomChannel 已停止")
+
+ def get_metadata(self) -> ChannelMetadata:
+ return ChannelMetadata(
+ channel_id=self.channel_id,
+ source="websocket",
+ extra={
+ "ws_url": self.config.ws_url,
+ "bot_id": self.config.bot_id[:8] + "..." if len(self.config.bot_id) > 8 else self.config.bot_id,
+ },
+ )
diff --git a/jiuwenclaw/gateway/cron/controller.py b/jiuwenclaw/gateway/cron/controller.py
index 36f29f3469..eeb5b2ec75 100644
--- a/jiuwenclaw/gateway/cron/controller.py
+++ b/jiuwenclaw/gateway/cron/controller.py
@@ -288,7 +288,7 @@ class CronController:
"targets": {
"type": "string",
"enum": [e.value for e in CronTargetChannel],
- "description": "推送频道:web=网页, feishu=飞书, whatsapp=WhatsApp",
+ "description": "推送频道:web=网页, feishu=飞书, whatsapp=WhatsApp, wecom=企业微信。不传则使用当前请求来源频道",
"default": self._target_channel.value,
},
"enabled": {
diff --git a/jiuwenclaw/gateway/cron/models.py b/jiuwenclaw/gateway/cron/models.py
index 9e2a9c754b..0998533b3f 100644
--- a/jiuwenclaw/gateway/cron/models.py
+++ b/jiuwenclaw/gateway/cron/models.py
@@ -11,6 +11,7 @@ class CronTargetChannel(str, Enum):
WEB = "web"
FEISHU = "feishu"
WHATSAPP = "whatsapp"
+ WECOM = "wecom"
# XIAOYI = "xiaoyi"
# DINGTALK = "dingtalk"
diff --git a/jiuwenclaw/gateway/cron/scheduler.py b/jiuwenclaw/gateway/cron/scheduler.py
index e8f8d54db1..ba5c2e0f70 100644
--- a/jiuwenclaw/gateway/cron/scheduler.py
+++ b/jiuwenclaw/gateway/cron/scheduler.py
@@ -423,6 +423,12 @@ class CronSchedulerService:
metadata = {
"whatsapp_jid": last_jid,
}
+ elif channel_id == "wecom":
+ last_chat_id = str(ch_cfg.get("last_chat_id") or "").strip()
+ if last_chat_id:
+ metadata = {
+ "wecom_chat_id": last_chat_id,
+ }
except Exception:
metadata = None
diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.py
index c32323dddb..5b756be81c 100644
--- a/jiuwenclaw/gateway/message_handler.py
+++ b/jiuwenclaw/gateway/message_handler.py
@@ -48,8 +48,8 @@ class MessageHandler(ABC):
self._stream_tasks: dict[str, asyncio.Task] = {} # request_id -> task
self._stream_sessions: dict[str, str | None] = {} # request_id -> session_id
- # per-channel 控制状态:支持 \new_session / \mode 指令(feishu/xiaoyi/dingding/whatsapp)
- self._control_channels = {"feishu", "xiaoyi", "dingtalk", "whatsapp"}
+ # per-channel 控制状态:支持 \new_session / \mode 指令(feishu/xiaoyi/dingding/whatsapp/wecom)
+ self._control_channels = {"feishu", "xiaoyi", "dingtalk", "whatsapp", "wecom"}
self._channel_states: Dict[str, ChannelControlState] = {}
# 直接使用 jiuwenclaw.config 的 get_config_raw/set_config/update_channel_in_config
diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yaml
index 61258510fe..203e7de688 100644
--- a/jiuwenclaw/resources/config.yaml
+++ b/jiuwenclaw/resources/config.yaml
@@ -105,6 +105,15 @@ channels:
bridge_command: node scripts/whatsapp-bridge.js
bridge_workdir:
enabled: false
+ wecom:
+ # 企业微信 AI 机器人配置
+ bot_id:
+ secret:
+ ws_url: wss://openws.work.weixin.qq.com
+ allow_from: []
+ enable_streaming: true
+ send_thinking_message: false
+ enabled: false
browser:
# chrome_path can be a string or per-OS map.
diff --git a/jiuwenclaw/web/public/wecom.webp b/jiuwenclaw/web/public/wecom.webp
new file mode 100644
index 0000000000..fe936c6341
Binary files /dev/null and b/jiuwenclaw/web/public/wecom.webp differ
diff --git a/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx b/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx
index cee4b49562..1589f9f7fb 100644
--- a/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx
+++ b/jiuwenclaw/web/src/components/ChannelsPanel/index.tsx
@@ -14,7 +14,7 @@ type ChannelItem = {
};
type LoadState = 'idle' | 'loading' | 'success' | 'error';
-type SupportedChannelId = 'web' | 'xiaoyi' | 'feishu' | 'dingtalk' | 'telegram' | 'discord' | 'whatsapp';
+type SupportedChannelId = 'web' | 'xiaoyi' | 'feishu' | 'dingtalk' | 'telegram' | 'discord' | 'whatsapp'| 'wecom';
const ADAPTING_CHANNEL_IDS = new Set<SupportedChannelId>([]);
type FeishuConfig = {
@@ -123,6 +123,29 @@ type WhatsAppDraft = {
bridge_workdir: string;
};
+type WecomConfig = {
+ enabled: boolean;
+ bot_id: string;
+ secret: string;
+ ws_url: string;
+ allow_from: string[];
+ enable_streaming: boolean;
+ send_thinking_message: boolean;
+ /** 心跳/定时推送目标 chatid,不填则用最近一次聊天的 last_chat_id */
+ default_chat_id: string;
+};
+
+type WecomDraft = {
+ enabled: boolean;
+ bot_id: string;
+ secret: string;
+ ws_url: string;
+ allow_from: string;
+ enable_streaming: boolean;
+ send_thinking_message: boolean;
+ default_chat_id: string;
+};
+
const DEFAULT_FEISHU_CONF: FeishuConfig = {
enabled: false,
app_id: '',
@@ -176,6 +199,17 @@ const DEFAULT_WHATSAPP_CONF: WhatsAppConfig = {
bridge_workdir: '',
};
+const DEFAULT_WECOM_CONF: WecomConfig = {
+ enabled: false,
+ bot_id: '',
+ secret: '',
+ ws_url: 'wss://openws.work.weixin.qq.com',
+ allow_from: [],
+ enable_streaming: true,
+ send_thinking_message: false,
+ default_chat_id: '',
+};
+
const SUPPORTED_CHANNELS: Array<{ channel_id: SupportedChannelId; logo_src: string | null }> = [
{ channel_id: 'web', logo_src: null },
{ channel_id: 'xiaoyi', logo_src: '/xiaoyi.webp' },
@@ -184,6 +218,7 @@ const SUPPORTED_CHANNELS: Array<{ channel_id: SupportedChannelId; logo_src: stri
{ channel_id: 'telegram', logo_src: '/telegram.webp' },
{ channel_id: 'discord', logo_src: '/discord.webp' },
{ channel_id: 'whatsapp', logo_src: '/whatsapp.png' },
+ { channel_id: 'wecom', logo_src: '/wecom.webp' },
];
@@ -488,6 +523,53 @@ function buildWhatsAppPayload(draft: WhatsAppDraft): Record<string, unknown> {
};
}
+function normalizeWecomConfig(input: unknown): WecomConfig {
+ if (!input || typeof input !== 'object') {
+ return DEFAULT_WECOM_CONF;
+ }
+ const data = input as Record<string, unknown>;
+ const allowFromRaw = Array.isArray(data.allow_from) ? data.allow_from : [];
+ const allowFrom = allowFromRaw
+ .map((item) => String(item ?? '').trim())
+ .filter((item) => item.length > 0);
+ return {
+ enabled: Boolean(data.enabled),
+ bot_id: String(data.bot_id ?? '').trim(),
+ secret: String(data.secret ?? '').trim(),
+ ws_url: String(data.ws_url ?? 'wss://openws.work.weixin.qq.com').trim(),
+ allow_from: allowFrom,
+ enable_streaming: data.enable_streaming === undefined ? true : Boolean(data.enable_streaming),
+ send_thinking_message: data.send_thinking_message === undefined ? true : Boolean(data.send_thinking_message),
+ default_chat_id: String(data.default_chat_id ?? data.last_chat_id ?? '').trim(),
+ };
+}
+
+function draftFromWecomConfig(conf: WecomConfig): WecomDraft {
+ return {
+ enabled: conf.enabled,
+ bot_id: conf.bot_id,
+ secret: conf.secret,
+ ws_url: conf.ws_url,
+ allow_from: conf.allow_from.join('\n'),
+ enable_streaming: conf.enable_streaming,
+ send_thinking_message: conf.send_thinking_message,
+ default_chat_id: conf.default_chat_id,
+ };
+}
+
+function buildWecomPayload(draft: WecomDraft): Record<string, unknown> {
+ return {
+ enabled: draft.enabled,
+ bot_id: draft.bot_id.trim(),
+ secret: draft.secret.trim(),
+ allow_from: normalizeAllowFromText(draft.allow_from),
+ default_chat_id: draft.default_chat_id.trim(),
+ };
+}
+
+function isSensitiveWecomField(field: keyof WecomDraft): boolean {
+ return field === 'secret';
+}
function VisibilityIcon({ visible }: { visible: boolean }) {
return visible ? (
<svg className="channels-panel__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8}>
@@ -595,6 +677,13 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
const [whatsappSaving, setWhatsappSaving] = useState(false);
const [whatsappSaveError, setWhatsappSaveError] = useState<string | null>(null);
const [whatsappSuccess, setWhatsappSuccess] = useState<string | null>(null);
+ const [wecomConfig, setWecomConfig] = useState<WecomConfig>(DEFAULT_WECOM_CONF);
+ const [wecomDraft, setWecomDraft] = useState<WecomDraft>(draftFromWecomConfig(DEFAULT_WECOM_CONF));
+ const [wecomVisibleFields, setWecomVisibleFields] = useState<Record<string, boolean>>({});
+ const [wecomLoading, setWecomLoading] = useState(false);
+ const [wecomSaving, setWecomSaving] = useState(false);
+ const [wecomSaveError, setWecomSaveError] = useState<string | null>(null);
+ const [wecomSuccess, setWecomSuccess] = useState<string | null>(null);
const fetchChannels = useCallback(async () => {
setLoadState('loading');
@@ -715,6 +804,23 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
setWhatsappLoading(false);
}
}, [t]);
+
+ const fetchWecomConfig = useCallback(async () => {
+ setWecomLoading(true);
+ setWecomSaveError(null);
+ setWecomSuccess(null);
+ try {
+ const payload = await webRequest<{ config?: unknown }>('channel.wecom.get_conf');
+ const normalized = normalizeWecomConfig(payload?.config);
+ setWecomConfig(normalized);
+ setWecomDraft(draftFromWecomConfig(normalized));
+ setWecomVisibleFields({});
+ } catch (err) {
+ setWecomSaveError(err instanceof Error ? err.message : t('channels.errors.loadWecom'));
+ } finally {
+ setWecomLoading(false);
+ }
+ }, [t]);
const handleSelectChannel = useCallback(
(channelId: SupportedChannelId) => {
@@ -750,7 +856,10 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
if (activeChannelId === 'whatsapp') {
void fetchWhatsAppConfig();
}
- }, [activeChannelId, fetchDiscordConfig, fetchDingtalkConfig, fetchFeishuConfig, fetchTelegramConfig, fetchWhatsAppConfig, fetchXiaoyiConfig]);
+ if (activeChannelId === 'wecom') {
+ void fetchWecomConfig();
+ }
+ }, [activeChannelId, fetchDiscordConfig, fetchDingtalkConfig, fetchFeishuConfig, fetchTelegramConfig, fetchWhatsAppConfig,fetchXiaoyiConfig, fetchWecomConfig]);
const statusText = useMemo(() => {
const enabledCount = channels.filter((channel) => channel.enabled).length;
@@ -829,6 +938,16 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
baseDraft.bridge_workdir !== whatsappDraft.bridge_workdir
);
}, [whatsappConfig, whatsappDraft]);
+ const hasWecomConfigChanges = useMemo(() => {
+ const baseDraft = draftFromWecomConfig(wecomConfig);
+ return (
+ baseDraft.enabled !== wecomDraft.enabled ||
+ baseDraft.bot_id !== wecomDraft.bot_id ||
+ baseDraft.secret !== wecomDraft.secret ||
+ baseDraft.default_chat_id !== wecomDraft.default_chat_id ||
+ normalizeAllowFromText(baseDraft.allow_from).join('\n') !== normalizeAllowFromText(wecomDraft.allow_from).join('\n')
+ );
+ }, [wecomConfig, wecomDraft]);
const handleFieldChange = <K extends keyof FeishuDraft>(key: K, value: FeishuDraft[K]) => {
setDraft((prev) => ({ ...prev, [key]: value }));
if (saveError) {
@@ -966,6 +1085,27 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
}
};
+ const handleWecomFieldChange = <K extends keyof WecomDraft>(key: K, value: WecomDraft[K]) => {
+ setWecomDraft((prev) => ({ ...prev, [key]: value }));
+ if (wecomSaveError) {
+ setWecomSaveError(null);
+ }
+ if (wecomSuccess) {
+ setWecomSuccess(null);
+ }
+ };
+
+ const handleCancelWecomConfig = () => {
+ if (!hasWecomConfigChanges) return;
+ setWecomDraft(draftFromWecomConfig(wecomConfig));
+ setWecomSaveError(null);
+ setWecomSuccess(null);
+ };
+
+ const toggleWecomFieldVisible = (field: keyof WecomDraft) => {
+ setWecomVisibleFields((prev) => ({ ...prev, [field]: !prev[field] }));
+ };
+
const handleSaveConfig = async () => {
if (!hasConfigChanges || saving) return;
setSaving(true);
@@ -1061,16 +1201,35 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
}
};
- const isConfigRefreshing = feishuLoading || xiaoyiLoading || dingtalkLoading || telegramLoading || discordLoading || whatsappLoading;
+ const handleSaveWecomConfig = async () => {
+ if (!hasWecomConfigChanges || wecomSaving) return;
+ setWecomSaving(true);
+ setWecomSaveError(null);
+ try {
+ const payload = buildWecomPayload(wecomDraft);
+ const result = await webRequest<{ config?: unknown }>('channel.wecom.set_conf', payload);
+ const normalized = normalizeWecomConfig(result?.config);
+ setWecomConfig(normalized);
+ setWecomDraft(draftFromWecomConfig(normalized));
+ setWecomSuccess(t('channels.saved.wecom'));
+ } catch (saveErr) {
+ const message = saveErr instanceof Error ? saveErr.message : t('channels.errors.saveGeneric');
+ setWecomSaveError(message);
+ } finally {
+ setWecomSaving(false);
+ }
+ };
+
+ const isConfigRefreshing = feishuLoading || xiaoyiLoading || dingtalkLoading || telegramLoading || discordLoading || whatsappLoading || wecomLoading;
const configErrorNotice = useMemo(() => {
return Array.from(
new Set(
- [saveError, xiaoyiSaveError, dingtalkSaveError, telegramSaveError, discordSaveError, whatsappSaveError].filter(
+ [saveError, xiaoyiSaveError, dingtalkSaveError, telegramSaveError, discordSaveError, whatsappSaveError, wecomSaveError].filter(
(message): message is string => Boolean(message),
),
),
).join(t('common.and'));
- }, [discordSaveError, dingtalkSaveError, saveError, t, telegramSaveError, whatsappSaveError, xiaoyiSaveError]);
+ }, [discordSaveError, dingtalkSaveError, saveError, t, telegramSaveError, whatsappSaveError, wecomSaveError, xiaoyiSaveError]);
useEffect(() => {
if (!configErrorNotice) {
return;
@@ -1082,6 +1241,7 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
setTelegramSaveError(null);
setDiscordSaveError(null);
setWhatsappSaveError(null);
+ setWecomSaveError(null);
}, 2000);
return () => {
window.clearTimeout(timer);
@@ -1979,6 +2139,145 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {
</div>
</div>
) : null}
+
+ {activeChannelId === 'wecom' ? (
+ <div className="w-full h-full rounded-xl border border-border bg-card/70 backdrop-blur-sm overflow-hidden shadow-sm flex flex-col">
+ <div className="px-4 py-3 bg-secondary/30 border-b border-border">
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex items-center gap-3">
+ <ChannelHeaderLogo channelId="wecom" label={getChannelLabel(t, 'wecom')} />
+ <div>
+ <h4 className="text-sm font-medium text-text">{t('channels.config.wecomTitle')}</h4>
+ <p className="text-xs text-text-muted mt-1">{t('channels.config.wecomSubtitle')}</p>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => void fetchWecomConfig()}
+ disabled={wecomSaving || isConfigRefreshing}
+ className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {wecomLoading ? t('common.refreshing') : t('common.refresh')}
+ </button>
+ <button
+ type="button"
+ onClick={handleCancelWecomConfig}
+ disabled={!hasWecomConfigChanges || wecomSaving}
+ className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {t('common.cancel')}
+ </button>
+ <button
+ type="button"
+ onClick={() => void handleSaveWecomConfig()}
+ disabled={
+ !hasWecomConfigChanges ||
+ wecomSaving ||
+ !isConnected ||
+ !wecomDraft.bot_id.trim() ||
+ !wecomDraft.secret.trim()
+ }
+ className="btn primary !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {wecomSaving ? t('common.saving') : t('common.save')}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {wecomSuccess ? (
+ <div className="mx-4 mt-4 rounded-md border border-[var(--border-ok)] bg-ok-subtle px-3 py-2 text-sm text-ok">
+ {wecomSuccess}
+ </div>
+ ) : null}
+
+ <div className="p-4 pt-3 flex-1 overflow-auto">
+ {wecomLoading ? (
+ <div className="text-sm text-text-muted">{t('channels.loading.wecom')}</div>
+ ) : (
+ <table className="w-full text-sm">
+ <tbody>
+ <tr className="border-t border-border first:border-t-0 even:bg-secondary/10">
+ <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">enabled</td>
+ <td className="px-4 py-2.5 align-middle">
+ <button
+ type="button"
+ role="switch"
+ aria-checked={wecomDraft.enabled}
+ onClick={() => handleWecomFieldChange('enabled', !wecomDraft.enabled)}
+ className={`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none ${
+ wecomDraft.enabled ? 'bg-ok' : 'bg-secondary'
+ }`}
+ >
+ <span
+ className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ${
+ wecomDraft.enabled ? 'translate-x-4' : 'translate-x-0'
+ }`}
+ />
+ </button>
+ </td>
+ </tr>
+ {(['bot_id', 'secret'] as const).map((field) => (
+ <tr key={field} className="border-t border-border first:border-t-0 even:bg-secondary/10">
+ <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">{field}</td>
+ <td className="px-4 py-2.5 break-all text-[13px] align-middle">
+ <div className="relative">
+ <input
+ type={isSensitiveWecomField(field) && !wecomVisibleFields[field] ? 'password' : 'text'}
+ value={wecomDraft[field]}
+ onChange={(e) => handleWecomFieldChange(field, e.target.value)}
+ placeholder={t('channels.placeholders.configValue')}
+ className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] outline-none focus:border-accent ${
+ isSensitiveWecomField(field) ? 'pr-10' : ''
+ }`}
+ />
+ {isSensitiveWecomField(field) ? (
+ <button
+ type="button"
+ onClick={() => toggleWecomFieldVisible(field)}
+ className="channels-panel__visibility-toggle"
+ aria-label={wecomVisibleFields[field] ? t('channels.hideValue') : t('channels.showValue')}
+ title={wecomVisibleFields[field] ? t('channels.hideValue') : t('channels.showValue')}
+ >
+ <VisibilityIcon visible={Boolean(wecomVisibleFields[field])} />
+ </button>
+ ) : null}
+ </div>
+ </td>
+ </tr>
+ ))}
+ <tr className="border-t border-border first:border-t-0 even:bg-secondary/10">
+ <td className="px-4 py-2.5 align-top mono text-xs text-text-muted w-[32%]">default_chat_id</td>
+ <td className="px-4 py-2.5 break-all text-[13px] align-middle">
+ <input
+ type="text"
+ value={wecomDraft.default_chat_id}
+ onChange={(e) => handleWecomFieldChange('default_chat_id', e.target.value)}
+ placeholder={t('channels.placeholders.wecomDefaultChatId')}
+ className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] outline-none focus:border-accent"
+ />
+ <p className="mt-1 text-xs text-text-muted">{t('channels.placeholders.wecomDefaultChatIdHint')}</p>
+ </td>
+ </tr>
+ <tr className="border-t border-border first:border-t-0 even:bg-secondary/10">
+ <td className="px-4 py-2.5 align-top mono text-xs text-text-muted w-[32%]">allow_from</td>
+ <td className="px-4 py-2.5 break-all text-[13px] align-middle">
+ <textarea
+ value={wecomDraft.allow_from}
+ onChange={(e) => handleWecomFieldChange('allow_from', e.target.value)}
+ placeholder={t('channels.placeholders.ids')}
+ rows={4}
+ className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] outline-none focus:border-accent resize-y"
+ />
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ ) : null}
</section>
</div>
)}
diff --git a/jiuwenclaw/web/src/components/CronPanel/index.tsx b/jiuwenclaw/web/src/components/CronPanel/index.tsx
index d63c255069..686620368c 100644
--- a/jiuwenclaw/web/src/components/CronPanel/index.tsx
+++ b/jiuwenclaw/web/src/components/CronPanel/index.tsx
@@ -72,6 +72,7 @@ export default function CronPanel() {
const targetOptions = [
{ value: 'web', label: t('cron.targets.web') },
{ value: 'feishu', label: t('cron.targets.feishu') },
+ { value: 'wecom', label: t('cron.targets.wecom') },
{ value: 'xiaoyi', label: t('cron.targets.xiaoyi'), disabled: true, style: { color: '#8c8c96ff' } },
{ value: 'dingtalk', label: t('cron.targets.dingtalk'), disabled: true, style: { color: '#8c8c96ff' } }
];
diff --git a/jiuwenclaw/web/src/components/HeartbeatPanel/index.tsx b/jiuwenclaw/web/src/components/HeartbeatPanel/index.tsx
index 04465ada74..fe13db0b26 100644
--- a/jiuwenclaw/web/src/components/HeartbeatPanel/index.tsx
+++ b/jiuwenclaw/web/src/components/HeartbeatPanel/index.tsx
@@ -340,6 +340,7 @@ export function HeartbeatPanel() {
>
<option value="web">{t('heartbeat.channels.web')}</option>
<option value="feishu">{t('heartbeat.channels.feishu')}</option>
+ <option value="wecom">{t('heartbeat.channels.wecom')}</option>
<option value="xiaoyi" disabled style={{ color: '#8c8c96ff'}}>{t('heartbeat.channels.xiaoyi')}</option>
<option value="dingtalk" disabled style={{ color: '#8c8c96ff' }}>{t('heartbeat.channels.dingtalk')}</option>
</select>
diff --git a/jiuwenclaw/web/src/components/SessionsPanel/index.tsx b/jiuwenclaw/web/src/components/SessionsPanel/index.tsx
index 0da2692f0b..e7a32117b3 100644
--- a/jiuwenclaw/web/src/components/SessionsPanel/index.tsx
+++ b/jiuwenclaw/web/src/components/SessionsPanel/index.tsx
@@ -43,13 +43,14 @@ function parseSessionDisplayLabel(sessionId: string, t: (key: string, options?:
if (!sessionId) return t('sessions.unknownSession');
// 处理以 sess_、cron_、feishu_、xiaoyi_、dingtalk_ 开头的会话ID
- const prefixes = ['sess_', 'cron_', 'feishu_', 'xiaoyi_', 'dingtalk_'];
+ const prefixes = ['sess_', 'cron_', 'feishu_', 'xiaoyi_', 'dingtalk_', 'wecom_'];
const prefixMap: Record<string, string> = {
'sess_': t('sessions.prefixes.session'),
'cron_': t('sessions.prefixes.cron'),
'feishu_': t('sessions.prefixes.feishu'),
'xiaoyi_': t('sessions.prefixes.xiaoyi'),
- 'dingtalk_': t('sessions.prefixes.dingtalk')
+ 'dingtalk_': t('sessions.prefixes.dingtalk'),
+ 'wecom_': t('sessions.prefixes.wecom')
};
for (const prefix of prefixes) {
diff --git a/jiuwenclaw/web/src/i18n/locales/en.json b/jiuwenclaw/web/src/i18n/locales/en.json
index 4f4bd5d366..862bfbabe5 100644
--- a/jiuwenclaw/web/src/i18n/locales/en.json
+++ b/jiuwenclaw/web/src/i18n/locales/en.json
@@ -103,6 +103,7 @@
"feishu": "Lark",
"xiaoyi": "Xiaoyi",
"dingtalk": "DingTalk",
+ "wecom": "WeCom",
"heartbeat": "Heartbeat",
"unknown": "Unknown"
},
@@ -142,6 +143,7 @@
"channels": {
"web": "Web (web)",
"feishu": "Lark (feishu)",
+ "wecom": "WeCom (wecom)",
"xiaoyi": "Xiaoyi (xiaoyi)",
"dingtalk": "DingTalk (dingtalk)"
},
@@ -235,7 +237,8 @@
"dingtalk": "DingTalk",
"telegram": "Telegram",
"discord": "Discord",
- "whatsapp": "WhatsApp"
+ "whatsapp": "WhatsApp",
+ "wecom": "WeCom"
},
"status": {
"loadFailed": "Load failed",
@@ -260,7 +263,9 @@
"telegramTitle": "Telegram Channel Configuration",
"telegramSubtitle": "Configure Telegram Bot service settings",
"whatsappTitle": "WhatsApp Channel Configuration",
- "whatsappSubtitle": "Configure WhatsApp Baileys Bridge service settings"
+ "whatsappSubtitle": "Configure WhatsApp Baileys Bridge service settings",
+ "wecomTitle": "WeCom Channel Configuration",
+ "wecomSubtitle": "Configure WeCom channel service settings"
},
"loading": {
"xiaoyi": "Loading Xiaoyi settings...",
@@ -268,7 +273,8 @@
"feishu": "Loading Lark settings...",
"telegram": "Loading Telegram settings...",
"discord": "Loading Discord settings...",
- "whatsapp": "Loading WhatsApp settings..."
+ "whatsapp": "Loading WhatsApp settings...",
+ "wecom": "Loading WeCom settings..."
},
"placeholders": {
"configValue": "Enter a configuration value",
@@ -279,7 +285,9 @@
"ids": "One ID per line (comma-separated is also supported)",
"telegramBotToken": "Enter Bot Token (from @BotFather)",
"telegramUserIds": "One Telegram user_id per line (comma-separated is also supported)",
- "whatsappJids": "One WhatsApp JID per line (comma-separated is also supported)"
+ "whatsappJids": "One WhatsApp JID per line (comma-separated is also supported)",
+ "wecomDefaultChatId": "userid or chatid (group)",
+ "wecomDefaultChatIdHint": "Target for heartbeat/scheduled push. Leave empty to use last chatid"
},
"saved": {
"feishu": "Lark settings saved",
@@ -287,7 +295,8 @@
"dingtalk": "DingTalk settings saved",
"telegram": "Telegram settings saved",
"discord": "Discord settings saved",
- "whatsapp": "WhatsApp settings saved"
+ "whatsapp": "WhatsApp settings saved",
+ "wecom": "WeCom settings saved"
},
"errors": {
"loadChannels": "Failed to load channels",
@@ -297,6 +306,7 @@
"loadTelegram": "Failed to load Telegram settings",
"loadDiscord": "Failed to load Discord settings",
"loadWhatsApp": "Failed to load WhatsApp settings",
+ "loadWecom": "Failed to load WeCom settings",
"saveGeneric": "Save failed, please try again later"
}
},
@@ -363,6 +373,7 @@
"targets": {
"web": "Web (web)",
"feishu": "Lark (feishu)",
+ "wecom": "WeCom (wecom)",
"xiaoyi": "Xiaoyi (xiaoyi)",
"dingtalk": "DingTalk (dingtalk)"
},
diff --git a/jiuwenclaw/web/src/i18n/locales/zh.json b/jiuwenclaw/web/src/i18n/locales/zh.json
index e12830000d..f3e8b613df 100644
--- a/jiuwenclaw/web/src/i18n/locales/zh.json
+++ b/jiuwenclaw/web/src/i18n/locales/zh.json
@@ -103,6 +103,7 @@
"feishu": "飞书",
"xiaoyi": "小艺",
"dingtalk": "钉钉",
+ "wecom": "企业微信",
"heartbeat": "心跳",
"unknown": "未知"
},
@@ -142,6 +143,7 @@
"channels": {
"web": "网页 (web)",
"feishu": "飞书 (feishu)",
+ "wecom": "企业微信 (wecom)",
"xiaoyi": "小艺 (xiaoyi)",
"dingtalk": "钉钉 (dingtalk)"
},
@@ -235,7 +237,8 @@
"dingtalk": "钉钉",
"telegram": "Telegram",
"discord": "Discord",
- "whatsapp": "WhatsApp"
+ "whatsapp": "WhatsApp",
+ "wecom": "企业微信"
},
"status": {
"loadFailed": "加载失败",
@@ -260,7 +263,9 @@
"telegramTitle": "Telegram 频道参数配置",
"telegramSubtitle": "配置 Telegram Bot 服务相关参数",
"whatsappTitle": "WhatsApp 频道参数配置",
- "whatsappSubtitle": "配置 WhatsApp Baileys Bridge 服务相关参数"
+ "whatsappSubtitle": "配置 WhatsApp Baileys Bridge 服务相关参数",
+ "wecomTitle": "企业微信频道参数配置",
+ "wecomSubtitle": "配置企业微信频道相关参数"
},
"loading": {
"xiaoyi": "正在加载小艺配置...",
@@ -268,7 +273,8 @@
"feishu": "正在加载飞书配置...",
"telegram": "正在加载 Telegram 配置...",
"discord": "正在加载 Discord 配置...",
- "whatsapp": "正在加载 WhatsApp 配置..."
+ "whatsapp": "正在加载 WhatsApp 配置...",
+ "wecom": "正在加载企业微信配置..."
},
"placeholders": {
"configValue": "请输入配置值",
@@ -279,7 +285,9 @@
"ids": "每行一个 ID(也支持逗号分隔)",
"telegramBotToken": "请输入 Bot Token(从 @BotFather 获取)",
"telegramUserIds": "每行一个 Telegram user_id(也支持逗号分隔)",
- "whatsappJids": "每行一个 WhatsApp JID(也支持逗号分隔)"
+ "whatsappJids": "每行一个 WhatsApp JID(也支持逗号分隔)",
+ "wecomDefaultChatId": "userid 或 chatid(群聊)",
+ "wecomDefaultChatIdHint": "心跳/定时推送目标。不填则自动使用最近一次聊天的 chatid"
},
"saved": {
"feishu": "飞书配置已保存",
@@ -287,7 +295,8 @@
"dingtalk": "钉钉配置已保存",
"telegram": "Telegram 配置已保存",
"discord": "Discord 配置已保存",
- "whatsapp": "WhatsApp 配置已保存"
+ "whatsapp": "WhatsApp 配置已保存",
+ "wecom": "企业微信配置已保存"
},
"errors": {
"loadChannels": "获取 channels 失败",
@@ -297,6 +306,7 @@
"loadTelegram": "获取 Telegram 配置失败",
"loadDiscord": "获取 Discord 配置失败",
"loadWhatsApp": "获取 WhatsApp 配置失败",
+ "loadWecom": "获取企业微信配置失败",
"saveGeneric": "保存失败,请稍后重试"
}
},
@@ -363,6 +373,7 @@
"targets": {
"web": "网页 (web)",
"feishu": "飞书 (feishu)",
+ "wecom": "企业微信 (wecom)",
"xiaoyi": "小艺 (xiaoyi)",
"dingtalk": "钉钉 (dingtalk)"
},
diff --git a/pyproject.toml b/pyproject.toml
index d5a58f2d98..b24c7423a7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -27,6 +27,7 @@ dependencies = [
"python-telegram-bot>=20.0",
"discord.py>=2.4.0",
"dingtalk-stream>=0.24.3",
+ "wecom-aibot-sdk>=1.0.0",
"python-socks>=2.8.1",
"greenlet>=3.3.2",
"skillnet-ai>=0.0.14",
diff --git a/uv.lock b/uv.lock
index f631af08e6..b22223d236 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1365,6 +1365,7 @@ dependencies = [
{ name = "ruamel-yaml" },
{ name = "skillnet-ai" },
{ name = "websockets" },
+ { name = "wecom-aibot-sdk" },
]
[package.optional-dependencies]
@@ -1392,6 +1393,7 @@ requires-dist = [
{ name = "ruamel-yaml", specifier = ">=0.18.0" },
{ name = "skillnet-ai", specifier = ">=0.0.14" },
{ name = "websockets", specifier = ">=12.0" },
+ { name = "wecom-aibot-sdk", specifier = ">=1.0.0" },
]
provides-extras = ["dev"]
@@ -4070,6 +4072,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598, upload-time = "2026-01-10T09:23:45.395Z" },
]
+[[package]]
+name = "wecom-aibot-sdk"
+version = "1.0.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+ { name = "httpx" },
+ { name = "websockets" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/aa/57/08f0f012a585a1e34b4d903376e9f7610f965dadec995202371883834d1f/wecom_aibot_sdk-1.0.3.tar.gz", hash = "sha256:5f81394c85e7f1d7c8de33aecf705768800509a12d3a0e571c2e7d97bf1961ad", size = 39777, upload-time = "2026-03-16T11:07:11.032Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/1e/686df5a8e689c5c9af5dc9b1f50cfbb51aa26c2e75ad535cc530e121db97/wecom_aibot_sdk-1.0.3-py3-none-any.whl", hash = "sha256:cd1724307c342bab8c5c652b04b3ab743d1b6542831f8847e8a893eb29db8cab", size = 21512, upload-time = "2026-03-16T11:07:09.365Z" },
+]
+
[[package]]
name = "win32-setctime"
version = "1.2.0"