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: 支持feishu多bot channel(feishu_enterprise)、修复由多bot实例引入的 ws 冲突与多Bot会话持久化

yechenzhen9a42eea9716f
diff --git "a/docs/\351\242\221\351\201\223.md" "b/docs/\351\242\221\351\201\223.md"
index 6c145da2af..2048ae4418 100644
--- "a/docs/\351\242\221\351\201\223.md"
+++ "b/docs/\351\242\221\351\201\223.md"
@@ -151,6 +151,56 @@ channels:
1. 启动前端服务后,在"频道-飞书"自己中打开Enable开关并配置第三步记录的 App ID 与 App Secret
1. 启动前端服务后,在“频道-飞书”中打开Enable开关并配置第三步记录的 App ID 与 App Secret
+## 9. 飞书多bot(`feishu_enterprise`)
+
+当一个团队需要在同一套 JiuwenClaw 服务中接入多个飞书应用(多个 Bot)时,可使用 `channels.feishu_enterprise`。
+
+每个 bot 会以独立 channel 运行,channel_id 格式为:`feishu_enterprise:<app_id>`。
+
+当前多bot仅支持手动编辑 `~/.jiuwenclaw/config/config.yaml`:
+
+``````
+channels:
+ feishu_enterprise:
+ bot_a:
+ app_id: "cli_xxx"
+ app_secret: "xxx"
+ encrypt_key: ""
+ verification_token: ""
+ allow_from: []
+ enable_streaming: true
+ chat_id: ""
+ enabled: true
+ bot_b:
+ app_id: "cli_yyy"
+ app_secret: "yyy"
+ encrypt_key: ""
+ verification_token: ""
+ allow_from: []
+ enable_streaming: true
+ chat_id: ""
+ enabled: true
+``````
+
+### 字段说明
+
+| 配置项 | 说明 |
+|:------|:-----|
+| `app_id` | 飞书应用 App ID(必填) |
+| `app_secret` | 飞书应用 App Secret(必填) |
+| `encrypt_key` | 事件订阅加密 Key(可选) |
+| `verification_token` | 事件订阅 Token(可选) |
+| `allow_from` | 允许的用户 open_id 列表,空列表表示不限制 |
+| `enable_streaming` | 是否启用流式下发 |
+| `chat_id` | 固定推送目标(可选) |
+| `enabled` | 是否启用该 bot |
+
+### 与单 Bot `feishu` 的区别
+
+- `feishu`:单通道,channel_id 固定为 `feishu`。
+- `feishu_enterprise`:多通道,每个 bot 使用独立 channel_id(`feishu_enterprise:<app_id>`)。
+- 多 Bot 场景下,会按 bot 维度分别记录最近会话信息,避免 bot 之间互相覆盖。
+
# 钉钉
## 1. 前提条件
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index 89d8121c8a..62ff29ccef 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -1481,6 +1481,8 @@ async def _run() -> None:
whatsapp_task = None
wecom_channel = None
wecom_task = None
+ feishu_enterprise_channels: dict[str, FeishuChannel] = {}
+ feishu_enterprise_tasks: dict[str, asyncio.Task] = {}
_last_channels_conf = {} # Store previous config to detect changes
@@ -1540,10 +1542,11 @@ async def _run() -> None:
nonlocal discord_channel, discord_task
nonlocal whatsapp_channel, whatsapp_task
nonlocal wecom_channel, wecom_task, _last_channels_conf
+ nonlocal feishu_enterprise_channels, feishu_enterprise_tasks
changed_channels = [
c
- for c in ["feishu", "xiaoyi", "dingtalk", "telegram", "whatsapp", "discord", "wecom"]
+ for c in ["feishu", "feishu_enterprise", "xiaoyi", "dingtalk", "telegram", "whatsapp", "discord", "wecom"]
if _should_restart_channel(c, _last_channels_conf, conf)
]
_last_channels_conf = dict(conf or {})
@@ -1575,6 +1578,58 @@ async def _run() -> None:
else:
logger.info("[App] channels.feishu 未配置或格式错误,FeishuChannel 不启用")
+ if "feishu_enterprise" in changed_channels:
+ for bot_key, task in list(feishu_enterprise_tasks.items()):
+ await _stop_channel(feishu_enterprise_channels.get(bot_key), task, f"feishu_enterprise[{bot_key}]")
+ feishu_enterprise_channels = {}
+ feishu_enterprise_tasks = {}
+
+ enterprise_conf = conf.get("feishu_enterprise") if isinstance(conf, dict) else None
+ if not isinstance(enterprise_conf, dict):
+ logger.info("[App] channels.feishu_enterprise 未配置或格式错误,FeishuEnterpriseChannel 不启用")
+ else:
+ for bot_key, bot_conf_raw in enterprise_conf.items():
+ if not isinstance(bot_key, str) or not bot_key.strip():
+ continue
+ bot_conf = bot_conf_raw if isinstance(bot_conf_raw, dict) else None
+ if bot_conf is None:
+ logger.info("[App] channels.feishu_enterprise.%s 配置格式错误,跳过", bot_key)
+ continue
+ enabled, reason = _is_channel_enabled(bot_conf, ["app_id", "app_secret"])
+ if not enabled:
+ logger.info(
+ "[App] channels.feishu_enterprise.%s.%s,FeishuEnterpriseChannel 未启用",
+ bot_key,
+ reason,
+ )
+ continue
+
+ bot_key = bot_key.strip()
+ app_id = str(bot_conf.get("app_id") or "").strip()
+ channel_id = f"feishu_enterprise:{app_id}"
+ feishu_config = FeishuConfig(
+ enabled=True,
+ app_id=app_id,
+ app_secret=str(bot_conf.get("app_secret") or "").strip(),
+ encrypt_key=str(bot_conf.get("encrypt_key") or "").strip(),
+ verification_token=str(bot_conf.get("verification_token") or "").strip(),
+ allow_from=bot_conf.get("allow_from") or [],
+ enable_streaming=bool(bot_conf.get("enable_streaming", True)),
+ chat_id=str(bot_conf.get("chat_id") or "").strip(),
+ channel_id=channel_id,
+ bot_key=bot_key,
+ )
+ channel = FeishuChannel(feishu_config, _DummyBus())
+ channel_manager.register_channel(channel)
+ task = asyncio.create_task(channel.start(), name=f"feishu-enterprise-{bot_key}")
+ feishu_enterprise_channels[bot_key] = channel
+ feishu_enterprise_tasks[bot_key] = task
+ logger.info(
+ "[App] 已按 config.yaml.channels.feishu_enterprise.%s 注册 FeishuChannel(%s)",
+ bot_key,
+ channel_id,
+ )
+
if "xiaoyi" in changed_channels:
xiaoyi_conf = conf.get("xiaoyi") if isinstance(conf, dict) else None
await _stop_channel(xiaoyi_channel, xiaoyi_task, "xiaoyi")
@@ -1806,6 +1861,15 @@ async def _run() -> None:
except asyncio.CancelledError:
pass
await feishu_channel.stop()
+ for bot_key, task in list(feishu_enterprise_tasks.items()):
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ channel = feishu_enterprise_channels.get(bot_key)
+ if channel is not None:
+ await channel.stop()
if xiaoyi_channel is not None and xiaoyi_task is not None:
xiaoyi_task.cancel()
try:
diff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.py
index a720d13fa1..8d3152cce4 100644
--- a/jiuwenclaw/channel/feishu.py
+++ b/jiuwenclaw/channel/feishu.py
@@ -28,6 +28,8 @@ class FeishuConfig(BaseModel):
allow_from: list[str] = Field(default_factory=list) # 允许的用户的open_id列表
enable_streaming: bool = True # 是否开启流式/过程消息下发
chat_id: str = "" # 可选:固定推送目标 chat_id(群聊 oc_xxx 或个人 open_id)
+ channel_id: str = "feishu" # ChannelManager 路由键,支持多实例
+ bot_key: str = "" # 企业飞书多 bot 配置键(仅 feishu_enterprise 使用)
try:
@@ -56,6 +58,25 @@ MSG_TYPE_MAP = {
}
+class _ThreadLocalLoopProxy:
+ """Provide a thread-local event loop proxy for lark_oapi ws client."""
+
+ @staticmethod
+ def _get_loop() -> asyncio.AbstractEventLoop:
+ try:
+ return asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ return loop
+
+ def run_until_complete(self, coro):
+ return self._get_loop().run_until_complete(coro)
+
+ def create_task(self, coro):
+ return self._get_loop().create_task(coro)
+
+
class FeishuChannel(BaseChannel):
"""
飞书/飞书IM通道实现,基于WebSocket长连接。
@@ -73,6 +94,8 @@ class FeishuChannel(BaseChannel):
"""
name = "feishu"
+ _ws_loop_proxy_lock = threading.Lock()
+ _ws_loop_proxy_installed = False
def __init__(self, config: FeishuConfig, router: RobotMessageRouter):
"""
@@ -84,6 +107,7 @@ class FeishuChannel(BaseChannel):
"""
super().__init__(config, router)
self.config: FeishuConfig = config
+ self._channel_id = str(getattr(config, "channel_id", "") or self.name).strip() or self.name
self._api_client: Any = None # 飞书API客户端(用于发送消息)
self._websocket_client: Any = None # WebSocket客户端(用于接收消息)
self._websocket_thread: threading.Thread | None = None # WebSocket运行线程
@@ -98,7 +122,7 @@ class FeishuChannel(BaseChannel):
@property
def channel_id(self) -> str:
"""返回通道唯一标识符,用于ChannelManager注册与消息派发。"""
- return self.name
+ return self._channel_id
def on_message(self, callback: Callable[[Message], None]) -> None:
"""
@@ -131,7 +155,7 @@ class FeishuChannel(BaseChannel):
msg = Message(
id=message_id,
type="req",
- channel_id=self.name,
+ channel_id=self.channel_id,
session_id=str(chat_id),
params={"content": content, "query": content},
timestamp=time.time(), ok=True,
@@ -213,11 +237,8 @@ class FeishuChannel(BaseChannel):
asyncio.set_event_loop(loop)
self._ws_thread_loop = loop
- # 临时替换lark_oapi.ws.client模块的事件循环,避免"already running"错误
- import lark_oapi.ws.client as _ws_client_mod
-
- _saved_loop = getattr(_ws_client_mod, "loop", None)
- _ws_client_mod.loop = loop
+ # 将 SDK 的模块级 loop 替换为线程内代理,避免多实例时相互覆盖。
+ self._ensure_thread_local_ws_loop_proxy()
ws_client = None
try:
@@ -241,23 +262,23 @@ class FeishuChannel(BaseChannel):
ws_client.start()
except Exception as e:
if self._stopping or not self._running:
- logger.info("飞书WebSocket线程退出: {}", e)
+ logger.info("飞书WebSocket线程退出: %s", e)
else:
- logger.error("飞书WebSocket连接建立失败: {}", e)
+ logger.error("飞书WebSocket连接建立失败: %s", e)
finally:
- self._cleanup_websocket_thread(_saved_loop, ws_client, loop)
+ self._cleanup_websocket_thread(ws_client, loop)
- def _cleanup_websocket_thread(
- self,
- saved_loop: Any,
- ws_client: Any,
- loop: asyncio.AbstractEventLoop,
- ) -> None:
- """清理WebSocket线程资源。"""
- import lark_oapi.ws.client as _ws_client_mod
+ @classmethod
+ def _ensure_thread_local_ws_loop_proxy(cls) -> None:
+ with cls._ws_loop_proxy_lock:
+ if cls._ws_loop_proxy_installed:
+ return
+ import lark_oapi.ws.client as _ws_client_mod
+ _ws_client_mod.loop = _ThreadLocalLoopProxy()
+ cls._ws_loop_proxy_installed = True
- if saved_loop is not None:
- _ws_client_mod.loop = saved_loop
+ def _cleanup_websocket_thread(self, ws_client: Any, loop: asyncio.AbstractEventLoop) -> None:
+ """清理WebSocket线程资源。"""
if ws_client is None:
self._websocket_client = None
@@ -991,20 +1012,37 @@ class FeishuChannel(BaseChannel):
)
# 将最近一次可回发的飞书身份写入 config.yaml,供 cron 推送时使用
- try:
- from jiuwenclaw.config import update_channel_in_config
-
- update_channel_in_config(
- "feishu",
- {
- "last_chat_id": getattr(message, "chat_id", None) or "",
- "last_open_id": open_id or "",
- "last_message_id": getattr(message, "message_id", None) or "",
- },
- )
- except Exception:
- # 不影响正常收消息
- pass
+ if self.channel_id == self.name:
+ try:
+ from jiuwenclaw.config import update_channel_in_config
+
+ update_channel_in_config(
+ "feishu",
+ {
+ "last_chat_id": getattr(message, "chat_id", None) or "",
+ "last_open_id": open_id or "",
+ "last_message_id": getattr(message, "message_id", None) or "",
+ },
+ )
+ except Exception:
+ # 不影响正常收消息
+ pass
+ elif self.channel_id.startswith("feishu_enterprise:") and self.config.bot_key:
+ try:
+ from jiuwenclaw.config import update_channel_subsection_in_config
+
+ update_channel_subsection_in_config(
+ "feishu_enterprise",
+ self.config.bot_key,
+ {
+ "last_chat_id": getattr(message, "chat_id", None) or "",
+ "last_open_id": open_id or "",
+ "last_message_id": getattr(message, "message_id", None) or "",
+ },
+ )
+ except Exception:
+ # 不影响正常收消息
+ pass
# 处理消息:将平台身份写入 metadata,供回发时使用(与 session_id 解耦,\new_session 后仍可正确回发)
await self._handle_message(
diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.py
index d036d957fd..338ddbbff9 100644
--- a/jiuwenclaw/config.py
+++ b/jiuwenclaw/config.py
@@ -129,6 +129,27 @@ def update_channel_in_config(channel_id: str, conf: dict[str, Any]) -> None:
_dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+def update_channel_subsection_in_config(
+ channel_id: str,
+ subsection_id: str,
+ conf: dict[str, Any],
+) -> None:
+ """更新 channels[channel_id][subsection_id] 并写回。"""
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
+ if "channels" not in data:
+ data["channels"] = {}
+ channels = data["channels"]
+ if channel_id not in channels:
+ channels[channel_id] = {}
+ section = channels[channel_id]
+ if subsection_id not in section:
+ section[subsection_id] = {}
+ subsection = section[subsection_id]
+ for k, v in conf.items():
+ subsection[k] = v
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+
+
def update_preferred_language_in_config(lang: str) -> None:
"""只更新顶层 preferred_language 并写回。"""
data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
diff --git a/jiuwenclaw/gateway/cron/scheduler.py b/jiuwenclaw/gateway/cron/scheduler.py
index 4427c0b074..ba8afc847f 100644
--- a/jiuwenclaw/gateway/cron/scheduler.py
+++ b/jiuwenclaw/gateway/cron/scheduler.py
@@ -400,7 +400,8 @@ class CronSchedulerService:
from jiuwenclaw.config import get_config_raw
cfg = get_config_raw() or {}
- ch_cfg = (cfg.get("channels") or {}).get(channel_id) or {}
+ channels_cfg = cfg.get("channels") or {}
+ ch_cfg = channels_cfg.get(channel_id) or {}
if channel_id == "feishu":
last_chat_id = str(ch_cfg.get("last_chat_id") or "").strip()
last_open_id = str(ch_cfg.get("last_open_id") or "").strip()
@@ -409,6 +410,24 @@ class CronSchedulerService:
"feishu_chat_id": last_chat_id,
"feishu_open_id": last_open_id,
}
+ elif channel_id.startswith("feishu_enterprise:"):
+ app_id = channel_id.split(":", 1)[1].strip()
+ enterprise_cfg = channels_cfg.get("feishu_enterprise") or {}
+ if isinstance(enterprise_cfg, dict) and app_id:
+ for _, bot_cfg in enterprise_cfg.items():
+ if not isinstance(bot_cfg, dict):
+ continue
+ bot_app_id = str(bot_cfg.get("app_id") or "").strip()
+ if bot_app_id != app_id:
+ continue
+ last_chat_id = str(bot_cfg.get("last_chat_id") or "").strip()
+ last_open_id = str(bot_cfg.get("last_open_id") or "").strip()
+ if last_chat_id or last_open_id:
+ metadata = {
+ "feishu_chat_id": last_chat_id,
+ "feishu_open_id": last_open_id,
+ }
+ break
elif channel_id == "xiaoyi":
last_session_id = str(ch_cfg.get("last_session_id") or "").strip()
last_task_id = str(ch_cfg.get("last_task_id") or "").strip()
diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yaml
index c6986b5c34..4057a89a57 100644
--- a/jiuwenclaw/resources/config.yaml
+++ b/jiuwenclaw/resources/config.yaml
@@ -118,6 +118,17 @@ channels:
allow_from:
enable_streaming: false
enabled: false
+ feishu_enterprise:
+ # 企业飞书多 Bot 配置(每个 bot 会注册为独立 channel: feishu_enterprise:<app_id>)
+ # bot_a:
+ # app_id:
+ # app_secret:
+ # encrypt_key:
+ # verification_token:
+ # allow_from: []
+ # enable_streaming: true
+ # chat_id:
+ # enabled: false
xiaoyi:
# 华为小艺 A2A 配置
mode: xiaoyi_channel