refactor(channels): make built-in channels self-contained (#4908)

* refactor(channels): own setup and instance contracts

* refactor(channels): isolate management contracts

* refactor(channels): normalize activation contracts

* fix(channels): enforce management contracts

* refactor(channels): finish setup ownership migration

* fix(channels): harden management contracts

* fix(channels): enforce lazy loading and runtime ownership

* fix(feishu): make multi-instance startup idempotent

* fix(webui): render channel setup contracts cleanly

* fix(feishu): stop websocket clients cleanly

* fix(channels): enforce persistence and activation gates

* fix(channels): preserve global feature action scope

* fix(channels): apply defaults for single plugins

* fix(channels): enforce management contract boundaries

* refactor(feishu): remove identity helper indirection

* fix(channels): preserve management setup contracts

* refactor(channels): generalize instance settings UI

* refactor(channels): package channel plugins with web UI metadata

* refactor(channels): make built-ins self-contained packages

* test(channels): colocate tests with channel packages

* fix(dingtalk): use official brand icon

* feat(channels): colocate webui translations

* docs(channels): clarify plugin ownership

* test(exec): remove output wait race

* refactor(channels): unify plugin descriptors

* fix(channels): enforce descriptor-owned contracts

* refactor(channels): finish package-owned plugin setup

* refactor(channels): use repository-owned packages only

* fix(channels): self-describe dependencies and runtime state

* fix(channels): warn about legacy entry points
This commit is contained in:
chengyongru authored and GitHub committed 2026-07-19 23:30:49 +08:00
1 parent 7aaac37bca
commit 462a0dfb0f
388 files changed
+17093 -5110

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""DingTalk channel package."""
+24
View File
@@ -0,0 +1,24 @@
"""DingTalk management contract."""
from nanobot.channels._manifest import field, required_fields
from nanobot.channels.contracts import ChannelSetupSpec
from nanobot.channels.plugin import ChannelPlugin
SETUP_SPEC = ChannelSetupSpec(
fields={
"clientId": field(),
"clientSecret": field("secret"),
"allowFrom": field("list"),
},
required=required_fields("clientId", "clientSecret"),
official_url="https://open.dingtalk.com/",
)
PLUGIN = ChannelPlugin(
name="dingtalk",
display_name="DingTalk",
runtime=f"{__package__}.runtime:DingTalkChannel",
setup=SETUP_SPEC,
dependencies=("dingtalk-stream>=0.24.0,<1.0.0",),
webui="webui/index.ts",
)
+812
View File
@@ -0,0 +1,812 @@
"""DingTalk/DingDing channel implementation using Stream Mode."""
import asyncio
import json
import mimetypes
import os
import time
import zipfile
from contextlib import suppress
from inspect import isawaitable
from io import BytesIO
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urljoin, urlparse
import httpx
from pydantic import Field
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.schema import Base
from nanobot.security.network import validate_resolved_url, validate_url_target
DINGTALK_MAX_REMOTE_MEDIA_BYTES = 20 * 1024 * 1024
DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS = 3
try:
from dingtalk_stream import (
AckMessage,
CallbackHandler,
CallbackMessage,
Credential,
DingTalkStreamClient,
)
from dingtalk_stream.chatbot import ChatbotMessage
DINGTALK_AVAILABLE = True
except ImportError:
DINGTALK_AVAILABLE = False
# Fallback so class definitions don't crash at module level
CallbackHandler = object # type: ignore[assignment,misc]
CallbackMessage = None # type: ignore[assignment,misc]
AckMessage = None # type: ignore[assignment,misc]
ChatbotMessage = None # type: ignore[assignment,misc]
class NanobotDingTalkHandler(CallbackHandler):
"""
Standard DingTalk Stream SDK Callback Handler.
Parses incoming messages and forwards them to the Nanobot channel.
"""
def __init__(self, channel: "DingTalkChannel"):
super().__init__()
self.channel = channel
async def process(self, message: CallbackMessage):
"""Process incoming stream message."""
try:
# Parse using SDK's ChatbotMessage for robust handling
chatbot_msg = ChatbotMessage.from_dict(message.data)
# Extract text content; fall back to raw dict if SDK object is empty
content = ""
if chatbot_msg.text:
content = chatbot_msg.text.content.strip()
elif chatbot_msg.extensions.get("content", {}).get("recognition"):
content = chatbot_msg.extensions["content"]["recognition"].strip()
if not content:
content = message.data.get("text", {}).get("content", "").strip()
# Handle file/image messages
file_paths = []
if chatbot_msg.message_type == "picture" and chatbot_msg.image_content:
download_code = chatbot_msg.image_content.download_code
if download_code:
sender_uid = chatbot_msg.sender_staff_id or chatbot_msg.sender_id or "unknown"
fp = await self.channel._download_dingtalk_file(download_code, "image.jpg", sender_uid)
if fp:
file_paths.append(fp)
content = content or "[Image]"
elif chatbot_msg.message_type == "file":
download_code = message.data.get("content", {}).get("downloadCode") or message.data.get("downloadCode")
fname = message.data.get("content", {}).get("fileName") or message.data.get("fileName") or "file"
if download_code:
sender_uid = chatbot_msg.sender_staff_id or chatbot_msg.sender_id or "unknown"
fp = await self.channel._download_dingtalk_file(download_code, fname, sender_uid)
if fp:
file_paths.append(fp)
content = content or "[File]"
elif chatbot_msg.message_type == "richText" and chatbot_msg.rich_text_content:
rich_list = chatbot_msg.rich_text_content.rich_text_list or []
for item in rich_list:
if not isinstance(item, dict):
continue
# A rich-text item may carry text and/or a downloadCode; the
# DingTalk SDK treats them independently, so handle both.
t = item.get("text", "").strip()
if t:
fmt = item.get("type", "")
if fmt == "bold":
formatted = f"**{t}**"
elif fmt == "italic":
formatted = f"*{t}*"
elif fmt == "inlineCode":
formatted = f"`{t}`"
elif fmt == "pre":
formatted = f"```\n{t}\n```"
else:
formatted = t
content = (content + " " + formatted).strip() if content else formatted
if item.get("downloadCode"):
dc = item["downloadCode"]
fname = item.get("fileName") or "file"
sender_uid = chatbot_msg.sender_staff_id or chatbot_msg.sender_id or "unknown"
fp = await self.channel._download_dingtalk_file(dc, fname, sender_uid)
if fp:
file_paths.append(fp)
content = content or "[File]"
if file_paths:
file_list = "\n".join("- " + p for p in file_paths)
content = content + "\n\nReceived files:\n" + file_list
if not content:
self.channel.logger.warning(
"Received empty or unsupported message type: {}",
chatbot_msg.message_type,
)
return AckMessage.STATUS_OK, "OK"
sender_id = chatbot_msg.sender_staff_id or chatbot_msg.sender_id
sender_name = chatbot_msg.sender_nick or "Unknown"
conversation_type = message.data.get("conversationType")
conversation_id = (
message.data.get("conversationId")
or message.data.get("openConversationId")
)
self.channel.logger.info("Received message from {} ({}): {}", sender_name, sender_id, content)
# Forward to Nanobot via _on_message (non-blocking).
# Store reference to prevent GC before task completes.
task = asyncio.create_task(
self.channel._on_message(
content,
sender_id,
sender_name,
conversation_type,
conversation_id,
)
)
self.channel._background_tasks.add(task)
task.add_done_callback(self.channel._background_tasks.discard)
return AckMessage.STATUS_OK, "OK"
except Exception:
self.channel.logger.exception("Error processing message")
# Return OK to avoid retry loop from DingTalk server
return AckMessage.STATUS_OK, "Error"
class DingTalkConfig(Base):
"""DingTalk channel configuration using Stream mode."""
enabled: bool = False
client_id: str = ""
client_secret: str = ""
allow_from: list[str] = Field(default_factory=list)
allow_remote_media_redirects: bool = False
remote_media_redirect_allowed_hosts: list[str] = Field(default_factory=list)
group_user_isolation: bool = False # If True, each user in group chat gets their own session
class DingTalkChannel(BaseChannel):
"""
DingTalk channel using Stream Mode.
Uses WebSocket to receive events via `dingtalk-stream` SDK.
Uses direct HTTP API to send messages (SDK is mainly for receiving).
Supports both private (1:1) and group chats.
Group chat_id is stored with a "group:" prefix to route replies back.
"""
name = "dingtalk"
display_name = "DingTalk"
_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
_AUDIO_EXTS = {".amr", ".mp3", ".wav", ".ogg", ".m4a", ".aac"}
_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
_ZIP_BEFORE_UPLOAD_EXTS = {".htm", ".html"}
@classmethod
def default_config(cls) -> dict[str, Any]:
return DingTalkConfig().model_dump(by_alias=True)
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = DingTalkConfig.model_validate(config)
super().__init__(config, bus)
self.config: DingTalkConfig = config
self._client: Any = None
self._http: httpx.AsyncClient | None = None
self._start_task: asyncio.Task | None = None
# Access Token management for sending messages
self._access_token: str | None = None
self._token_expiry: float = 0
# Hold references to background tasks to prevent GC
self._background_tasks: set[asyncio.Task] = set()
async def start(self) -> None:
"""Start the DingTalk bot with Stream Mode."""
current_task = asyncio.current_task()
self._start_task = current_task
try:
if not DINGTALK_AVAILABLE:
self.logger.error(
"Stream SDK not installed. Run: nanobot plugins enable dingtalk"
)
return
if not self.config.client_id or not self.config.client_secret:
self.logger.error("client_id and client_secret not configured")
return
self._running = True
self._http = httpx.AsyncClient(
timeout=httpx.Timeout(10.0, connect=10.0, read=30.0, write=30.0, pool=10.0)
)
self.logger.info(
"Initializing Stream Client with Client ID: {}...",
self.config.client_id,
)
credential = Credential(self.config.client_id, self.config.client_secret)
self._client = DingTalkStreamClient(credential)
# Register standard handler
handler = NanobotDingTalkHandler(self)
self._client.register_callback_handler(ChatbotMessage.TOPIC, handler)
self.logger.info("bot started with Stream Mode")
# Reconnect loop: restart stream if SDK exits or crashes
while self._running:
try:
await self._client.start()
except Exception as e:
self.logger.warning("stream error: {}", e)
if self._running:
self.logger.info("Reconnecting stream in 5 seconds...")
await asyncio.sleep(5)
except Exception:
self.logger.exception("Failed to start channel")
finally:
self._running = False
if self._start_task is current_task:
self._start_task = None
async def stop(self) -> None:
"""Stop the DingTalk bot."""
self._running = False
await self._close_stream_client()
start_task = self._start_task
if start_task and start_task is not asyncio.current_task() and not start_task.done():
start_task.cancel()
await asyncio.sleep(0)
if not start_task.done():
start_task.cancel()
with suppress(asyncio.CancelledError):
await start_task
self._client = None
# Close the shared HTTP client
if self._http:
await self._http.aclose()
self._http = None
# Cancel outstanding background tasks
for task in self._background_tasks:
task.cancel()
self._background_tasks.clear()
async def _close_stream_client(self) -> None:
client = self._client
if client is None:
return
close = getattr(client, "close", None)
if close is None:
websocket = getattr(client, "websocket", None)
close = getattr(websocket, "close", None)
if close is None:
return
try:
result = close()
if isawaitable(result):
await result
except Exception:
self.logger.debug("DingTalk stream client close failed", exc_info=True)
async def _get_access_token(self) -> str | None:
"""Get or refresh Access Token."""
if self._access_token and time.time() < self._token_expiry:
return self._access_token
url = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
data = {
"appKey": self.config.client_id,
"appSecret": self.config.client_secret,
}
if not self._http:
self.logger.warning("HTTP client not initialized, cannot refresh token")
return None
try:
resp = await self._http.post(url, json=data)
resp.raise_for_status()
res_data = resp.json()
self._access_token = res_data.get("accessToken")
# Expire 60s early to be safe
self._token_expiry = time.time() + int(res_data.get("expireIn", 7200)) - 60
return self._access_token
except Exception:
self.logger.exception("Failed to get access token")
return None
@staticmethod
def _is_http_url(value: str) -> bool:
return urlparse(value).scheme in ("http", "https")
def _guess_upload_type(self, media_ref: str) -> str:
ext = Path(urlparse(media_ref).path).suffix.lower()
if ext in self._IMAGE_EXTS:
return "image"
if ext in self._AUDIO_EXTS:
return "voice"
if ext in self._VIDEO_EXTS:
return "video"
return "file"
def _guess_filename(self, media_ref: str, upload_type: str) -> str:
name = os.path.basename(urlparse(media_ref).path)
return name or {"image": "image.jpg", "voice": "audio.amr", "video": "video.mp4"}.get(upload_type, "file.bin")
@staticmethod
def _zip_bytes(filename: str, data: bytes) -> tuple[bytes, str, str]:
stem = Path(filename).stem or "attachment"
safe_name = filename or "attachment.bin"
zip_name = f"{stem}.zip"
buffer = BytesIO()
with zipfile.ZipFile(buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as archive:
archive.writestr(safe_name, data)
return buffer.getvalue(), zip_name, "application/zip"
def _normalize_upload_payload(
self,
filename: str,
data: bytes,
content_type: str | None,
) -> tuple[bytes, str, str | None]:
ext = Path(filename).suffix.lower()
if ext in self._ZIP_BEFORE_UPLOAD_EXTS or content_type == "text/html":
self.logger.info(
"does not accept raw HTML attachments, zipping {} before upload",
filename,
)
return self._zip_bytes(filename, data)
return data, filename, content_type
def _validate_remote_media_url(self, media_ref: str) -> bool:
ok, err = validate_url_target(media_ref)
if not ok:
self.logger.warning("remote media URL blocked ref={} reason={}", media_ref, err)
return False
return True
def _redirect_host_allowed(self, current_url: str, next_url: str) -> bool:
current_host = (urlparse(current_url).hostname or "").lower()
next_host = (urlparse(next_url).hostname or "").lower()
if not next_host:
return False
if next_host == current_host:
return True
allowed_hosts = {host.lower() for host in self.config.remote_media_redirect_allowed_hosts}
return next_host in allowed_hosts
def _next_remote_media_url(self, current_url: str, location: str | None) -> str | None:
if not self.config.allow_remote_media_redirects:
self.logger.warning("media download redirect refused ref={}", current_url)
return None
if not location:
self.logger.warning("media download redirect without Location ref={}", current_url)
return None
next_url = urljoin(current_url, location)
if not self._redirect_host_allowed(current_url, next_url):
self.logger.warning(
"media download cross-host redirect refused ref={} next={}",
current_url,
next_url,
)
return None
if not self._validate_remote_media_url(next_url):
return None
return next_url
async def _fetch_remote_media_bytes(
self,
media_ref: str,
) -> tuple[bytes | None, str | None]:
"""Fetch a remote media URL with SSRF, redirect, and size checks."""
if not self._http:
return None, None
if not self._validate_remote_media_url(media_ref):
return None, None
try:
# Prefer streaming with a running byte cap so large responses are not
# materialized before the limit is enforced. Test fakes may only
# implement get(), so keep a small compatibility fallback below.
stream = getattr(self._http, "stream", None)
if stream is not None:
current_url = media_ref
for _ in range(DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS + 1):
async with stream("GET", current_url, follow_redirects=False) as resp:
final_ok, final_err = validate_resolved_url(str(resp.url))
if not final_ok:
self.logger.warning(
"remote media redirect blocked ref={} final={} reason={}",
media_ref,
resp.url,
final_err,
)
return None, None
if 300 <= resp.status_code < 400:
next_url = self._next_remote_media_url(
str(resp.url), resp.headers.get("location")
)
if not next_url:
return None, None
current_url = next_url
continue
if resp.status_code >= 400:
self.logger.warning(
"media download failed status={} ref={}",
resp.status_code,
current_url,
)
return None, None
chunks: list[bytes] = []
total = 0
async for chunk in resp.aiter_bytes():
total += len(chunk)
if total > DINGTALK_MAX_REMOTE_MEDIA_BYTES:
self.logger.warning(
"media download too large ref={} bytes>{}",
current_url,
DINGTALK_MAX_REMOTE_MEDIA_BYTES,
)
return None, None
chunks.append(chunk)
return b"".join(chunks), (resp.headers.get("content-type") or "")
self.logger.warning("media download exceeded redirect limit ref={}", media_ref)
return None, None
current_url = media_ref
for _ in range(DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS + 1):
resp = await self._http.get(current_url, follow_redirects=False)
final_ok, final_err = validate_resolved_url(str(getattr(resp, "url", current_url)))
if not final_ok:
self.logger.warning(
"remote media redirect blocked ref={} final={} reason={}",
media_ref,
getattr(resp, "url", current_url),
final_err,
)
return None, None
if 300 <= resp.status_code < 400:
next_url = self._next_remote_media_url(
str(getattr(resp, "url", current_url)), resp.headers.get("location")
)
if not next_url:
return None, None
current_url = next_url
continue
if resp.status_code >= 400:
self.logger.warning(
"media download failed status={} ref={}",
resp.status_code,
current_url,
)
return None, None
if len(resp.content) > DINGTALK_MAX_REMOTE_MEDIA_BYTES:
self.logger.warning(
"media download too large ref={} bytes>{}",
current_url,
DINGTALK_MAX_REMOTE_MEDIA_BYTES,
)
return None, None
return resp.content, (resp.headers.get("content-type") or "")
self.logger.warning("media download exceeded redirect limit ref={}", media_ref)
return None, None
except httpx.TransportError:
self.logger.exception("media download network error ref={}", media_ref)
raise
except Exception:
self.logger.exception("media download error ref={}", media_ref)
return None, None
async def _read_media_bytes(
self,
media_ref: str,
) -> tuple[bytes | None, str | None, str | None]:
if not media_ref:
return None, None, None
if self._is_http_url(media_ref):
data, raw_content_type = await self._fetch_remote_media_bytes(media_ref)
if data is None:
return None, None, None
content_type = (raw_content_type or "").split(";")[0].strip()
filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))
return data, filename, content_type or None
try:
if media_ref.startswith("file://"):
parsed = urlparse(media_ref)
local_path = Path(unquote(parsed.path))
else:
local_path = Path(os.path.expanduser(media_ref))
if not local_path.is_file():
self.logger.warning("media file not found: {}", local_path)
return None, None, None
data = await asyncio.to_thread(local_path.read_bytes)
content_type = mimetypes.guess_type(local_path.name)[0]
return data, local_path.name, content_type
except Exception:
self.logger.exception("media read error ref={}", media_ref)
return None, None, None
async def _upload_media(
self,
token: str,
data: bytes,
media_type: str,
filename: str,
content_type: str | None,
) -> str | None:
if not self._http:
return None
url = f"https://oapi.dingtalk.com/media/upload?access_token={token}&type={media_type}"
mime = content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
files = {"media": (filename, data, mime)}
try:
resp = await self._http.post(url, files=files)
text = resp.text
result = resp.json() if resp.headers.get("content-type", "").startswith("application/json") else {}
if resp.status_code >= 400:
self.logger.error("media upload failed status={} type={} body={}", resp.status_code, media_type, text[:500])
return None
errcode = result.get("errcode", 0)
if errcode != 0:
self.logger.error("media upload api error type={} errcode={} body={}", media_type, errcode, text[:500])
return None
sub = result.get("result") or {}
media_id = result.get("media_id") or result.get("mediaId") or sub.get("media_id") or sub.get("mediaId")
if not media_id:
self.logger.error("media upload missing media_id body={}", text[:500])
return None
return str(media_id)
except httpx.TransportError:
self.logger.exception("media upload network error type={}", media_type)
raise
except Exception:
self.logger.exception("media upload error type={}", media_type)
return None
async def _send_batch_message(
self,
token: str,
chat_id: str,
msg_key: str,
msg_param: dict[str, Any],
) -> bool:
if not self._http:
self.logger.warning("HTTP client not initialized, cannot send")
return False
headers = {"x-acs-dingtalk-access-token": token}
if chat_id.startswith("group:"):
# Group chat
url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
payload = {
"robotCode": self.config.client_id,
"openConversationId": chat_id[6:], # Remove "group:" prefix,
"msgKey": msg_key,
"msgParam": json.dumps(msg_param, ensure_ascii=False),
}
else:
# Private chat
url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
payload = {
"robotCode": self.config.client_id,
"userIds": [chat_id],
"msgKey": msg_key,
"msgParam": json.dumps(msg_param, ensure_ascii=False),
}
try:
resp = await self._http.post(url, json=payload, headers=headers)
body = resp.text
if resp.status_code != 200:
self.logger.error("send failed msgKey={} status={} body={}", msg_key, resp.status_code, body[:500])
return False
try:
result = resp.json()
except Exception:
result = {}
errcode = result.get("errcode")
if errcode not in (None, 0):
self.logger.error("send api error msgKey={} errcode={} body={}", msg_key, errcode, body[:500])
return False
self.logger.debug("message sent to {} with msgKey={}", chat_id, msg_key)
return True
except httpx.TransportError:
self.logger.exception("network error sending message msgKey={}", msg_key)
raise
except Exception:
self.logger.exception("Error sending message msgKey={}", msg_key)
return False
async def _send_markdown_text(self, token: str, chat_id: str, content: str) -> bool:
return await self._send_batch_message(
token,
chat_id,
"sampleMarkdown",
{"text": content, "title": "Nanobot Reply"},
)
async def _send_media_ref(self, token: str, chat_id: str, media_ref: str) -> bool:
media_ref = (media_ref or "").strip()
if not media_ref:
return True
upload_type = self._guess_upload_type(media_ref)
if upload_type == "image" and self._is_http_url(media_ref):
ok = await self._send_batch_message(
token,
chat_id,
"sampleImageMsg",
{"photoURL": media_ref},
)
if ok:
return True
self.logger.warning("image url send failed, trying upload fallback: {}", media_ref)
data, filename, content_type = await self._read_media_bytes(media_ref)
if not data:
self.logger.error("media read failed: {}", media_ref)
return False
filename = filename or self._guess_filename(media_ref, upload_type)
data, filename, content_type = self._normalize_upload_payload(filename, data, content_type)
file_type = Path(filename).suffix.lower().lstrip(".")
if not file_type:
guessed = mimetypes.guess_extension(content_type or "")
file_type = (guessed or ".bin").lstrip(".")
if file_type == "jpeg":
file_type = "jpg"
media_id = await self._upload_media(
token=token,
data=data,
media_type=upload_type,
filename=filename,
content_type=content_type,
)
if not media_id:
return False
if upload_type == "image":
# Verified in production: sampleImageMsg accepts media_id in photoURL.
ok = await self._send_batch_message(
token,
chat_id,
"sampleImageMsg",
{"photoURL": media_id},
)
if ok:
return True
self.logger.warning("image media_id send failed, falling back to file: {}", media_ref)
return await self._send_batch_message(
token,
chat_id,
"sampleFile",
{"mediaId": media_id, "fileName": filename, "fileType": file_type},
)
async def send(self, msg: OutboundMessage) -> None:
"""Send a message through DingTalk."""
token = await self._get_access_token()
if not token:
raise RuntimeError("DingTalk access token unavailable")
if msg.content and msg.content.strip():
if not await self._send_markdown_text(token, msg.chat_id, msg.content.strip()):
raise RuntimeError("DingTalk text message was not delivered")
for media_ref in msg.media or []:
ok = await self._send_media_ref(token, msg.chat_id, media_ref)
if ok:
continue
self.logger.error("media send failed for {}", media_ref)
# Send visible fallback so failures are observable by the user.
filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))
if not await self._send_markdown_text(
token,
msg.chat_id,
f"[Attachment send failed: {filename}]",
):
raise RuntimeError("DingTalk attachment fallback was not delivered")
async def _on_message(
self,
content: str,
sender_id: str,
sender_name: str,
conversation_type: str | None = None,
conversation_id: str | None = None,
) -> None:
"""Handle incoming message (called by NanobotDingTalkHandler).
Delegates to BaseChannel._handle_message() which enforces allow_from
permission checks before publishing to the bus.
"""
try:
self.logger.info("inbound: {} from {}", content, sender_name)
is_group = conversation_type == "2" and conversation_id
chat_id = f"group:{conversation_id}" if is_group else sender_id
session_key = None
if is_group and self.config.group_user_isolation:
session_key = f"{self.name}:group:{conversation_id}:{sender_id}"
await self._handle_message(
sender_id=sender_id,
chat_id=chat_id,
content=str(content),
metadata={
"sender_name": sender_name,
"platform": "dingtalk",
"conversation_type": conversation_type,
},
session_key=session_key,
)
except Exception:
self.logger.exception("Error publishing message")
async def _download_dingtalk_file(
self,
download_code: str,
filename: str,
sender_id: str,
) -> str | None:
"""Download a DingTalk file to the media directory, return local path."""
from nanobot.config.paths import get_media_dir
try:
token = await self._get_access_token()
if not token or not self._http:
self.logger.error("file download: no token or http client")
return None
# Step 1: Exchange downloadCode for a temporary download URL
api_url = "https://api.dingtalk.com/v1.0/robot/messageFiles/download"
headers = {"x-acs-dingtalk-access-token": token, "Content-Type": "application/json"}
payload = {"downloadCode": download_code, "robotCode": self.config.client_id}
resp = await self._http.post(api_url, json=payload, headers=headers)
if resp.status_code != 200:
self.logger.error("get download URL failed: status={}, body={}", resp.status_code, resp.text)
return None
result = resp.json()
download_url = result.get("downloadUrl")
if not download_url:
self.logger.error("download URL not found in response: {}", result)
return None
# Step 2: Download the file content
file_resp = await self._http.get(download_url, follow_redirects=True)
if file_resp.status_code != 200:
self.logger.error("file download failed: status={}", file_resp.status_code)
return None
# Save to media directory (accessible under workspace)
download_dir = get_media_dir("dingtalk") / sender_id
download_dir.mkdir(parents=True, exist_ok=True)
file_path = download_dir / filename
await asyncio.to_thread(file_path.write_bytes, file_resp.content)
self.logger.info("file saved: {}", file_path)
return str(file_path)
except Exception:
self.logger.exception("file download error")
return None
@@ -0,0 +1 @@
"""Tests for the DingTalk channel package."""
@@ -0,0 +1,986 @@
import asyncio
import zipfile
from io import BytesIO
from types import SimpleNamespace
from unittest.mock import AsyncMock
import httpx
import pytest
# Check optional dingtalk dependencies before running tests
try:
from nanobot.channels import dingtalk
DINGTALK_AVAILABLE = getattr(dingtalk, "DINGTALK_AVAILABLE", False)
except ImportError:
DINGTALK_AVAILABLE = False
if not DINGTALK_AVAILABLE:
pytest.skip("DingTalk dependencies not installed (dingtalk-stream)", allow_module_level=True)
import nanobot.channels.dingtalk.runtime as dingtalk_module
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.dingtalk.runtime import (
DingTalkChannel,
DingTalkConfig,
NanobotDingTalkHandler,
)
class _FakeResponse:
def __init__(
self,
status_code: int = 200,
json_body: dict | None = None,
*,
content: bytes = b"",
headers: dict[str, str] | None = None,
url: str = "https://example.com/file",
) -> None:
self.status_code = status_code
self._json_body = json_body or {}
self.text = content.decode("utf-8", errors="replace") if content else "{}"
self.content = content
self.headers = headers or {"content-type": "application/json"}
self.url = httpx.URL(url)
def json(self) -> dict:
return self._json_body
class _FakeHttp:
def __init__(self, responses: list[_FakeResponse] | None = None) -> None:
self.calls: list[dict] = []
self._responses = list(responses) if responses else []
def _next_response(self) -> _FakeResponse:
if self._responses:
return self._responses.pop(0)
return _FakeResponse()
async def post(self, url: str, json=None, headers=None, **kwargs):
self.calls.append(
{"method": "POST", "url": url, "json": json, "headers": headers, "kwargs": kwargs}
)
return self._next_response()
async def get(self, url: str, **kwargs):
self.calls.append({"method": "GET", "url": url, "kwargs": kwargs})
return self._next_response()
class _NetworkErrorHttp:
"""HTTP client stub that raises httpx.TransportError on every request."""
def __init__(self) -> None:
self.calls: list[dict] = []
async def post(self, url: str, json=None, headers=None, **kwargs):
self.calls.append({"method": "POST", "url": url, "json": json, "headers": headers})
raise httpx.ConnectError("Connection refused")
async def get(self, url: str, **kwargs):
self.calls.append({"method": "GET", "url": url})
raise httpx.ConnectError("Connection refused")
@pytest.mark.asyncio
async def test_group_message_keeps_sender_id_and_routes_chat_id() -> None:
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"])
bus = MessageBus()
channel = DingTalkChannel(config, bus)
await channel._on_message(
"hello",
sender_id="user1",
sender_name="Alice",
conversation_type="2",
conversation_id="conv123",
)
msg = await bus.consume_inbound()
assert msg.sender_id == "user1"
assert msg.chat_id == "group:conv123"
assert msg.metadata["conversation_type"] == "2"
@pytest.mark.asyncio
async def test_group_user_isolation_false_uses_shared_session() -> None:
"""By default group messages share the same session_key."""
config = DingTalkConfig(
client_id="app", client_secret="secret", allow_from=["*"], group_user_isolation=False
)
bus = MessageBus()
channel = DingTalkChannel(config, bus)
for user_id in ("user1", "user2"):
await channel._on_message(
"hello",
sender_id=user_id,
sender_name=user_id,
conversation_type="2",
conversation_id="conv123",
)
msg1 = await bus.consume_inbound()
msg2 = await bus.consume_inbound()
assert msg1.session_key == msg2.session_key == "dingtalk:group:conv123"
assert msg1.chat_id == msg2.chat_id == "group:conv123"
@pytest.mark.asyncio
async def test_group_user_isolation_true_separates_sessions() -> None:
"""When group_user_isolation is True, each user gets their own session_key."""
config = DingTalkConfig(
client_id="app", client_secret="secret", allow_from=["*"], group_user_isolation=True
)
bus = MessageBus()
channel = DingTalkChannel(config, bus)
for user_id in ("user1", "user2"):
await channel._on_message(
"hello",
sender_id=user_id,
sender_name=user_id,
conversation_type="2",
conversation_id="conv123",
)
msg1 = await bus.consume_inbound()
msg2 = await bus.consume_inbound()
assert msg1.session_key == "dingtalk:group:conv123:user1"
assert msg2.session_key == "dingtalk:group:conv123:user2"
assert msg1.chat_id == msg2.chat_id == "group:conv123"
@pytest.mark.asyncio
async def test_group_send_uses_group_messages_api() -> None:
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
channel = DingTalkChannel(config, MessageBus())
channel._http = _FakeHttp()
ok = await channel._send_batch_message(
"token",
"group:conv123",
"sampleMarkdown",
{"text": "hello", "title": "Nanobot Reply"},
)
assert ok is True
call = channel._http.calls[0]
assert call["url"] == "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
assert call["json"]["openConversationId"] == "conv123"
assert call["json"]["msgKey"] == "sampleMarkdown"
@pytest.mark.asyncio
async def test_handler_uses_voice_recognition_text_when_text_is_empty(monkeypatch) -> None:
bus = MessageBus()
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
bus,
)
handler = NanobotDingTalkHandler(channel)
class _FakeChatbotMessage:
text = None
extensions = {"content": {"recognition": "voice transcript"}}
sender_staff_id = "user1"
sender_id = "fallback-user"
sender_nick = "Alice"
message_type = "audio"
@staticmethod
def from_dict(_data):
return _FakeChatbotMessage()
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", _FakeChatbotMessage)
monkeypatch.setattr(dingtalk_module, "AckMessage", SimpleNamespace(STATUS_OK="OK"))
status, body = await handler.process(
SimpleNamespace(
data={
"conversationType": "2",
"conversationId": "conv123",
"text": {"content": ""},
}
)
)
await asyncio.gather(*list(channel._background_tasks))
msg = await bus.consume_inbound()
assert (status, body) == ("OK", "OK")
assert msg.content == "voice transcript"
assert msg.sender_id == "user1"
assert msg.chat_id == "group:conv123"
@pytest.mark.asyncio
async def test_handler_processes_file_message(monkeypatch) -> None:
"""Test that file messages are handled and forwarded with downloaded path."""
bus = MessageBus()
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
bus,
)
handler = NanobotDingTalkHandler(channel)
class _FakeFileChatbotMessage:
text = None
extensions = {}
image_content = None
rich_text_content = None
sender_staff_id = "user1"
sender_id = "fallback-user"
sender_nick = "Alice"
message_type = "file"
@staticmethod
def from_dict(_data):
return _FakeFileChatbotMessage()
async def fake_download(download_code, filename, sender_id):
return f"/tmp/nanobot_dingtalk/{sender_id}/{filename}"
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", _FakeFileChatbotMessage)
monkeypatch.setattr(dingtalk_module, "AckMessage", SimpleNamespace(STATUS_OK="OK"))
monkeypatch.setattr(channel, "_download_dingtalk_file", fake_download)
status, body = await handler.process(
SimpleNamespace(
data={
"conversationType": "1",
"content": {"downloadCode": "abc123", "fileName": "report.xlsx"},
"text": {"content": ""},
}
)
)
await asyncio.gather(*list(channel._background_tasks))
msg = await bus.consume_inbound()
assert (status, body) == ("OK", "OK")
assert "[File]" in msg.content
assert "/tmp/nanobot_dingtalk/user1/report.xlsx" in msg.content
def _rich_text_message(rich_text_list):
class _FakeRichTextChatbotMessage:
text = None
extensions = {}
image_content = None
rich_text_content = SimpleNamespace(rich_text_list=rich_text_list)
sender_staff_id = "user1"
sender_id = "fallback-user"
sender_nick = "Alice"
message_type = "richText"
@staticmethod
def from_dict(_data):
return _FakeRichTextChatbotMessage()
return _FakeRichTextChatbotMessage
@pytest.mark.asyncio
async def test_handler_richtext_keeps_formatted_segments(monkeypatch) -> None:
"""richText segments with non-'text' types (bold/italic/code/pre) must be kept
and mapped to Markdown, not dropped (issue #4497)."""
bus = MessageBus()
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
bus,
)
handler = NanobotDingTalkHandler(channel)
fake_msg = _rich_text_message([
{"type": "bold", "text": "Title"},
{"type": "text", "text": "plain"},
{"type": "italic", "text": "em"},
{"type": "inlineCode", "text": "x = 1"},
{"type": "pre", "text": "block"},
])
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", fake_msg)
monkeypatch.setattr(dingtalk_module, "AckMessage", SimpleNamespace(STATUS_OK="OK"))
status, body = await handler.process(
SimpleNamespace(data={"conversationType": "1", "text": {"content": ""}})
)
msg = await asyncio.wait_for(bus.consume_inbound(), timeout=2.0)
assert (status, body) == ("OK", "OK")
assert msg.content == "**Title** plain *em* `x = 1` ```\nblock\n```"
@pytest.mark.asyncio
async def test_handler_richtext_all_formatted_not_dropped(monkeypatch) -> None:
"""A richText message made only of formatted segments must not end up with empty
content and fall through to the 'unsupported message type' path (issue #4497)."""
bus = MessageBus()
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
bus,
)
handler = NanobotDingTalkHandler(channel)
fake_msg = _rich_text_message([{"type": "bold", "text": "Important"}])
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", fake_msg)
monkeypatch.setattr(dingtalk_module, "AckMessage", SimpleNamespace(STATUS_OK="OK"))
status, body = await handler.process(
SimpleNamespace(data={"conversationType": "1", "text": {"content": ""}})
)
# Before the fix this message produced empty content and never reached the bus,
# so consume_inbound would block here.
msg = await asyncio.wait_for(bus.consume_inbound(), timeout=2.0)
assert (status, body) == ("OK", "OK")
assert msg.content == "**Important**"
@pytest.mark.asyncio
async def test_handler_richtext_item_with_text_and_download(monkeypatch) -> None:
"""A rich-text item carrying both text and a downloadCode must yield both the
text and the downloaded file, not drop the attachment (issue #4497)."""
bus = MessageBus()
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["user1"]),
bus,
)
handler = NanobotDingTalkHandler(channel)
fake_msg = _rich_text_message([
{"text": "see attached", "downloadCode": "abc123", "fileName": "report.xlsx"},
])
async def fake_download(download_code, filename, sender_id):
return f"/tmp/nanobot_dingtalk/{sender_id}/{filename}"
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", fake_msg)
monkeypatch.setattr(dingtalk_module, "AckMessage", SimpleNamespace(STATUS_OK="OK"))
monkeypatch.setattr(channel, "_download_dingtalk_file", fake_download)
status, body = await handler.process(
SimpleNamespace(data={"conversationType": "1", "text": {"content": ""}})
)
await asyncio.gather(*list(channel._background_tasks))
msg = await asyncio.wait_for(bus.consume_inbound(), timeout=2.0)
assert (status, body) == ("OK", "OK")
assert "see attached" in msg.content
assert "/tmp/nanobot_dingtalk/user1/report.xlsx" in msg.content
@pytest.mark.asyncio
async def test_start_configures_http_timeout(monkeypatch) -> None:
"""The shared httpx client must be created with an explicit timeout so file/image
downloads don't hit httpx's 5s default and ConnectTimeout (issue #4497)."""
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
class _FakeStreamClient:
def __init__(self, _credential):
pass
def register_callback_handler(self, _topic, _handler):
pass
async def start(self):
# Exit the reconnect loop after one iteration.
channel._running = False
monkeypatch.setattr(dingtalk_module, "DINGTALK_AVAILABLE", True)
monkeypatch.setattr(dingtalk_module, "Credential", lambda *a, **k: object())
monkeypatch.setattr(dingtalk_module, "DingTalkStreamClient", _FakeStreamClient)
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", SimpleNamespace(TOPIC="topic"))
await channel.start()
assert channel._http is not None
timeout = channel._http.timeout
assert timeout.connect == 10.0
assert timeout.read == 30.0
assert timeout.write == 30.0
assert timeout.pool == 10.0
await channel.stop()
@pytest.mark.asyncio
async def test_stop_cancels_stream_client_after_sdk_swallows_first_cancel(monkeypatch) -> None:
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
created: dict[str, object] = {}
class _FakeWebsocket:
def __init__(self) -> None:
self.closed = False
async def close(self) -> None:
self.closed = True
class _CancelSwallowingStreamClient:
def __init__(self, _credential):
self.websocket = _FakeWebsocket()
self.started = asyncio.Event()
self.cancelled_once = asyncio.Event()
created["client"] = self
def register_callback_handler(self, _topic, _handler):
pass
async def start(self):
self.started.set()
while True:
try:
await asyncio.Future()
except asyncio.CancelledError:
self.cancelled_once.set()
await asyncio.sleep(3600)
monkeypatch.setattr(dingtalk_module, "DINGTALK_AVAILABLE", True)
monkeypatch.setattr(dingtalk_module, "Credential", lambda *a, **k: object())
monkeypatch.setattr(dingtalk_module, "DingTalkStreamClient", _CancelSwallowingStreamClient)
monkeypatch.setattr(dingtalk_module, "ChatbotMessage", SimpleNamespace(TOPIC="topic"))
start_task = asyncio.create_task(channel.start())
while "client" not in created:
await asyncio.sleep(0)
client = created["client"]
await asyncio.wait_for(client.started.wait(), timeout=0.5)
start_task.cancel()
await asyncio.wait_for(client.cancelled_once.wait(), timeout=0.5)
assert not start_task.done()
await asyncio.wait_for(channel.stop(), timeout=0.5)
assert client.websocket.closed is True
assert start_task.cancelled()
@pytest.mark.asyncio
async def test_download_dingtalk_file(tmp_path, monkeypatch) -> None:
"""Test the two-step file download flow (get URL then download content)."""
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
# Mock access token
async def fake_get_token():
return "test-token"
monkeypatch.setattr(channel, "_get_access_token", fake_get_token)
# Mock HTTP: first POST returns downloadUrl, then GET returns file bytes
file_content = b"fake file content"
channel._http = _FakeHttp(responses=[
_FakeResponse(200, {"downloadUrl": "https://example.com/tmpfile"}),
_FakeResponse(200),
])
channel._http._responses[1].content = file_content
# Redirect media dir to tmp_path
monkeypatch.setattr(
"nanobot.config.paths.get_media_dir",
lambda channel_name=None: tmp_path / channel_name if channel_name else tmp_path,
)
result = await channel._download_dingtalk_file("code123", "test.xlsx", "user1")
assert result is not None
assert result.endswith("test.xlsx")
assert (tmp_path / "dingtalk" / "user1" / "test.xlsx").read_bytes() == file_content
# Verify API calls
assert channel._http.calls[0]["method"] == "POST"
assert "messageFiles/download" in channel._http.calls[0]["url"]
assert channel._http.calls[0]["json"]["downloadCode"] == "code123"
assert channel._http.calls[1]["method"] == "GET"
@pytest.mark.asyncio
async def test_read_media_bytes_rejects_private_http_target_before_fetch() -> None:
"""Remote media fetches must not reach loopback/private addresses."""
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
200,
content=b"internal secret",
headers={"content-type": "text/plain"},
url="http://127.0.0.1/admin.txt",
)
]
)
data, filename, content_type = await channel._read_media_bytes("http://127.0.0.1/admin.txt")
assert (data, filename, content_type) == (None, None, None)
assert channel._http.calls == []
@pytest.mark.asyncio
async def test_read_media_bytes_rejects_private_redirect_result() -> None:
"""A public-looking media URL must not be accepted after redirecting private."""
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
200,
content=b"metadata bytes",
headers={"content-type": "text/plain"},
url="http://127.0.0.1/metadata",
)
]
)
data, filename, content_type = await channel._read_media_bytes("https://example.com/safe.txt")
assert (data, filename, content_type) == (None, None, None)
assert len(channel._http.calls) == 1
@pytest.mark.asyncio
async def test_read_media_bytes_rejects_oversized_remote_response(monkeypatch) -> None:
"""DingTalk media downloads should enforce a byte cap before upload."""
monkeypatch.setattr(dingtalk_module, "DINGTALK_MAX_REMOTE_MEDIA_BYTES", 8, raising=False)
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
200,
content=b"123456789",
headers={"content-type": "text/plain"},
url="https://example.com/large.txt",
)
]
)
data, filename, content_type = await channel._read_media_bytes("https://example.com/large.txt")
assert (data, filename, content_type) == (None, None, None)
@pytest.mark.asyncio
async def test_read_media_bytes_does_not_follow_remote_redirects_by_default() -> None:
"""Redirects are refused by default instead of followed into internal networks."""
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
302,
headers={"location": "http://127.0.0.1/metadata"},
url="https://example.com/redirect.txt",
)
]
)
data, filename, content_type = await channel._read_media_bytes("https://example.com/redirect.txt")
assert (data, filename, content_type) == (None, None, None)
assert channel._http.calls[0]["kwargs"]["follow_redirects"] is False
@pytest.mark.asyncio
async def test_read_media_bytes_follows_safe_redirect_when_explicitly_enabled() -> None:
"""Operators can opt in to public redirects without enabling private redirects."""
channel = DingTalkChannel(
DingTalkConfig(
client_id="app",
client_secret="secret",
allow_from=["*"],
allow_remote_media_redirects=True,
),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
302,
headers={"location": "https://example.com/final.txt"},
url="https://example.com/redirect.txt",
),
_FakeResponse(
200,
content=b"redirected media",
headers={"content-type": "text/plain"},
url="https://example.com/final.txt",
),
]
)
data, filename, content_type = await channel._read_media_bytes("https://example.com/redirect.txt")
assert (data, filename, content_type) == (b"redirected media", "redirect.txt", "text/plain")
assert [call["url"] for call in channel._http.calls] == [
"https://example.com/redirect.txt",
"https://example.com/final.txt",
]
assert all(call["kwargs"]["follow_redirects"] is False for call in channel._http.calls)
@pytest.mark.asyncio
async def test_read_media_bytes_blocks_cross_host_redirect_without_allowlist() -> None:
"""Redirect opt-in should not allow arbitrary cross-host redirects by default."""
channel = DingTalkChannel(
DingTalkConfig(
client_id="app",
client_secret="secret",
allow_from=["*"],
allow_remote_media_redirects=True,
),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
302,
headers={"location": "https://example.org/final.txt"},
url="https://example.com/redirect.txt",
),
_FakeResponse(
200,
content=b"cross-host media",
headers={"content-type": "text/plain"},
url="https://example.org/final.txt",
),
]
)
data, filename, content_type = await channel._read_media_bytes("https://example.com/redirect.txt")
assert (data, filename, content_type) == (None, None, None)
assert [call["url"] for call in channel._http.calls] == ["https://example.com/redirect.txt"]
@pytest.mark.asyncio
async def test_read_media_bytes_allows_cross_host_redirect_when_allowlisted() -> None:
"""Operators can explicitly allow a known CDN/download host for redirects."""
channel = DingTalkChannel(
DingTalkConfig(
client_id="app",
client_secret="secret",
allow_from=["*"],
allow_remote_media_redirects=True,
remote_media_redirect_allowed_hosts=["example.org"],
),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
302,
headers={"location": "https://example.org/final.txt"},
url="https://example.com/redirect.txt",
),
_FakeResponse(
200,
content=b"cross-host media",
headers={"content-type": "text/plain"},
url="https://example.org/final.txt",
),
]
)
data, filename, content_type = await channel._read_media_bytes("https://example.com/redirect.txt")
assert (data, filename, content_type) == (b"cross-host media", "redirect.txt", "text/plain")
assert [call["url"] for call in channel._http.calls] == [
"https://example.com/redirect.txt",
"https://example.org/final.txt",
]
@pytest.mark.asyncio
async def test_read_media_bytes_blocks_private_redirect_even_when_redirects_enabled() -> None:
"""Redirect opt-in must still validate each hop before fetching it."""
channel = DingTalkChannel(
DingTalkConfig(
client_id="app",
client_secret="secret",
allow_from=["*"],
allow_remote_media_redirects=True,
),
MessageBus(),
)
channel._http = _FakeHttp(
responses=[
_FakeResponse(
302,
headers={"location": "http://127.0.0.1/metadata"},
url="https://example.com/redirect.txt",
),
_FakeResponse(
200,
content=b"internal secret",
headers={"content-type": "text/plain"},
url="http://127.0.0.1/metadata",
),
]
)
data, filename, content_type = await channel._read_media_bytes("https://example.com/redirect.txt")
assert (data, filename, content_type) == (None, None, None)
assert [call["url"] for call in channel._http.calls] == ["https://example.com/redirect.txt"]
def test_normalize_upload_payload_zips_html_attachment() -> None:
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
data, filename, content_type = channel._normalize_upload_payload(
"report.html",
b"<html><body>Hello</body></html>",
"text/html",
)
assert filename == "report.zip"
assert content_type == "application/zip"
archive = zipfile.ZipFile(BytesIO(data))
assert archive.namelist() == ["report.html"]
assert archive.read("report.html") == b"<html><body>Hello</body></html>"
@pytest.mark.asyncio
async def test_send_media_ref_zips_html_before_upload(tmp_path, monkeypatch) -> None:
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
html_path = tmp_path / "report.html"
html_path.write_text("<html><body>Hello</body></html>", encoding="utf-8")
captured: dict[str, object] = {}
async def fake_upload_media(*, token, data, media_type, filename, content_type):
captured.update(
{
"token": token,
"data": data,
"media_type": media_type,
"filename": filename,
"content_type": content_type,
}
)
return "media-123"
async def fake_send_batch_message(token, chat_id, msg_key, msg_param):
captured.update(
{
"sent_token": token,
"chat_id": chat_id,
"msg_key": msg_key,
"msg_param": msg_param,
}
)
return True
monkeypatch.setattr(channel, "_upload_media", fake_upload_media)
monkeypatch.setattr(channel, "_send_batch_message", fake_send_batch_message)
ok = await channel._send_media_ref("token-123", "user-1", str(html_path))
assert ok is True
assert captured["media_type"] == "file"
assert captured["filename"] == "report.zip"
assert captured["content_type"] == "application/zip"
assert captured["msg_key"] == "sampleFile"
assert captured["msg_param"] == {
"mediaId": "media-123",
"fileName": "report.zip",
"fileType": "zip",
}
archive = zipfile.ZipFile(BytesIO(captured["data"]))
assert archive.namelist() == ["report.html"]
# ── Exception handling tests ──────────────────────────────────────────
@pytest.mark.asyncio
async def test_send_batch_message_propagates_transport_error() -> None:
"""Network/transport errors must re-raise so callers can retry."""
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
channel = DingTalkChannel(config, MessageBus())
channel._http = _NetworkErrorHttp()
with pytest.raises(httpx.ConnectError, match="Connection refused"):
await channel._send_batch_message(
"token",
"user123",
"sampleMarkdown",
{"text": "hello", "title": "Nanobot Reply"},
)
# The POST was attempted exactly once
assert len(channel._http.calls) == 1
assert channel._http.calls[0]["method"] == "POST"
@pytest.mark.asyncio
async def test_send_batch_message_returns_false_on_api_error() -> None:
"""DingTalk API-level errors (non-200 status, errcode != 0) should return False."""
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
channel = DingTalkChannel(config, MessageBus())
# Non-200 status code → API error → return False
channel._http = _FakeHttp(responses=[_FakeResponse(400, {"errcode": 400})])
result = await channel._send_batch_message(
"token", "user123", "sampleMarkdown", {"text": "hello"}
)
assert result is False
# 200 with non-zero errcode → API error → return False
channel._http = _FakeHttp(responses=[_FakeResponse(200, {"errcode": 100})])
result = await channel._send_batch_message(
"token", "user123", "sampleMarkdown", {"text": "hello"}
)
assert result is False
# 200 with errcode=0 → success → return True
channel._http = _FakeHttp(responses=[_FakeResponse(200, {"errcode": 0})])
result = await channel._send_batch_message(
"token", "user123", "sampleMarkdown", {"text": "hello"}
)
assert result is True
@pytest.mark.asyncio
async def test_send_raises_when_access_token_is_unavailable(monkeypatch) -> None:
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
monkeypatch.setattr(channel, "_get_access_token", AsyncMock(return_value=None))
with pytest.raises(RuntimeError, match="access token unavailable"):
await channel.send(
OutboundMessage(channel="dingtalk", chat_id="user123", content="hello")
)
@pytest.mark.asyncio
async def test_send_raises_when_text_is_not_delivered(monkeypatch) -> None:
channel = DingTalkChannel(
DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]),
MessageBus(),
)
monkeypatch.setattr(channel, "_get_access_token", AsyncMock(return_value="token"))
monkeypatch.setattr(channel, "_send_markdown_text", AsyncMock(return_value=False))
with pytest.raises(RuntimeError, match="text message was not delivered"):
await channel.send(
OutboundMessage(channel="dingtalk", chat_id="user123", content="hello")
)
@pytest.mark.asyncio
async def test_send_media_ref_short_circuits_on_transport_error() -> None:
"""When the first send fails with a transport error, _send_media_ref must
re-raise immediately instead of trying download+upload+fallback."""
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
channel = DingTalkChannel(config, MessageBus())
channel._http = _NetworkErrorHttp()
# An image URL triggers the sampleImageMsg path first
with pytest.raises(httpx.ConnectError, match="Connection refused"):
await channel._send_media_ref("token", "user123", "https://example.com/photo.jpg")
# Only one POST should have been attempted — no download/upload/fallback
assert len(channel._http.calls) == 1
assert channel._http.calls[0]["method"] == "POST"
@pytest.mark.asyncio
async def test_send_media_ref_short_circuits_on_download_transport_error() -> None:
"""When the image URL send returns an API error (False) but the download
for the fallback hits a transport error, it must re-raise rather than
silently returning False."""
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
channel = DingTalkChannel(config, MessageBus())
# First POST (sampleImageMsg) returns API error → False, then GET (download) raises transport error
class _MixedHttp:
def __init__(self) -> None:
self.calls: list[dict] = []
async def post(self, url, json=None, headers=None, **kwargs):
self.calls.append({"method": "POST", "url": url})
# API-level failure: 200 with errcode != 0
return _FakeResponse(200, {"errcode": 100})
async def get(self, url, **kwargs):
self.calls.append({"method": "GET", "url": url})
raise httpx.ConnectError("Connection refused")
channel._http = _MixedHttp()
with pytest.raises(httpx.ConnectError, match="Connection refused"):
await channel._send_media_ref("token", "user123", "https://example.com/photo.jpg")
# Should have attempted POST (image URL) and GET (download), but NOT upload
assert len(channel._http.calls) == 2
assert channel._http.calls[0]["method"] == "POST"
assert channel._http.calls[1]["method"] == "GET"
@pytest.mark.asyncio
async def test_send_media_ref_short_circuits_on_upload_transport_error() -> None:
"""When download succeeds but upload hits a transport error, must re-raise."""
config = DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"])
channel = DingTalkChannel(config, MessageBus())
image_bytes = b"\xff\xd8\xff\xe0" + b"\x00" * 100 # minimal JPEG-ish data
class _UploadFailsHttp:
def __init__(self) -> None:
self.calls: list[dict] = []
async def post(self, url, json=None, headers=None, files=None, **kwargs):
self.calls.append({"method": "POST", "url": url})
# If it's the upload endpoint, raise transport error
if "media/upload" in url:
raise httpx.ConnectError("Connection refused")
# Otherwise (sampleImageMsg), return API error to trigger fallback
return _FakeResponse(200, {"errcode": 100})
async def get(self, url, **kwargs):
self.calls.append({"method": "GET", "url": url})
resp = _FakeResponse(200)
resp.content = image_bytes
resp.headers = {"content-type": "image/jpeg"}
return resp
channel._http = _UploadFailsHttp()
with pytest.raises(httpx.ConnectError, match="Connection refused"):
await channel._send_media_ref("token", "user123", "https://example.com/photo.jpg")
# POST (image URL), GET (download), POST (upload) attempted — no further sends
methods = [c["method"] for c in channel._http.calls]
assert methods == ["POST", "GET", "POST"]
@@ -0,0 +1,31 @@
from __future__ import annotations
import pytest
from nanobot.channels.validation import validate_channel_config
from nanobot.config.loader import save_config
from nanobot.config.schema import Config
def test_validate_manual_channel_returns_configured(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
config_path = tmp_path / "config.json"
save_config(
Config.model_validate(
{
"channels": {
"dingtalk": {
"clientId": "ding-client",
"clientSecret": "ding-secret",
}
}
}
),
config_path,
)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
result = validate_channel_config("dingtalk", {})
assert result["status"] == "configured"
assert result["can_enable"] is True
assert any(check["status"] == "skipped" for check in result["checks"])
+21
View File
@@ -0,0 +1,21 @@
import type { ChannelUiContribution } from "@/channel-plugins/types";
import { chatAppGuideUrl } from "@/components/settings/channels/catalog";
export default {
presentation: {
displayName: "DingTalk",
initials: "DT",
color: "#1677FF",
logoUrl:
"https://img.alicdn.com/imgextra/i3/O1CN01WMvMRG1ks3Ixc9x1v_!!6000000004738-55-tps-32-32.svg",
setup: {
mode: "credentials",
docsUrl: chatAppGuideUrl("dingtalk"),
fields: [
{ key: "channels.dingtalk.clientId" },
{ key: "channels.dingtalk.clientSecret" },
{ key: "channels.dingtalk.allowFrom" },
],
},
},
} satisfies ChannelUiContribution;
@@ -0,0 +1,31 @@
{
"description": "Use nanobot from DingTalk groups.",
"requirements": "DingTalk app credentials and gateway",
"setup": {
"docsLabel": "Open DingTalk setup",
"officialLabel": "Open DingTalk console",
"tryIt": "Send a test message from the DingTalk group where the app is installed.",
"summary": "DingTalk needs app credentials from Stream mode.",
"steps": [
"Create or choose a DingTalk app with Stream mode enabled.",
"Add Client ID and Client Secret.",
"Save and enable DingTalk, then send a test message."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "DingTalk client ID",
"help": "Copy it from DingTalk app credentials."
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "Copy it from the same DingTalk app credentials page."
},
"allowFrom": {
"label": "Allowed users",
"placeholder": "User IDs, comma separated"
}
}
}
}
@@ -0,0 +1,31 @@
{
"description": "Usa nanobot desde grupos de DingTalk.",
"requirements": "Credenciales de la app de DingTalk y gateway",
"setup": {
"docsLabel": "Abrir guía de DingTalk",
"officialLabel": "Abrir consola de DingTalk",
"tryIt": "Envía un mensaje de prueba desde el grupo de DingTalk donde está instalada la app.",
"summary": "DingTalk necesita credenciales de una app en modo Stream.",
"steps": [
"Crea o elige una app de DingTalk con el modo Stream activado.",
"Añade el Client ID y el Client Secret.",
"Guarda y activa DingTalk; después envía un mensaje de prueba."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "Client ID de DingTalk",
"help": "Cópialo de las credenciales de la app de DingTalk."
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "Cópialo de la misma página de credenciales."
},
"allowFrom": {
"label": "Usuarios permitidos",
"placeholder": "ID de usuario separados por comas"
}
}
}
}
@@ -0,0 +1,31 @@
{
"description": "Utilisez nanobot depuis les groupes DingTalk.",
"requirements": "Identifiants d’application DingTalk et passerelle",
"setup": {
"docsLabel": "Ouvrir le guide DingTalk",
"officialLabel": "Ouvrir la console DingTalk",
"tryIt": "Envoyez un message test dans le groupe DingTalk où l’application est installée.",
"summary": "DingTalk nécessite les identifiants d’une application en mode Stream.",
"steps": [
"Créez ou choisissez une application DingTalk avec le mode Stream activé.",
"Ajoutez le Client ID et le Client Secret.",
"Enregistrez et activez DingTalk, puis envoyez un message test."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "Client ID DingTalk",
"help": "Copiez-le depuis les identifiants de l’application DingTalk."
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "Copiez-le depuis la même page d’identifiants DingTalk."
},
"allowFrom": {
"label": "Utilisateurs autorisés",
"placeholder": "ID utilisateur séparés par des virgules"
}
}
}
}
@@ -0,0 +1,31 @@
{
"description": "Gunakan nanobot dari grup DingTalk.",
"requirements": "Kredensial aplikasi DingTalk dan gateway",
"setup": {
"docsLabel": "Buka panduan DingTalk",
"officialLabel": "Buka konsol DingTalk",
"tryIt": "Kirim pesan uji dari grup DingTalk tempat aplikasi dipasang.",
"summary": "DingTalk memerlukan kredensial aplikasi dari mode Stream.",
"steps": [
"Buat atau pilih aplikasi DingTalk dengan mode Stream aktif.",
"Tambahkan Client ID dan Client Secret.",
"Simpan dan aktifkan DingTalk, lalu kirim pesan uji."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "Client ID DingTalk",
"help": "Salin dari kredensial aplikasi DingTalk."
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "Salin dari halaman kredensial yang sama."
},
"allowFrom": {
"label": "Pengguna yang diizinkan",
"placeholder": "ID pengguna, dipisahkan koma"
}
}
}
}
@@ -0,0 +1,31 @@
{
"description": "DingTalk グループから nanobot を利用します。",
"requirements": "DingTalk アプリの認証情報とゲートウェイ",
"setup": {
"docsLabel": "DingTalk 設定ガイドを開く",
"officialLabel": "DingTalk コンソールを開く",
"tryIt": "アプリをインストールした DingTalk グループからテストメッセージを送信します。",
"summary": "DingTalk には Stream モードのアプリ認証情報が必要です。",
"steps": [
"Stream モードを有効にした DingTalk アプリを作成または選択します。",
"Client ID と Client Secret を追加します。",
"保存して DingTalk を有効にし、テストメッセージを送信します。"
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "DingTalk Client ID",
"help": "DingTalk アプリの認証情報からコピーします。"
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "同じ認証情報ページからコピーします。"
},
"allowFrom": {
"label": "許可するユーザー",
"placeholder": "ユーザー ID(カンマ区切り)"
}
}
}
}
@@ -0,0 +1,31 @@
{
"description": "DingTalk 그룹에서 nanobot을 사용합니다.",
"requirements": "DingTalk 앱 자격 증명 및 게이트웨이",
"setup": {
"docsLabel": "DingTalk 설정 가이드 열기",
"officialLabel": "DingTalk 콘솔 열기",
"tryIt": "앱이 설치된 DingTalk 그룹에서 테스트 메시지를 보내세요.",
"summary": "DingTalk에는 Stream 모드 앱 자격 증명이 필요합니다.",
"steps": [
"Stream 모드가 활성화된 DingTalk 앱을 만들거나 선택하세요.",
"Client ID와 Client Secret을 추가하세요.",
"저장하고 DingTalk을 활성화한 다음 테스트 메시지를 보내세요."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "DingTalk Client ID",
"help": "DingTalk 앱 자격 증명에서 복사하세요."
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "같은 자격 증명 페이지에서 복사하세요."
},
"allowFrom": {
"label": "허용된 사용자",
"placeholder": "사용자 ID, 쉼표로 구분"
}
}
}
}
@@ -0,0 +1,31 @@
{
"description": "Use o nanobot em grupos do DingTalk.",
"requirements": "Credenciais do app DingTalk e gateway",
"setup": {
"docsLabel": "Abrir guia do DingTalk",
"officialLabel": "Abrir console do DingTalk",
"tryIt": "Envie uma mensagem de teste no grupo do DingTalk onde o app está instalado.",
"summary": "O DingTalk precisa das credenciais de um app no modo Stream.",
"steps": [
"Crie ou escolha um app do DingTalk com o modo Stream ativado.",
"Adicione o Client ID e o Client Secret.",
"Salve e ative o DingTalk; depois, envie uma mensagem de teste."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "Client ID do DingTalk",
"help": "Copie das credenciais do app DingTalk."
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "Copie da mesma página de credenciais."
},
"allowFrom": {
"label": "Usuários permitidos",
"placeholder": "IDs de usuário separados por vírgulas"
}
}
}
}
@@ -0,0 +1,31 @@
{
"description": "Sử dụng nanobot trong các nhóm DingTalk.",
"requirements": "Thông tin xác thực ứng dụng DingTalk và gateway",
"setup": {
"docsLabel": "Mở hướng dẫn DingTalk",
"officialLabel": "Mở bảng điều khiển DingTalk",
"tryIt": "Gửi tin nhắn thử từ nhóm DingTalk đã cài ứng dụng.",
"summary": "DingTalk cần thông tin xác thực ứng dụng ở chế độ Stream.",
"steps": [
"Tạo hoặc chọn ứng dụng DingTalk đã bật chế độ Stream.",
"Thêm Client ID và Client Secret.",
"Lưu và bật DingTalk, sau đó gửi tin nhắn thử."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "Client ID DingTalk",
"help": "Sao chép từ thông tin xác thực ứng dụng DingTalk."
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "Sao chép từ cùng trang thông tin xác thực."
},
"allowFrom": {
"label": "Người dùng được phép",
"placeholder": "ID người dùng, phân tách bằng dấu phẩy"
}
}
}
}
@@ -0,0 +1,32 @@
{
"displayName": "钉钉",
"description": "在钉钉群中使用 nanobot。",
"requirements": "钉钉应用凭据和网关",
"setup": {
"docsLabel": "打开钉钉配置指南",
"officialLabel": "打开钉钉开发者后台",
"tryIt": "在已安装应用的钉钉群中发送一条测试消息。",
"summary": "钉钉需要 Stream 模式的应用凭据。",
"steps": [
"创建或选择一个已启用 Stream 模式的钉钉应用。",
"填写 Client ID 和 Client Secret。",
"保存并启用钉钉,然后发送一条测试消息。"
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "钉钉 Client ID",
"help": "从钉钉应用凭据页面复制。"
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "从同一个钉钉应用凭据页面复制。"
},
"allowFrom": {
"label": "允许的用户",
"placeholder": "用户 ID,用逗号分隔"
}
}
}
}
@@ -0,0 +1,32 @@
{
"displayName": "釘釘",
"description": "在釘釘群組中使用 nanobot。",
"requirements": "釘釘應用程式憑證和閘道",
"setup": {
"docsLabel": "開啟釘釘設定指南",
"officialLabel": "開啟釘釘開發者後台",
"tryIt": "在已安裝應用程式的釘釘群組中傳送一則測試訊息。",
"summary": "釘釘需要 Stream 模式的應用程式憑證。",
"steps": [
"建立或選擇一個已啟用 Stream 模式的釘釘應用程式。",
"填入 Client ID 和 Client Secret。",
"儲存並啟用釘釘,然後傳送一則測試訊息。"
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "釘釘 Client ID",
"help": "從釘釘應用程式憑證頁面複製。"
},
"clientSecret": {
"label": "Client Secret",
"placeholder": "••••••",
"help": "從同一個釘釘應用程式憑證頁面複製。"
},
"allowFrom": {
"label": "允許的使用者",
"placeholder": "使用者 ID,以逗號分隔"
}
}
}
}