Skip to content

The agent that grows with you

feat(qqbot): add support for proactive media delivery via send_message

cadezhoue167fc33b797
diff --git a/tests/tools/test_qqbot_send_message_media.py b/tests/tools/test_qqbot_send_message_media.py
new file mode 100644
index 00000000000..ca008441fe5
--- /dev/null
+++ b/tests/tools/test_qqbot_send_message_media.py
@@ -0,0 +1,243 @@
+"""QQ Bot proactive MEDIA delivery via send_message / _send_to_platform (#37315)."""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+from gateway.config import Platform
+from gateway.platforms.qqbot.constants import (
+ MEDIA_TYPE_FILE,
+ MEDIA_TYPE_IMAGE,
+ MEDIA_TYPE_VIDEO,
+ MEDIA_TYPE_VOICE,
+ MSG_TYPE_MEDIA,
+)
+from tools.send_message_senders import _qqbot_media_file_type
+from tools.send_message_tool import _send_qqbot, _send_to_platform
+
+
+def _pconfig():
+ return SimpleNamespace(
+ token="client-secret",
+ extra={"app_id": "app-123", "client_secret": "client-secret"},
+ enabled=True,
+ )
+
+
+class TestQqbotMediaFileType:
+ def test_image_ext(self):
+ assert _qqbot_media_file_type("/tmp/a.PNG", False) == MEDIA_TYPE_IMAGE
+
+ def test_video_ext(self):
+ assert _qqbot_media_file_type("/tmp/a.mp4", False) == MEDIA_TYPE_VIDEO
+
+ def test_voice_flag_or_ext(self):
+ assert _qqbot_media_file_type("/tmp/a.ogg", True) == MEDIA_TYPE_VOICE
+ assert _qqbot_media_file_type("/tmp/a.opus", False) == MEDIA_TYPE_VOICE
+
+ def test_generic_file(self):
+ assert _qqbot_media_file_type("/tmp/report.pdf", False) == MEDIA_TYPE_FILE
+
+
+class TestSendToPlatformQqbotMediaRouting:
+ def test_media_only_routes_to_send_qqbot_not_allowlist_error(self, tmp_path):
+ img = tmp_path / "shot.png"
+ img.write_bytes(b"\x89PNG\r\n\x1a\n")
+ media = [(str(img), False)]
+
+ with patch(
+ "tools.send_message_tool._send_qqbot",
+ new=AsyncMock(
+ return_value={
+ "success": True,
+ "platform": "qqbot",
+ "chat_id": "openid-1",
+ }
+ ),
+ ) as mock_send:
+ result = asyncio.run(
+ _send_to_platform(
+ Platform.QQBOT,
+ _pconfig(),
+ "openid-1",
+ "",
+ media_files=media,
+ )
+ )
+
+ assert result["success"] is True
+ assert "only supported for" not in str(result)
+ mock_send.assert_awaited_once()
+ assert mock_send.await_args.kwargs.get("media_files") == media
+
+ def test_text_plus_media_uses_caption_not_omission_warning(self, tmp_path):
+ img = tmp_path / "photo.jpg"
+ img.write_bytes(b"jpeg-bytes")
+ media = [(str(img), False)]
+
+ with patch(
+ "tools.send_message_tool._send_qqbot",
+ new=AsyncMock(
+ return_value={"success": True, "platform": "qqbot", "chat_id": "oid"}
+ ),
+ ) as mock_send:
+ result = asyncio.run(
+ _send_to_platform(
+ Platform.QQBOT,
+ _pconfig(),
+ "oid",
+ "hello caption",
+ media_files=media,
+ )
+ )
+
+ assert result.get("success") is True
+ assert not any("omitted" in w for w in result.get("warnings", []))
+ assert mock_send.await_count == 1
+ call = mock_send.await_args
+ assert call.kwargs.get("media_files") == media
+ assert call.kwargs.get("caption") == "hello caption"
+ assert call.args[2] == ""
+
+
+class TestSendQqbotMedia:
+ def test_media_path_calls_deliver_after_token(self, tmp_path):
+ img = tmp_path / "logo.png"
+ img.write_bytes(b"png-data")
+
+ token_resp = SimpleNamespace(
+ status_code=200,
+ json=lambda: {"access_token": "at-1"},
+ )
+
+ class _Client:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def post(self, url, json=None, headers=None):
+ assert "getAppAccessToken" in url or url.endswith("getAppAccessToken")
+ return token_resp
+
+ class _HttpxMod:
+ AsyncClient = _Client
+
+ deliver = AsyncMock(
+ return_value={
+ "success": True,
+ "platform": "qqbot",
+ "chat_id": "user-openid",
+ "message_id": "m-1",
+ "chat_type": "c2c",
+ }
+ )
+
+ with patch.dict("sys.modules", {"httpx": _HttpxMod()}), patch(
+ "tools.send_message_senders._qqbot_deliver_one_media",
+ new=deliver,
+ ):
+ result = asyncio.run(
+ _send_qqbot(
+ _pconfig(),
+ "user-openid",
+ "",
+ media_files=[(str(img), False)],
+ caption="see this",
+ )
+ )
+
+ assert result["success"] is True
+ deliver.assert_awaited_once()
+ _args, kwargs = deliver.await_args
+ assert kwargs.get("caption") == "see this" or (
+ len(_args) >= 6 and _args[5] == "see this"
+ )
+ # chat_id + path
+ assert "user-openid" in _args
+ assert str(img) in _args
+
+ def test_deliver_one_media_falls_back_c2c_to_group(self, tmp_path):
+ from tools.send_message_senders import _qqbot_deliver_one_media
+
+ img = tmp_path / "a.png"
+ img.write_bytes(b"x")
+ calls = []
+
+ async def _fake_upload_local(
+ client, headers, chat_type, chat_id, media_path, file_type
+ ):
+ calls.append(("upload", chat_type, file_type))
+ if chat_type == "c2c":
+ raise RuntimeError("c2c rejected")
+ return {"file_info": "FI-99"}
+
+ async def _fake_send_media(
+ client, headers, chat_type, chat_id, file_info, caption=None
+ ):
+ calls.append(("send", chat_type, file_info, caption))
+ return {"id": "mid-2"}
+
+ with patch(
+ "tools.send_message_senders._qqbot_upload_local_file",
+ new=AsyncMock(side_effect=_fake_upload_local),
+ ), patch(
+ "tools.send_message_senders._qqbot_send_media_message",
+ new=AsyncMock(side_effect=_fake_send_media),
+ ):
+ result = asyncio.run(
+ _qqbot_deliver_one_media(
+ client=None,
+ headers={"Authorization": "QQBot t"},
+ chat_id="gid",
+ media_path=str(img),
+ is_voice=False,
+ caption="cap",
+ )
+ )
+
+ assert result["success"] is True
+ assert result["chat_type"] == "group"
+ assert ("upload", "c2c", MEDIA_TYPE_IMAGE) in calls
+ assert ("upload", "group", MEDIA_TYPE_IMAGE) in calls
+ assert ("send", "group", "FI-99", "cap") in calls
+
+
+class TestQqbotSendMediaMessageBody:
+ def test_body_uses_msg_type_media(self):
+ from tools.send_message_senders import _qqbot_send_media_message
+
+ captured = {}
+
+ async def _fake_api(client, headers, method, path, body=None, timeout=30.0):
+ captured["method"] = method
+ captured["path"] = path
+ captured["body"] = body
+ return {"id": "x"}
+
+ with patch(
+ "tools.send_message_senders._qqbot_api_json",
+ new=AsyncMock(side_effect=_fake_api),
+ ):
+ asyncio.run(
+ _qqbot_send_media_message(
+ None,
+ {},
+ "c2c",
+ "u1",
+ "FILEINFO",
+ caption="hi",
+ )
+ )
+
+ assert captured["method"] == "POST"
+ assert captured["path"] == "/v2/users/u1/messages"
+ assert captured["body"]["msg_type"] == MSG_TYPE_MEDIA
+ assert captured["body"]["media"] == {"file_info": "FILEINFO"}
+ assert captured["body"]["content"] == "hi"
diff --git a/tools/send_message_senders.py b/tools/send_message_senders.py
index f53822dfac4..02ba98ef4d8 100644
--- a/tools/send_message_senders.py
+++ b/tools/send_message_senders.py
@@ -617,8 +617,153 @@ async def _send_bluebubbles(extra, chat_id, message):
return _error(f"BlueBubbles send failed: {e}")
-async def _send_qqbot(pconfig, chat_id, message):
- """Send via the QQ Bot Open Platform REST API (no WebSocket needed)."""
+def _qqbot_media_file_type(media_path: str, is_voice: bool) -> int:
+ """Map a local path / voice flag to QQ Bot ``file_type`` constants."""
+ from gateway.platforms.qqbot.constants import (
+ MEDIA_TYPE_FILE, MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, MEDIA_TYPE_VOICE)
+
+ ext = os.path.splitext(media_path)[1].lower()
+ if is_voice or ext in _VOICE_EXTS:
+ return MEDIA_TYPE_VOICE
+ if ext in _IMAGE_EXTS:
+ return MEDIA_TYPE_IMAGE
+ if ext in _VIDEO_EXTS:
+ return MEDIA_TYPE_VIDEO
+ if ext in _AUDIO_EXTS:
+ return MEDIA_TYPE_VOICE
+ return MEDIA_TYPE_FILE
+
+
+async def _qqbot_api_json(client, headers: dict, method: str, path: str,
+ body: dict | None = None, *, timeout: float = 30.0) -> dict:
+ """POST/GET JSON against ``api.sgroup.qq.com``; raise RuntimeError on failure."""
+ from gateway.platforms.qqbot.constants import API_BASE
+
+ resp = await client.request(method, f"{API_BASE}{path}", json=body, headers=headers, timeout=timeout)
+ try:
+ data = resp.json() if resp.content else {}
+ except Exception:
+ data = {}
+ if resp.status_code >= 400:
+ raise RuntimeError(
+ f"QQ Bot API error [{resp.status_code}] {path}: "
+ f"{data.get('message', data) or resp.text[:200]}")
+ return data if isinstance(data, dict) else {}
+
+
+async def _qqbot_upload_local_file(client, headers, chat_type, chat_id, media_path, file_type) -> dict:
+ """Chunked-upload a local file; returns the ``/files`` complete response."""
+ from pathlib import Path as _Path
+ from gateway.platforms.qqbot.chunked_upload import ChunkedUploader
+ from gateway.platforms.qqbot.constants import FILE_UPLOAD_TIMEOUT
+
+ local_path = _Path(media_path).expanduser()
+ if not local_path.is_absolute():
+ local_path = (_Path.cwd() / local_path).resolve()
+ if not local_path.exists() or not local_path.is_file():
+ raise FileNotFoundError(f"Media file not found: {local_path}")
+
+ async def _api_request(method, path, body=None, timeout=FILE_UPLOAD_TIMEOUT):
+ return await _qqbot_api_json(client, headers, method, path, body, timeout=timeout)
+
+ uploader = ChunkedUploader(api_request=_api_request, http_put=client.put, log_tag="send_message.qqbot")
+ return await uploader.upload(
+ chat_type=chat_type, target_id=chat_id, file_path=str(local_path),
+ file_type=file_type, file_name=local_path.name)
+
+
+async def _qqbot_upload_url(client, headers, chat_type, chat_id, url, file_type,
+ file_name=None) -> dict:
+ """Ask QQ to fetch ``url`` into the media store; returns upload JSON."""
+ from gateway.platforms.qqbot.constants import FILE_UPLOAD_TIMEOUT, MEDIA_TYPE_FILE
+
+ path = f"/v2/users/{chat_id}/files" if chat_type == "c2c" else f"/v2/groups/{chat_id}/files"
+ body = {"file_type": file_type, "srv_send_msg": False, "url": url}
+ if file_type == MEDIA_TYPE_FILE and file_name:
+ body["file_name"] = file_name
+ return await _qqbot_api_json(client, headers, "POST", path, body, timeout=FILE_UPLOAD_TIMEOUT)
+
+
+def _qqbot_extract_file_info(upload: dict):
+ if not isinstance(upload, dict):
+ return None
+ file_info = upload.get("file_info") or (upload.get("data") or {}).get("file_info")
+ return file_info if file_info else None
+
+
+async def _qqbot_send_media_message(client, headers, chat_type, chat_id, file_info,
+ caption=None) -> dict:
+ """POST a RichMedia message referencing an uploaded ``file_info``."""
+ from gateway.platforms.qqbot.constants import MAX_MESSAGE_LENGTH, MSG_TYPE_MEDIA
+
+ path = f"/v2/users/{chat_id}/messages" if chat_type == "c2c" else f"/v2/groups/{chat_id}/messages"
+ body = {"msg_type": MSG_TYPE_MEDIA, "media": {"file_info": file_info},
+ "msg_seq": int(time.time() * 1000) % 1_000_000_000}
+ if caption and caption.strip():
+ body["content"] = caption.strip()[:MAX_MESSAGE_LENGTH]
+ return await _qqbot_api_json(client, headers, "POST", path, body)
+
+
+async def _qqbot_send_text_message(client, headers, chat_id, message: str) -> dict:
+ """Try channel → C2C → group text endpoints (pre-media standalone behavior)."""
+ payload = {"content": (message or "")[:4000], "msg_type": 0}
+ endpoints = (("channel", f"https://api.sgroup.qq.com/channels/{chat_id}/messages"),
+ ("c2c", f"https://api.sgroup.qq.com/v2/users/{chat_id}/messages"),
+ ("group", f"https://api.sgroup.qq.com/v2/groups/{chat_id}/messages"))
+ statuses = []
+ for kind, url in endpoints:
+ resp = await client.post(url, json=payload, headers=headers)
+ if resp.status_code in {200, 201}:
+ return _success("qqbot", chat_id, message_id=resp.json().get("id"))
+ statuses.append(f"{kind}={resp.status_code}")
+ return _error(f"QQBot send failed: {' '.join(statuses)}")
+
+
+async def _qqbot_deliver_one_media(client, headers, chat_id, media_path, is_voice,
+ caption=None) -> dict:
+ """Upload one attachment and send it, trying C2C then group (no guild)."""
+ from pathlib import Path as _Path
+ from urllib.parse import urlparse
+
+ file_type = _qqbot_media_file_type(media_path, is_voice)
+ is_url = urlparse(str(media_path)).scheme in {"http", "https"}
+ errors: list[str] = []
+
+ for chat_type in ("c2c", "group"):
+ try:
+ if is_url:
+ upload = await _qqbot_upload_url(
+ client, headers, chat_type, chat_id, media_path, file_type,
+ file_name=_Path(urlparse(media_path).path).name or "media")
+ else:
+ upload = await _qqbot_upload_local_file(
+ client, headers, chat_type, chat_id, media_path, file_type)
+ file_info = _qqbot_extract_file_info(upload)
+ if not file_info:
+ errors.append(f"{chat_type}: upload returned no file_info: {upload}")
+ continue
+ send_data = await _qqbot_send_media_message(
+ client, headers, chat_type, chat_id, file_info, caption=caption)
+ return _success("qqbot", chat_id, message_id=send_data.get("id"), chat_type=chat_type)
+ except Exception as exc:
+ errors.append(f"{chat_type}: {exc}")
+ continue
+
+ return _error(
+ "QQBot media send failed (guild/channel native media is unsupported; "
+ f"tried c2c and group): {'; '.join(errors)}")
+
+
+async def _send_qqbot(pconfig, chat_id, message, media_files=None, caption=None):
+ """Send via the QQ Bot Open Platform REST API (no WebSocket needed).
+
+ Guild channels, C2C (private) chats and groups are tried in order for text.
+ When ``media_files`` is provided, each attachment is uploaded (C2C then
+ group — guild has no native media upload path) and sent as a
+ ``msg_type=MEDIA`` RichMedia message (#37315). Optional ``caption`` rides on
+ the first media bubble; non-empty ``message`` is sent as a separate text
+ message before the media.
+ """
try:
import httpx
except ImportError:
@@ -626,13 +771,19 @@ async def _send_qqbot(pconfig, chat_id, message):
# Profile-scoped lookup so a multiplex profile never borrows another's QQ credentials.
from gateway.config import _getenv
+ from gateway.platforms.qqbot.constants import FILE_UPLOAD_TIMEOUT
extra = pconfig.extra or {}
appid = extra.get("app_id") or _getenv("QQ_APP_ID", "")
secret = pconfig.token or extra.get("client_secret") or _getenv("QQ_CLIENT_SECRET", "")
if not appid or not secret:
return _error("QQBot: QQ_APP_ID / QQ_CLIENT_SECRET not configured.")
+
+ media_files = media_files or []
+ # Longer timeout when uploading; text-only stays snappy.
+ client_timeout = FILE_UPLOAD_TIMEOUT if media_files else 15.0
+
try:
- async with httpx.AsyncClient(timeout=15) as client:
+ async with httpx.AsyncClient(timeout=client_timeout) as client:
token_resp = await client.post("https://bots.qq.com/app/getAppAccessToken",
json={"appId": str(appid), "clientSecret": str(secret)})
if token_resp.status_code != 200:
@@ -641,19 +792,41 @@ async def _send_qqbot(pconfig, chat_id, message):
if not access_token:
return _error("QQBot: no access_token in response")
- # Separate endpoints for guild channels, C2C (private) and groups; first 2xx wins.
headers = {"Authorization": f"QQBot {access_token}", "Content-Type": "application/json"}
- payload = {"content": message[:4000], "msg_type": 0}
- endpoints = (("channel", f"https://api.sgroup.qq.com/channels/{chat_id}/messages"),
- ("c2c", f"https://api.sgroup.qq.com/v2/users/{chat_id}/messages"),
- ("group", f"https://api.sgroup.qq.com/v2/groups/{chat_id}/messages"))
- statuses = []
- for kind, url in endpoints:
- resp = await client.post(url, json=payload, headers=headers)
- if resp.status_code in {200, 201}:
- return _success("qqbot", chat_id, message_id=resp.json().get("id"))
- statuses.append(f"{kind}={resp.status_code}")
- return _error(f"QQBot send failed: {' '.join(statuses)}")
+
+ # --- Media path (#37315) ---
+ if media_files:
+ last_result = None
+ text = (message or "").strip()
+ if text and not (caption and caption.strip()):
+ text_result = await _qqbot_send_text_message(client, headers, chat_id, text)
+ if isinstance(text_result, dict) and text_result.get("error"):
+ return text_result
+ last_result = text_result
+
+ for index, (media_path, is_voice) in enumerate(media_files):
+ if not media_path:
+ continue
+ # Caption applies to the first bubble only (single-file
+ # caption split already enforced by the caller).
+ media_caption = caption if index == 0 else None
+ if not os.path.exists(media_path):
+ from urllib.parse import urlparse as _urlparse
+ if _urlparse(str(media_path)).scheme not in {"http", "https"}:
+ logger.warning("QQBot media file not found, skipping: %s", media_path)
+ continue
+ result = await _qqbot_deliver_one_media(
+ client, headers, chat_id, media_path, bool(is_voice), caption=media_caption)
+ if isinstance(result, dict) and result.get("error"):
+ return result
+ last_result = result
+
+ if last_result is None:
+ return _error("QQBot: no deliverable media attachments")
+ return last_result
+
+ # --- Text-only path: first 2xx wins (pre-media behavior) ---
+ return await _qqbot_send_text_message(client, headers, chat_id, message or "")
except Exception as e:
return _error(f"QQBot send failed: {e}")
diff --git a/tools/send_message_tool.py b/tools/send_message_tool.py
index 1967f73c431..2254815d64d 100644
--- a/tools/send_message_tool.py
+++ b/tools/send_message_tool.py
@@ -683,7 +683,7 @@ _TEXT_SENDERS = {
"qqbot": lambda pc, cid, chunk, tid: _send_qqbot(pc, cid, chunk),
"yuanbao": lambda pc, cid, chunk, tid: _send_yuanbao(cid, chunk)}
-_MEDIA_PLATFORMS_NOTE = "telegram, discord, matrix, weixin, signal, yuanbao, feishu, whatsapp and slack"
+_MEDIA_PLATFORMS_NOTE = "telegram, discord, matrix, weixin, signal, yuanbao, feishu, whatsapp, slack and qqbot"
async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, media_files=None,
@@ -715,6 +715,24 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,
return await _send_chunks(chunks, lambda chunk, is_last: sender(
platform, pconfig, chat_id, chunk, media_files if is_last else empty_media, thread_id, force_document))
+ # --- QQ Bot: native media via REST upload + MSG_TYPE_MEDIA (issue #37315).
+ # Guild channels are unsupported for native media (same as QQBotAdapter);
+ # C2C / group use /v2/{users|groups}/{id}/files then .../messages.
+ if platform == Platform.QQBOT and media_files:
+ qq_caption, _ = _media_caption_split(
+ message, media_files, max_caption_len=(max_len or _DEFAULT_CAPTION_LIMIT))
+ if qq_caption is not None:
+ return await _send_qqbot(pconfig, chat_id, "", media_files=media_files, caption=qq_caption)
+ last_result = None
+ for i, chunk in enumerate(chunks):
+ is_last = (i == len(chunks) - 1)
+ result = await _send_qqbot(
+ pconfig, chat_id, chunk, media_files=media_files if is_last else None)
+ if isinstance(result, dict) and result.get("error"):
+ return result
+ last_result = result
+ return last_result
+
# Generic path: text only. Buzz delivers media natively via _send_via_adapter, so no warning.
warning = None
if media_files and platform_name != "buzz":