Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
Merge main into pr-332
Re-bin4021f5212c1e
diff --cc nanobot/channels/feishu.pyindex a4c745460,611c95e18..2dcf71023--- a/nanobot/channels/feishu.py+++ b/nanobot/channels/feishu.py@@@ -63,7 -253,7 +253,13 @@@ class FeishuChannel(BaseChannel)self._ws_thread: threading.Thread | None = Noneself._processed_message_ids: OrderedDict[str, None] = OrderedDict() # Ordered dedup cacheself._loop: asyncio.AbstractEventLoop | None = None-+++ @staticmethod++ def _register_optional_event(builder: Any, method_name: str, handler: Any) -> Any:++ """Register an event handler only when the SDK supports it."""++ method = getattr(builder, method_name, None)++ return method(handler) if callable(method) else builder++async def start(self) -> None:"""Start the Feishu bot with WebSocket long connection."""if not FEISHU_AVAILABLE:@@@ -83,21 -274,15 +280,25 @@@.app_secret(self.config.app_secret) \.log_level(lark.LogLevel.INFO) \.build()-- # Create event handler (register message receive and other common events)-- # Create event handler (only register message receive, ignore other events)-- event_handler = lark.EventDispatcherHandler.builder(++ builder = lark.EventDispatcherHandler.builder(self.config.encrypt_key or "",self.config.verification_token or "",).register_p2_im_message_receive_v1(self._on_message_sync- ).register_p2_im_message_reaction_created_v1(- self._on_reaction_created- ).register_p2_im_message_message_read_v1(- self._on_message_read- ).register_p2_im_chat_access_event_bot_p2p_chat_entered_v1(- self._on_bot_p2p_chat_entered-- ).build()-++ )++ builder = self._register_optional_event(++ builder, "register_p2_im_message_reaction_created_v1", self._on_reaction_created++ )++ builder = self._register_optional_event(++ builder, "register_p2_im_message_message_read_v1", self._on_message_read++ )++ builder = self._register_optional_event(++ builder,++ "register_p2_im_chat_access_event_bot_p2p_chat_entered_v1",++ self._on_bot_p2p_chat_entered,++ )++ event_handler = builder.build()+# Create WebSocket client for long connectionself._ws_client = lark.ws.Client(self.config.app_id,@@@ -234,29 -761,96 +777,96 @@@.content(content).build()).build()-response = self._client.im.v1.message.create(request)-if not response.success():logger.error(- f"Failed to send Feishu message: code={response.code}, "- f"msg={response.msg}, log_id={response.get_log_id()}"+ "Failed to send Feishu {} message: code={}, msg={}, log_id={}",+ msg_type, response.code, response.msg, response.get_log_id())- else:- logger.debug(f"Feishu message sent to {msg.chat_id}")-+ return False+ logger.debug("Feishu {} message sent to {}", msg_type, receive_id)+ return Trueexcept Exception as e:- logger.error(f"Error sending Feishu message: {e}")-- def _on_message_sync(self, data: "P2ImMessageReceiveV1") -> None:+ logger.error("Error sending Feishu {} message: {}", msg_type, e)+ return False++ async def send(self, msg: OutboundMessage) -> None:+ """Send a message through Feishu, including media (images/files) if present."""+ if not self._client:+ logger.warning("Feishu client not initialized")+ return++ try:+ receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"+ loop = asyncio.get_running_loop()++ for file_path in msg.media:+ if not os.path.isfile(file_path):+ logger.warning("Media file not found: {}", file_path)+ continue+ ext = os.path.splitext(file_path)[1].lower()+ if ext in self._IMAGE_EXTS:+ key = await loop.run_in_executor(None, self._upload_image_sync, file_path)+ if key:+ await loop.run_in_executor(+ None, self._send_message_sync,+ receive_id_type, msg.chat_id, "image", json.dumps({"image_key": key}, ensure_ascii=False),+ )+ else:+ key = await loop.run_in_executor(None, self._upload_file_sync, file_path)+ if key:+ # Use msg_type "media" for audio/video so users can play inline;+ # "file" for everything else (documents, archives, etc.)+ if ext in self._AUDIO_EXTS or ext in self._VIDEO_EXTS:+ media_type = "media"+ else:+ media_type = "file"+ await loop.run_in_executor(+ None, self._send_message_sync,+ receive_id_type, msg.chat_id, media_type, json.dumps({"file_key": key}, ensure_ascii=False),+ )++ if msg.content and msg.content.strip():+ fmt = self._detect_msg_format(msg.content)++ if fmt == "text":+ # Short plain text – send as simple text message+ text_body = json.dumps({"text": msg.content.strip()}, ensure_ascii=False)+ await loop.run_in_executor(+ None, self._send_message_sync,+ receive_id_type, msg.chat_id, "text", text_body,+ )++ elif fmt == "post":+ # Medium content with links – send as rich-text post+ post_body = self._markdown_to_post(msg.content)+ await loop.run_in_executor(+ None, self._send_message_sync,+ receive_id_type, msg.chat_id, "post", post_body,+ )++ else:+ # Complex / long content – send as interactive card+ elements = self._build_card_elements(msg.content)+ for chunk in self._split_elements_by_table_limit(elements):+ card = {"config": {"wide_screen_mode": True}, "elements": chunk}+ await loop.run_in_executor(+ None, self._send_message_sync,+ receive_id_type, msg.chat_id, "interactive", json.dumps(card, ensure_ascii=False),+ )++ except Exception as e:+ logger.error("Error sending Feishu message: {}", e)+- def _on_message_sync(self, data: "P2ImMessageReceiveV1") -> None:++ def _on_message_sync(self, data: Any) -> None:"""Sync handler for incoming messages (called from WebSocket thread).Schedules async handling in the main event loop."""if self._loop and self._loop.is_running():asyncio.run_coroutine_threadsafe(self._on_message(data), self._loop)-- async def _on_message(self, data: "P2ImMessageReceiveV1") -> None:+- async def _on_message(self, data: "P2ImMessageReceiveV1") -> None:++ async def _on_message(self, data: Any) -> None:"""Handle incoming message from Feishu."""try:event = data.event@@@ -310,29 -951,6 +967,19 @@@"msg_type": msg_type,})-+except Exception as e:- logger.error(f"Error processing Feishu message: {e}")+ logger.error("Error processing Feishu message: {}", e)+- def _on_reaction_created(self, data: "P2ImMessageReactionCreatedV1") -> None:- """- Handler for message reaction events.- We don't need to process these, but registering prevents error logs.- """++ def _on_reaction_created(self, data: Any) -> None:++ """Ignore reaction events so they do not generate SDK noise."""+ pass-- def _on_message_read(self, data: "P2ImMessageMessageReadV1") -> None:- """- Handler for message read events.- We don't need to process these, but registering prevents error logs.- """++++ def _on_message_read(self, data: Any) -> None:++ """Ignore read events so they do not generate SDK noise."""+ pass-+++ def _on_bot_p2p_chat_entered(self, data: Any) -> None:- """- Handler for bot entering p2p chat events.- This is triggered when a user opens a chat with the bot.- We don't need to process these, but registering prevents error logs.- """++ """Ignore p2p-enter events when a user opens a bot chat."""+ logger.debug("Bot entered p2p chat (user opened chat window)")+ passdiff --cc tests/test_feishu_post_content.pyindex 000000000,bf1ea823d..7b1cb9d31mode 000000,100644..100644--- a/tests/test_feishu_post_content.py+++ b/tests/test_feishu_post_content.py@@@ -1,0 -1,40 +1,65 @@@-from nanobot.channels.feishu import _extract_post_content++from nanobot.channels.feishu import FeishuChannel, _extract_post_content+++ def test_extract_post_content_supports_post_wrapper_shape() -> None:+ payload = {+ "post": {+ "zh_cn": {+ "title": "日报",+ "content": [+ [+ {"tag": "text", "text": "完成"},+ {"tag": "img", "image_key": "img_1"},+ ]+ ],+ }+ }+ }++ text, image_keys = _extract_post_content(payload)++ assert text == "日报 完成"+ assert image_keys == ["img_1"]+++ def test_extract_post_content_keeps_direct_shape_behavior() -> None:+ payload = {+ "title": "Daily",+ "content": [+ [+ {"tag": "text", "text": "report"},+ {"tag": "img", "image_key": "img_a"},+ {"tag": "img", "image_key": "img_b"},+ ]+ ],+ }++ text, image_keys = _extract_post_content(payload)++ assert text == "Daily report"+ assert image_keys == ["img_a", "img_b"]++++++def test_register_optional_event_keeps_builder_when_method_missing() -> None:++ class Builder:++ pass++++ builder = Builder()++ same = FeishuChannel._register_optional_event(builder, "missing", object())++ assert same is builder++++++def test_register_optional_event_calls_supported_method() -> None:++ called = []++++ class Builder:++ def register_event(self, handler):++ called.append(handler)++ return self++++ builder = Builder()++ handler = object()++ same = FeishuChannel._register_optional_event(builder, "register_event", handler)++++ assert same is builder++ assert called == [handler]