merge: resolve PR #1966 conflicts with main

This commit is contained in:
Xubin Ren
2026-03-14 15:32:19 +00:00
38 changed files with 2163 additions and 320 deletions
+146 -19
View File
@@ -7,7 +7,7 @@ import re
import threading
from collections import OrderedDict
from pathlib import Path
from typing import Any
from typing import Any, Literal
from loguru import logger
@@ -15,7 +15,8 @@ from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir
from nanobot.config.schema import FeishuConfig
from nanobot.config.schema import Base
from pydantic import Field
import importlib.util
@@ -231,6 +232,20 @@ def _extract_post_text(content_json: dict) -> str:
return text
class FeishuConfig(Base):
"""Feishu/Lark channel configuration using WebSocket long connection."""
enabled: bool = False
app_id: str = ""
app_secret: str = ""
encrypt_key: str = ""
verification_token: str = ""
allow_from: list[str] = Field(default_factory=list)
react_emoji: str = "THUMBSUP"
group_policy: Literal["open", "mention"] = "mention"
reply_to_message: bool = False # If True, bot replies quote the user's original message
class FeishuChannel(BaseChannel):
"""
Feishu/Lark channel using WebSocket long connection.
@@ -246,7 +261,13 @@ class FeishuChannel(BaseChannel):
name = "feishu"
display_name = "Feishu"
def __init__(self, config: FeishuConfig, bus: MessageBus):
@classmethod
def default_config(cls) -> dict[str, Any]:
return FeishuConfig().model_dump(by_alias=True)
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = FeishuConfig.model_validate(config)
super().__init__(config, bus)
self.config: FeishuConfig = config
self._client: Any = None
@@ -786,6 +807,77 @@ class FeishuChannel(BaseChannel):
return None, f"[{msg_type}: download failed]"
_REPLY_CONTEXT_MAX_LEN = 200
def _get_message_content_sync(self, message_id: str) -> str | None:
"""Fetch the text content of a Feishu message by ID (synchronous).
Returns a "[Reply to: ...]" context string, or None on failure.
"""
from lark_oapi.api.im.v1 import GetMessageRequest
try:
request = GetMessageRequest.builder().message_id(message_id).build()
response = self._client.im.v1.message.get(request)
if not response.success():
logger.debug(
"Feishu: could not fetch parent message {}: code={}, msg={}",
message_id, response.code, response.msg,
)
return None
items = getattr(response.data, "items", None)
if not items:
return None
msg_obj = items[0]
raw_content = getattr(msg_obj, "body", None)
raw_content = getattr(raw_content, "content", None) if raw_content else None
if not raw_content:
return None
try:
content_json = json.loads(raw_content)
except (json.JSONDecodeError, TypeError):
return None
msg_type = getattr(msg_obj, "msg_type", "")
if msg_type == "text":
text = content_json.get("text", "").strip()
elif msg_type == "post":
text, _ = _extract_post_content(content_json)
text = text.strip()
else:
text = ""
if not text:
return None
if len(text) > self._REPLY_CONTEXT_MAX_LEN:
text = text[: self._REPLY_CONTEXT_MAX_LEN] + "..."
return f"[Reply to: {text}]"
except Exception as e:
logger.debug("Feishu: error fetching parent message {}: {}", message_id, e)
return None
def _reply_message_sync(self, parent_message_id: str, msg_type: str, content: str) -> bool:
"""Reply to an existing Feishu message using the Reply API (synchronous)."""
from lark_oapi.api.im.v1 import ReplyMessageRequest, ReplyMessageRequestBody
try:
request = ReplyMessageRequest.builder() \
.message_id(parent_message_id) \
.request_body(
ReplyMessageRequestBody.builder()
.msg_type(msg_type)
.content(content)
.build()
).build()
response = self._client.im.v1.message.reply(request)
if not response.success():
logger.error(
"Failed to reply to Feishu message {}: code={}, msg={}, log_id={}",
parent_message_id, response.code, response.msg, response.get_log_id()
)
return False
logger.debug("Feishu reply sent to message {}", parent_message_id)
return True
except Exception as e:
logger.error("Error replying to Feishu message {}: {}", parent_message_id, e)
return False
def _send_message_sync(self, receive_id_type: str, receive_id: str, msg_type: str, content: str) -> bool:
"""Send a single message (text/image/file/interactive) synchronously."""
from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody
@@ -822,12 +914,38 @@ class FeishuChannel(BaseChannel):
receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
loop = asyncio.get_running_loop()
# Handle tool hint messages as code blocks in interactive cards
# Handle tool hint messages as code blocks in interactive cards.
# These are progress-only messages and should bypass normal reply routing.
if msg.metadata.get("_tool_hint"):
if msg.content and msg.content.strip():
await self._send_tool_hint_card(receive_id_type, msg.chat_id, msg.content.strip())
await self._send_tool_hint_card(
receive_id_type, msg.chat_id, msg.content.strip()
)
return
# Determine whether the first message should quote the user's message.
# Only the very first send (media or text) in this call uses reply; subsequent
# chunks/media fall back to plain create to avoid redundant quote bubbles.
reply_message_id: str | None = None
if (
self.config.reply_to_message
and not msg.metadata.get("_progress", False)
):
reply_message_id = msg.metadata.get("message_id") or None
first_send = True # tracks whether the reply has already been used
def _do_send(m_type: str, content: str) -> None:
"""Send via reply (first message) or create (subsequent)."""
nonlocal first_send
if reply_message_id and first_send:
first_send = False
ok = self._reply_message_sync(reply_message_id, m_type, content)
if ok:
return
# Fall back to regular send if reply fails
self._send_message_sync(receive_id_type, msg.chat_id, m_type, content)
for file_path in msg.media:
if not os.path.isfile(file_path):
logger.warning("Media file not found: {}", file_path)
@@ -837,8 +955,8 @@ class FeishuChannel(BaseChannel):
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),
None, _do_send,
"image", json.dumps({"image_key": key}, ensure_ascii=False),
)
else:
key = await loop.run_in_executor(None, self._upload_file_sync, file_path)
@@ -850,8 +968,8 @@ class FeishuChannel(BaseChannel):
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),
None, _do_send,
media_type, json.dumps({"file_key": key}, ensure_ascii=False),
)
if msg.content and msg.content.strip():
@@ -860,18 +978,12 @@ class FeishuChannel(BaseChannel):
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,
)
await loop.run_in_executor(None, _do_send, "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,
)
await loop.run_in_executor(None, _do_send, "post", post_body)
else:
# Complex / long content send as interactive card
@@ -879,8 +991,8 @@ class FeishuChannel(BaseChannel):
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),
None, _do_send,
"interactive", json.dumps(card, ensure_ascii=False),
)
except Exception as e:
@@ -975,6 +1087,19 @@ class FeishuChannel(BaseChannel):
else:
content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]"))
# Extract reply context (parent/root message IDs)
parent_id = getattr(message, "parent_id", None) or None
root_id = getattr(message, "root_id", None) or None
# Prepend quoted message text when the user replied to another message
if parent_id and self._client:
loop = asyncio.get_running_loop()
reply_ctx = await loop.run_in_executor(
None, self._get_message_content_sync, parent_id
)
if reply_ctx:
content_parts.insert(0, reply_ctx)
content = "\n".join(content_parts) if content_parts else ""
if not content and not media_paths:
@@ -991,6 +1116,8 @@ class FeishuChannel(BaseChannel):
"message_id": message_id,
"chat_type": chat_type,
"msg_type": msg_type,
"parent_id": parent_id,
"root_id": root_id,
}
)