The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(qqbot): move the built-in adapter into the bundled platform plugin
cxyhhhhh0a2992af65de
diff --git a/gateway/platforms/qqbot/__init__.py b/gateway/platforms/qqbot/__init__.pydeleted file mode 100644index 277e02fe1f6..00000000000--- a/gateway/platforms/qqbot/__init__.py+++ /dev/null@@ -1,42 +0,0 @@-"""QQBot platform package. Re-exports adapter symbols so existing import paths-(``from gateway.platforms.qqbot import QQAdapter, check_qq_requirements``) keep working.-Sub-modules: constants, utils, crypto (AES-256-GCM), onboard (QR), chunked_upload, keyboards."""--from .adapter import QQAdapter, QQCloseError, check_qq_requirements, _coerce_list, _ssrf_redirect_guard-from .onboard import BindStatus, build_connect_url, qr_register-from .crypto import decrypt_secret, generate_bind_key-from .utils import build_user_agent, get_api_headers, coerce_list-from .chunked_upload import ChunkedUploader, UploadDailyLimitExceededError, UploadFileTooLargeError-from .keyboards import (- ApprovalRequest, InlineKeyboard, InteractionEvent, build_approval_keyboard, build_approval_text,- build_update_prompt_keyboard, parse_approval_button_data, parse_interaction_event,- parse_update_prompt_button_data,-)--__all__ = [- "ApprovalRequest",- "BindStatus",- "ChunkedUploader",- "InlineKeyboard",- "InteractionEvent",- "QQAdapter",- "QQCloseError",- "UploadDailyLimitExceededError",- "UploadFileTooLargeError",- "_coerce_list",- "_ssrf_redirect_guard",- "build_approval_keyboard",- "build_approval_text",- "build_connect_url",- "build_update_prompt_keyboard",- "build_user_agent",- "check_qq_requirements",- "coerce_list",- "decrypt_secret",- "generate_bind_key",- "get_api_headers",- "parse_approval_button_data",- "parse_interaction_event",- "parse_update_prompt_button_data",- "qr_register",-]diff --git a/plugins/platforms/qqbot/__init__.py b/plugins/platforms/qqbot/__init__.pynew file mode 100644index 00000000000..67081b07507--- /dev/null+++ b/plugins/platforms/qqbot/__init__.py@@ -0,0 +1,3 @@+from .register import register++__all__ = ["register"]diff --git a/gateway/platforms/qqbot/adapter.py b/plugins/platforms/qqbot/adapter.pysimilarity index 99%rename from gateway/platforms/qqbot/adapter.pyrename to plugins/platforms/qqbot/adapter.pyindex 7067d92a7ac..8239df3de52 100644--- a/gateway/platforms/qqbot/adapter.py+++ b/plugins/platforms/qqbot/adapter.py@@ -61,16 +61,16 @@ class QQCloseError(Exception):super().__init__(f"WebSocket closed (code={self.code}, reason={self.reason})")-from gateway.platforms.qqbot.constants import (+from .constants import (API_BASE, TOKEN_URL, GATEWAY_URL_PATH, DEFAULT_API_TIMEOUT, FILE_UPLOAD_TIMEOUT,CONNECT_TIMEOUT_SECONDS, RECONNECT_BACKOFF, MAX_RECONNECT_ATTEMPTS, RATE_LIMIT_DELAY,QUICK_DISCONNECT_THRESHOLD, MAX_QUICK_DISCONNECT_COUNT, MAX_MESSAGE_LENGTH,DEDUP_WINDOW_SECONDS, DEDUP_MAX_SIZE, MSG_TYPE_TEXT, MSG_TYPE_MARKDOWN, MSG_TYPE_MEDIA,MSG_TYPE_INPUT_NOTIFY, MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, MEDIA_TYPE_VOICE, MEDIA_TYPE_FILE)-from gateway.platforms.qqbot.utils import coerce_list as _coerce_list, build_user_agent-from gateway.platforms.qqbot.chunked_upload import (+from .utils import coerce_list as _coerce_list, build_user_agent+from .chunked_upload import (ChunkedUploader, UploadDailyLimitExceededError, UploadFileTooLargeError)-from gateway.platforms.qqbot.keyboards import (+from .keyboards import (ApprovalRequest, InlineKeyboard, InteractionEvent, build_approval_keyboard,build_update_prompt_keyboard, parse_approval_button_data, parse_interaction_event,parse_update_prompt_button_data)@@ -1472,7 +1472,7 @@ class QQAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):self, chat_id: str, req: ApprovalRequest, reply_to: Optional[str] = None) -> SendResult:"""Send a 3-button approval request (allow-once / allow-always / deny);clicks come back as INTERACTION_CREATE decoded by parse_approval_button_data."""- from gateway.platforms.qqbot.keyboards import build_approval_text+ from .keyboards import build_approval_textkeyboard = build_approval_keyboard(req.session_key, allow_permanent=getattr(req, "allow_permanent", True))return await self.send_with_keyboard(chat_id, build_approval_text(req), keyboard, reply_to=reply_to)diff --git a/gateway/platforms/qqbot/chunked_upload.py b/plugins/platforms/qqbot/chunked_upload.pysimilarity index 99%rename from gateway/platforms/qqbot/chunked_upload.pyrename to plugins/platforms/qqbot/chunked_upload.pyindex f74ef1ae655..237ff0b0953 100644--- a/gateway/platforms/qqbot/chunked_upload.py+++ b/plugins/platforms/qqbot/chunked_upload.py@@ -16,7 +16,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Awaitable, Callable, Dict, List-from gateway.platforms.qqbot.constants import FILE_UPLOAD_TIMEOUT+from .constants import FILE_UPLOAD_TIMEOUTlogger = logging.getLogger(__name__)diff --git a/gateway/platforms/qqbot/constants.py b/plugins/platforms/qqbot/constants.pysimilarity index 100%rename from gateway/platforms/qqbot/constants.pyrename to plugins/platforms/qqbot/constants.pydiff --git a/gateway/platforms/qqbot/crypto.py b/plugins/platforms/qqbot/crypto.pysimilarity index 100%rename from gateway/platforms/qqbot/crypto.pyrename to plugins/platforms/qqbot/crypto.pydiff --git a/gateway/platforms/qqbot/keyboards.py b/plugins/platforms/qqbot/keyboards.pysimilarity index 100%rename from gateway/platforms/qqbot/keyboards.pyrename to plugins/platforms/qqbot/keyboards.pydiff --git a/gateway/platforms/qqbot/onboard.py b/plugins/platforms/qqbot/onboard.pysimilarity index 100%rename from gateway/platforms/qqbot/onboard.pyrename to plugins/platforms/qqbot/onboard.pydiff --git a/plugins/platforms/qqbot/plugin.yaml b/plugins/platforms/qqbot/plugin.yamlnew file mode 100644index 00000000000..b62b8a39fef--- /dev/null+++ b/plugins/platforms/qqbot/plugin.yaml@@ -0,0 +1,67 @@+name: qqbot+label: QQ Bot+kind: platform+version: 1.0.0+description: >+ QQ Bot gateway adapter (Official QQ Bot API v2). WebSocket gateway for+ inbound events, REST for outbound text and media.+author: Nous Research+requires_env:+ - name: QQ_APP_ID+ description: "QQ Bot App ID from QQ Open Platform (q.qq.com)"+ prompt: "QQ App ID"+ url: "https://q.qq.com"+ password: false+ - name: QQ_CLIENT_SECRET+ description: "QQ Bot Client Secret from QQ Open Platform"+ prompt: "QQ Client Secret"+ password: true+optional_env:+ - name: QQ_ALLOWED_USERS+ description: "Comma-separated QQ user OpenIDs allowed to use the bot"+ prompt: "QQ Allowed Users"+ password: false+ - name: QQ_GROUP_ALLOWED_USERS+ description: "Comma-separated QQ group OpenIDs allowed to interact with the bot"+ prompt: "QQ Group Allowed Users"+ password: false+ - name: QQ_ALLOW_ALL_USERS+ description: "Allow all QQ users without an allowlist (true/false)"+ prompt: "Allow All QQ Users"+ password: false+ - name: QQBOT_HOME_CHANNEL+ description: "Default QQ channel/group for cron delivery and notifications"+ prompt: "QQ Home Channel"+ password: false+ - name: QQBOT_HOME_CHANNEL_NAME+ description: "Display name for the QQ home channel"+ prompt: "QQ Home Channel Name"+ password: false+ - name: QQBOT_HOME_CHANNEL_THREAD_ID+ description: "Thread id for the QQ home channel, when the target is a thread"+ prompt: "QQ Home Channel Thread ID"+ password: false+ - name: QQ_MARKDOWN_SUPPORT+ description: "Send QQ messages as markdown when the bot is allowed to (true/false)"+ prompt: "QQ Markdown Support"+ password: false+ - name: QQ_SANDBOX+ description: "Enable QQ sandbox mode for development testing (true/false)"+ prompt: "QQ Sandbox Mode"+ password: false+ - name: QQ_PORTAL_HOST+ description: "QQ Open Platform portal host (default q.qq.com)"+ prompt: "QQ Portal Host"+ password: false+ - name: QQ_STT_API_KEY+ description: "API key for QQ voice transcription fallback"+ prompt: "QQ STT API Key"+ password: true+ - name: QQ_STT_BASE_URL+ description: "Base URL for the QQ voice transcription provider"+ prompt: "QQ STT Base URL"+ password: false+ - name: QQ_STT_MODEL+ description: "Model name for the QQ voice transcription provider"+ prompt: "QQ STT Model"+ password: falsediff --git a/plugins/platforms/qqbot/register.py b/plugins/platforms/qqbot/register.pynew file mode 100644index 00000000000..1b1bb59aa1a--- /dev/null+++ b/plugins/platforms/qqbot/register.py@@ -0,0 +1,204 @@+"""QQ Bot platform plugin: env/YAML seeding, interactive setup, and registry entry.++The adapter stays in ``adapter.py``. This module is the only thing ``__init__``+exports, so importing the package registers the platform and does not open a portal+connection.+"""++from __future__ import annotations++from typing import Any, Optional++from gateway.platforms._shared import apply_yaml_bridge, get_scoped_secret++from .adapter import QQAdapter, check_qq_requirements+from .constants import MAX_MESSAGE_LENGTH++_PLATFORM_HINT = (+ "You are on QQ, a popular Chinese messaging platform. QQ supports markdown formatting "+ "and emoji. You can send media files natively: include MEDIA:/absolute/path/to/file in "+ "your response. Images are sent as native photos, and other files arrive as downloadable documents."+)++_YAML_BRIDGE = (+ ("app_id", "QQ_APP_ID", "str"),+ ("client_secret", "QQ_CLIENT_SECRET", "str"),+ ("allow_from", "QQ_ALLOWED_USERS", "csv"),+ ("group_allow_from", "QQ_GROUP_ALLOWED_USERS", "csv"),+ ("markdown_support", "QQ_MARKDOWN_SUPPORT", "lower"),+)+_YAML_EXTRA_KEYS = ("dm_policy", "group_policy", "group_allowed_chats", "stt", "sandbox")+++def _scoped(name: str) -> str:+ return str(get_scoped_secret(name, "") or "").strip()+++def _truthy(raw: str) -> bool:+ return raw.lower() in {"1", "true", "yes", "on"}+++def _credentials_configured(extra: Optional[dict] = None) -> bool:+ extra = extra or {}+ app_id = str(extra.get("app_id") or "").strip() or _scoped("QQ_APP_ID")+ secret = str(extra.get("client_secret") or "").strip() or _scoped("QQ_CLIENT_SECRET")+ return bool(app_id and secret)+++def env_enablement() -> Optional[dict]:+ """Seed ``platforms.qqbot.extra`` from the profile's QQ env. ``None`` when the bot+ is not configured, so importing the plugin never enables a connect loop."""+ if not _credentials_configured():+ return None+ seed: dict[str, Any] = {"app_id": _scoped("QQ_APP_ID"), "client_secret": _scoped("QQ_CLIENT_SECRET")}+ if allow := _scoped("QQ_ALLOWED_USERS"):+ seed["allow_from"] = allow+ if groups := _scoped("QQ_GROUP_ALLOWED_USERS"):+ seed["group_allow_from"] = groups+ if markdown := _scoped("QQ_MARKDOWN_SUPPORT"):+ seed["markdown_support"] = _truthy(markdown)+ chat_id = _scoped("QQBOT_HOME_CHANNEL") or _scoped("QQ_HOME_CHANNEL")+ name = _scoped("QQBOT_HOME_CHANNEL_NAME") or _scoped("QQ_HOME_CHANNEL_NAME")+ thread_id = _scoped("QQBOT_HOME_CHANNEL_THREAD_ID") or _scoped("QQ_HOME_CHANNEL_THREAD_ID")+ if chat_id:+ home = {"chat_id": chat_id, "name": name or "Home"}+ if thread_id:+ home["thread_id"] = thread_id+ seed["home_channel"] = home+ return seed+++def apply_yaml_config(_yaml_cfg: dict, platform_cfg: dict) -> Optional[dict]:+ if not isinstance(platform_cfg, dict):+ return None+ seeded = apply_yaml_bridge(platform_cfg, _YAML_BRIDGE) or {}+ for key in _YAML_EXTRA_KEYS:+ if key in platform_cfg:+ seeded[key] = platform_cfg[key]+ return seeded or None+++def is_connected(pconfig) -> bool:+ extra = getattr(pconfig, "extra", None) or {}+ return _credentials_configured(extra)+++async def standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None,+ force_document=False, caption=None):+ """Late-import the REST sender so cron delivery works without a live gateway process."""+ from .send import send_qqbot+ return await send_qqbot(+ pconfig, chat_id, message, media_files=media_files, caption=caption,+ thread_id=thread_id, force_document=force_document,+ )+++def setup_qqbot() -> None:+ """Interactive setup: scan-to-configure or manual App ID / App Secret."""+ from hermes_cli.gateway_setup_wizard import (+ _confirm_reconfigure, _gw, _offer_home_channel, _print_setup_header, _prompt_csv, _save_env_values,+ )++ _print_setup_header("🐧 QQ Bot")+ if not _confirm_reconfigure("QQ Bot", "QQ_APP_ID", "QQ_CLIENT_SECRET"):+ return++ print()+ method_choices = [+ "Scan QR code to add bot automatically (recommended)",+ "Enter existing App ID and App Secret manually",+ ]+ credentials = None+ if _gw().prompt_choice(" How would you like to set up QQ Bot?", method_choices, 0) == 0:+ try:+ from .onboard import qr_register+ credentials = qr_register()+ except KeyboardInterrupt:+ print()+ _gw().print_warning(" QQ Bot setup cancelled.")+ return+ if not credentials:+ _gw().print_info(" QR setup did not complete. Continuing with manual input.")++ if not credentials:+ print()+ _gw()._print_info_lines(+ " Go to https://q.qq.com to register a QQ Bot application.",+ " Note your App ID and App Secret from the application page.",+ )+ print()+ app_id = _gw().prompt(" App ID", password=False)+ if not app_id:+ _gw().print_warning(" Skipped — QQ Bot won't work without an App ID.")+ return+ app_secret = _gw().prompt(" App Secret", password=True)+ if not app_secret:+ _gw().print_warning(" Skipped — QQ Bot won't work without an App Secret.")+ return+ credentials = {"app_id": app_id.strip(), "client_secret": app_secret.strip(), "user_openid": ""}++ _gw().save_env_value("QQ_APP_ID", credentials["app_id"])+ _gw().save_env_value("QQ_CLIENT_SECRET", credentials["client_secret"])+ user_openid = credentials.get("user_openid", "")++ print()+ access_choices = [+ "Use DM pairing approval (recommended)",+ "Allow all direct messages",+ "Only allow listed user OpenIDs",+ ]+ access_idx = _gw().prompt_choice(" How should direct messages be authorized?", access_choices, 0)+ if access_idx == 0:+ _gw().save_env_value("QQ_ALLOW_ALL_USERS", "false")+ allowed = ""+ if user_openid:+ print()+ if _gw().prompt_yes_no(f" Add yourself ({user_openid}) to the allow list?", True):+ allowed = user_openid+ _gw().print_success(f" Allow list set to {user_openid}")+ _gw().save_env_value("QQ_ALLOWED_USERS", allowed)+ _gw().print_success(" DM pairing enabled.")+ _gw().print_info(" Unknown users can request access; approve with `hermes pairing approve`.")+ elif access_idx == 1:+ _save_env_values(QQ_ALLOW_ALL_USERS="true", QQ_ALLOWED_USERS="")+ _gw().print_warning(" Open DM access enabled for QQ Bot.")+ else:+ allowlist = _prompt_csv(" Allowed user OpenIDs (comma-separated)", user_openid or "")+ _save_env_values(QQ_ALLOW_ALL_USERS="false", QQ_ALLOWED_USERS=allowlist)+ _gw().print_success(" Allowlist saved.")++ print()+ if user_openid:+ _offer_home_channel("QQBOT_HOME_CHANNEL", user_openid, "your QQ user ID")+ else:+ home_channel = _gw().prompt(" Home channel OpenID (for cron/notifications, or empty)", password=False)+ if home_channel:+ _gw().save_env_value("QQBOT_HOME_CHANNEL", home_channel.strip())+ _gw().print_success(f" Home channel set to {home_channel.strip()}")++ print()+ _gw().print_success("🐧 QQ Bot configured!")+ _gw().print_info(f" App ID: {credentials['app_id']}")+++def register(ctx) -> None:+ ctx.register_platform(+ name="qqbot",+ label="QQ Bot",+ adapter_factory=QQAdapter,+ check_fn=check_qq_requirements,+ validate_config=is_connected,+ is_connected=is_connected,+ required_env=["QQ_APP_ID", "QQ_CLIENT_SECRET"],+ install_hint="aiohttp and httpx are required. Run: hermes pm repair",+ setup_fn=setup_qqbot,+ allowed_users_env="QQ_ALLOWED_USERS",+ allow_all_env="QQ_ALLOW_ALL_USERS",+ max_message_length=MAX_MESSAGE_LENGTH,+ emoji="🐧",+ platform_hint=_PLATFORM_HINT,+ env_enablement_fn=env_enablement,+ apply_yaml_config_fn=apply_yaml_config,+ cron_deliver_env_var="QQBOT_HOME_CHANNEL",+ standalone_sender_fn=standalone_send,+ )diff --git a/plugins/platforms/qqbot/send.py b/plugins/platforms/qqbot/send.pynew file mode 100644index 00000000000..5c594fe346b--- /dev/null+++ b/plugins/platforms/qqbot/send.py@@ -0,0 +1,253 @@+"""Out-of-process QQ Bot sender (cron / CLI). Text tries guild, then C2C, then group.+Media uploads through C2C then group; guild channels have no native media path.+"""++from __future__ import annotations++import logging+import os+import time++from tools.send_message_senders import (+ _AUDIO_EXTS, _IMAGE_EXTS, _VIDEO_EXTS, _VOICE_EXTS, _error, _success)++logger = logging.getLogger("tools.send_message_tool")+++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 .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 .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 .chunked_upload import ChunkedUploader+ from .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 .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 .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, *,+ thread_id=None, force_document=False):+ """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:+ return _error("QQBot direct send requires httpx. Run: hermes pm repair")++ # Profile-scoped lookup so a multiplex profile never borrows another's QQ credentials.+ from gateway.platforms._shared import get_scoped_secret+ from .constants import FILE_UPLOAD_TIMEOUT+ extra = pconfig.extra or {}+ appid = extra.get("app_id") or get_scoped_secret("QQ_APP_ID", "")+ secret = pconfig.token or extra.get("client_secret") or get_scoped_secret("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=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:+ return _error(f"QQBot token request failed: {token_resp.status_code}")+ access_token = token_resp.json().get("access_token")+ if not access_token:+ return _error("QQBot: no access_token in response")++ headers = {"Authorization": f"QQBot {access_token}", "Content-Type": "application/json"}++ # --- Media path (#37315) ---+ if media_files:+ last_result = None+ text = (message or "").strip()+ warnings: list[str] = []+ 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"}:+ warnings.append(f"QQBot media file not found, skipping: {media_path}")+ logger.warning(warnings[-1])+ 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"):+ # Media failure must not discard the send (main degraded to text ++ # omission warning): collect it and keep delivering.+ warnings.append(result["error"])+ logger.warning("QQBot media delivery failed, omitting attachment: %s",+ result["error"])+ continue+ last_result = result++ if last_result is None:+ # Nothing was deliverable (caption rides the media, which all failed):+ # degrade to the text alone, as the pre-media generic path did.+ fallback_text = text or (caption or "").strip()+ if not fallback_text:+ return {"error": "QQBot: no deliverable media attachments",+ **({"warnings": warnings} if warnings else {})}+ text_result = await _qqbot_send_text_message(client, headers, chat_id, fallback_text)+ if isinstance(text_result, dict) and text_result.get("error"):+ return {**text_result, **({"warnings": warnings} if warnings else {})}+ last_result = text_result+ if warnings and isinstance(last_result, dict):+ last_result["warnings"] = [*last_result.get("warnings", []), *warnings]+ 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}")+++++# Tests and older call sites use this name.+_send_qqbot = send_qqbotdiff --git a/gateway/platforms/qqbot/utils.py b/plugins/platforms/qqbot/utils.pysimilarity index 100%rename from gateway/platforms/qqbot/utils.pyrename to plugins/platforms/qqbot/utils.pydiff --git a/tests/gateway/test_access_policy_mixin.py b/tests/gateway/test_access_policy_mixin.pyindex 7288c89779b..f383fa19f25 100644--- a/tests/gateway/test_access_policy_mixin.py+++ b/tests/gateway/test_access_policy_mixin.py@@ -29,7 +29,7 @@ def _scope(secrets):def _hosts():"""One bare instance per own-policy class, attributes set exactly as the adapters do."""- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterfrom plugins.platforms.weixin.adapter import WeixinAdapterfrom plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapterfrom gateway.platforms.whatsapp_common import WhatsAppBehaviorMixindiff --git a/tests/gateway/test_adapter_authz_secret_scope.py b/tests/gateway/test_adapter_authz_secret_scope.pyindex d6be4669b87..64f7780ea0e 100644--- a/tests/gateway/test_adapter_authz_secret_scope.py+++ b/tests/gateway/test_adapter_authz_secret_scope.py@@ -98,7 +98,7 @@ _GATES = [lambda: _email()._sender_accepted("[email protected]", {"sender_authenticated": True}),False, True),("qqbot.open_dm", {"QQ_ALLOW_ALL_USERS": "true"},- lambda: __import__("gateway.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter._open_dm_opted_in(object.__new__(__import__("gateway.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter)),+ lambda: __import__("plugins.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter._open_dm_opted_in(object.__new__(__import__("plugins.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter)),False, True),("whatsapp.open_dm", {"GATEWAY_ALLOW_ALL_USERS": "true"},lambda: __import__("gateway.platforms.whatsapp_common", fromlist=["WhatsAppBehaviorMixin"]).WhatsAppBehaviorMixin._open_dm_opted_in(_whatsapp()),diff --git a/tests/gateway/test_config_driven_access_policy.py b/tests/gateway/test_config_driven_access_policy.pyindex d0a7fe07ffd..718178e7b92 100644--- a/tests/gateway/test_config_driven_access_policy.py+++ b/tests/gateway/test_config_driven_access_policy.py@@ -111,7 +111,7 @@ def test_base_adapter_defaults_to_not_owning_access_policy():("plugins.platforms.wecom.adapter", "WeComAdapter"),("plugins.platforms.weixin.adapter", "WeixinAdapter"),("gateway.platforms.yuanbao", "YuanbaoAdapter"),- ("gateway.platforms.qqbot.adapter", "QQAdapter"),+ ("plugins.platforms.qqbot.adapter", "QQAdapter"),("plugins.platforms.whatsapp.adapter", "WhatsAppAdapter"),],)@@ -245,7 +245,7 @@ def test_own_policy_open_group_not_authorized_without_allowlist(monkeypatch, pla("plugins.platforms.whatsapp.adapter", "WhatsAppAdapter", "_is_dm_allowed"),("plugins.platforms.wecom.adapter", "WeComAdapter", "_is_dm_allowed"),("plugins.platforms.weixin.adapter", "WeixinAdapter", "_is_dm_allowed"),- ("gateway.platforms.qqbot.adapter", "QQAdapter", "_is_dm_allowed"),+ ("plugins.platforms.qqbot.adapter", "QQAdapter", "_is_dm_allowed"),],)def test_pairing_dm_policy_strict_intake_auth_denies_unknown(diff --git a/tests/gateway/test_qqbot.py b/tests/gateway/test_qqbot.pyindex df6b436fd8a..92f6d529037 100644--- a/tests/gateway/test_qqbot.py+++ b/tests/gateway/test_qqbot.py@@ -32,7 +32,7 @@ def _make_config(**extra):class TestQQAdapterInit:def _make(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))@@ -62,7 +62,7 @@ class TestQQAdapterInit:class TestCoerceList:def _fn(self, value):- from gateway.platforms.qqbot import _coerce_list+ from plugins.platforms.qqbot.utils import coerce_list as _coerce_listreturn _coerce_list(value)def test_none(self):@@ -78,7 +78,7 @@ class TestCoerceList:class TestIsVoiceContentType:def _fn(self, content_type, filename):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter._is_voice_content_type(content_type, filename)@@ -95,15 +95,15 @@ class TestIsVoiceContentType:class TestVoiceAttachmentSSRFProtection:def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))def test_connect_uses_redirect_guard_hook(self):- from gateway.platforms.qqbot import QQAdapter, _ssrf_redirect_guard+ from plugins.platforms.qqbot.adapter import QQAdapter, _ssrf_redirect_guardclient = mock.AsyncMock()- with mock.patch("gateway.platforms.qqbot.adapter.httpx.AsyncClient", return_value=client) as async_client_cls:+ with mock.patch("plugins.platforms.qqbot.adapter.httpx.AsyncClient", return_value=client) as async_client_cls:adapter = QQAdapter(_make_config(app_id="a", client_secret="b"))adapter._ensure_token = mock.AsyncMock(side_effect=RuntimeError("stop after client creation"))@@ -122,7 +122,7 @@ class TestVoiceAttachmentSSRFProtection:class TestVoiceAttachmentTempCleanup:def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))def _setup_download_mocks(self, adapter, content=b"RIFFmock-wav-audio-data"):@@ -166,7 +166,7 @@ class TestVoiceAttachmentTempCleanup:class TestQQWebSocketProxy:@pytest.mark.asyncioasync def test_open_ws_honors_proxy_env(self, monkeypatch):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterfor key in ("WSS_PROXY",@@ -196,7 +196,7 @@ class TestQQWebSocketProxy:seen_ws_kwargs.update(kwargs)return mock.AsyncMock(closed=False)- with mock.patch("gateway.platforms.qqbot.adapter.aiohttp.ClientSession", side_effect=FakeSession):+ with mock.patch("plugins.platforms.qqbot.adapter.aiohttp.ClientSession", side_effect=FakeSession):await adapter._open_ws("wss://api.sgroup.qq.com/websocket")assert seen_session_kwargs.get("trust_env") is True@@ -208,7 +208,7 @@ class TestQQWebSocketProxy:class TestStripAtMention:def _fn(self, content):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter._strip_at_mention(content)def test_removes_mention(self):@@ -222,7 +222,7 @@ class TestStripAtMention:class TestDmAllowed:def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))@@ -244,7 +244,7 @@ class TestDmAllowed:class TestGroupAllowed:def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))@@ -265,7 +265,7 @@ class TestGroupAllowed:class TestResolveSTTConfig:def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))def test_no_config(self):@@ -312,7 +312,7 @@ class TestResolveSTTConfig:class TestDispatchPayload:def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapteradapter = QQAdapter(_make_config(**extra))return adapter@@ -337,7 +337,7 @@ class TestDispatchPayload:class TestReadyHandling:def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))def test_ready_stores_session(self):@@ -356,7 +356,7 @@ class TestReadyHandling:class TestParseJson:def _fn(self, raw):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter._parse_json(raw)@@ -371,7 +371,7 @@ class TestParseJson:class TestBuildTextBody:def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))def test_plain_text(self):@@ -395,7 +395,7 @@ class TestWaitForReconnection:"""Test that send() waits for reconnection instead of silently dropping."""def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(**extra))@pytest.mark.asyncio@@ -439,13 +439,13 @@ class TestQQTimeoutErrorNormalization:delivery plain-text fallback."""def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b", **extra))@pytest.mark.asyncioasync def test_send_chunk_preserves_read_timeout_type(self, monkeypatch):from gateway.platforms.base import BasePlatformAdapter- import gateway.platforms.qqbot.adapter as qq_adapter_mod+ import plugins.platforms.qqbot.adapter as qq_adapter_mod# Skip the real 1s+2s retry backoff.monkeypatch.setattr(qq_adapter_mod.asyncio, "sleep", mock.AsyncMock())@@ -477,7 +477,7 @@ class TestQQTimeoutErrorNormalization:class TestChunkedUploadHelpers:def test_read_chunk_short_read_raises(self, tmp_path):- from gateway.platforms.qqbot.chunked_upload import _read_file_chunk+ from plugins.platforms.qqbot.chunked_upload import _read_file_chunkf = tmp_path / "x.bin"f.write_bytes(b"hi")with pytest.raises(IOError):@@ -485,7 +485,7 @@ class TestChunkedUploadHelpers:def test_parse_prepare_response_wrapped_in_data(self):- from gateway.platforms.qqbot.chunked_upload import _parse_prepare_response+ from plugins.platforms.qqbot.chunked_upload import _parse_prepare_responseraw = {"data": {"upload_id": "uid-42",@@ -516,7 +516,7 @@ class TestChunkedUploaderFlow:@pytest.mark.asyncioasync def test_full_upload_two_parts_success(self, tmp_path):- from gateway.platforms.qqbot.chunked_upload import ChunkedUploader+ from plugins.platforms.qqbot.chunked_upload import ChunkedUploader# Two-part file.f = tmp_path / "vid.mp4"@@ -583,7 +583,7 @@ class TestChunkedUploaderFlow:@pytest.mark.asyncioasync def test_group_paths(self, tmp_path):"""Group uploads hit /v2/groups/... instead of /v2/users/..."""- from gateway.platforms.qqbot.chunked_upload import ChunkedUploader+ from plugins.platforms.qqbot.chunked_upload import ChunkedUploaderf = tmp_path / "a.bin"f.write_bytes(b"x" * 100)@@ -628,27 +628,27 @@ class TestChunkedUploaderFlow:class TestApprovalButtonData:def test_parse_allow_once(self):- from gateway.platforms.qqbot.keyboards import parse_approval_button_data+ from plugins.platforms.qqbot.keyboards import parse_approval_button_dataresult = parse_approval_button_data("approve:agent:main:qqbot:c2c:UID:allow-once")assert result == ("agent:main:qqbot:c2c:UID", "allow-once")def test_parse_empty_returns_none(self):- from gateway.platforms.qqbot.keyboards import parse_approval_button_data+ from plugins.platforms.qqbot.keyboards import parse_approval_button_dataassert parse_approval_button_data("") is Noneassert parse_approval_button_data(None) is None # type: ignore[arg-type]class TestUpdatePromptButtonData:def test_parse_yes(self):- from gateway.platforms.qqbot.keyboards import parse_update_prompt_button_data+ from plugins.platforms.qqbot.keyboards import parse_update_prompt_button_dataassert parse_update_prompt_button_data("update_prompt:y") == "y"class TestBuildApprovalKeyboard:def test_button_data_embeds_session_key(self):- from gateway.platforms.qqbot.keyboards import build_approval_keyboard+ from plugins.platforms.qqbot.keyboards import build_approval_keyboardkb = build_approval_keyboard("agent:main:qqbot:c2c:UID")datas = [b.action.data for b in kb.content.rows[0].buttons]assert datas[0] == "approve:agent:main:qqbot:c2c:UID:allow-once"@@ -662,7 +662,7 @@ class TestBuildApprovalText:def test_truncates_long_commands(self):- from gateway.platforms.qqbot.keyboards import (+ from plugins.platforms.qqbot.keyboards import (ApprovalRequest, build_approval_text,)long = "x" * 1000@@ -679,7 +679,7 @@ class TestBuildApprovalText:class TestInteractionEventParsing:def test_parse_c2c_interaction(self):- from gateway.platforms.qqbot.keyboards import parse_interaction_event+ from plugins.platforms.qqbot.keyboards import parse_interaction_eventraw = {"id": "interaction-42","chat_type": 2,@@ -706,7 +706,7 @@ class TestAdapterInteractionDispatch:"""End-to-end verification of _on_interaction including ACK + callback."""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))@pytest.mark.asyncio@@ -752,7 +752,7 @@ class TestProcessQuotedContext:"""Verify the quoted-message pipeline: text + voice STT + images + files."""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))@pytest.mark.asyncio@@ -836,7 +836,7 @@ class TestDefaultInteractionDispatch:"""Verify the adapter's default INTERACTION_CREATE router."""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))def test_default_callback_installed_on_init(self):@@ -863,7 +863,7 @@ class TestDefaultInteractionDispatch:orig = tools.approval.resolve_gateway_approvaltools.approval.resolve_gateway_approval = fake_resolvetry:- from gateway.platforms.qqbot.keyboards import parse_interaction_event+ from plugins.platforms.qqbot.keyboards import parse_interaction_eventevent = parse_interaction_event({"id": "i","chat_type": 2,@@ -890,7 +890,7 @@ class TestDefaultInteractionDispatch:orig = tools.approval.resolve_gateway_approvaltools.approval.resolve_gateway_approval = fake_resolvetry:- from gateway.platforms.qqbot.keyboards import parse_interaction_event+ from plugins.platforms.qqbot.keyboards import parse_interaction_eventevent = parse_interaction_event({"id": "i", "chat_type": 1,"group_openid": "g-1",@@ -914,7 +914,7 @@ class TestDefaultInteractionDispatch:lambda: hermes_home,)- from gateway.platforms.qqbot.keyboards import parse_interaction_event+ from plugins.platforms.qqbot.keyboards import parse_interaction_eventevent = parse_interaction_event({"id": "i", "chat_type": 2, "user_openid": "u-1","data": {"resolved": {"button_data": "update_prompt:y"}},@@ -938,12 +938,12 @@ class TestProfileNamespaceApprovalAuthz:"""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))@staticmethoddef _parse(key):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter._parse_gateway_session_key(key)def test_parse_accepts_named_profile_namespace(self):@@ -982,7 +982,7 @@ class TestProfileNamespaceApprovalAuthz:orig = tools.approval.resolve_gateway_approvaltools.approval.resolve_gateway_approval = fake_resolvetry:- from gateway.platforms.qqbot.keyboards import parse_interaction_event+ from plugins.platforms.qqbot.keyboards import parse_interaction_eventevent = parse_interaction_event({"id": "i","chat_type": 2,@@ -1010,7 +1010,7 @@ class TestProfileNamespaceApprovalAuthz:orig = tools.approval.resolve_gateway_approvaltools.approval.resolve_gateway_approval = fake_resolvetry:- from gateway.platforms.qqbot.keyboards import parse_interaction_event+ from plugins.platforms.qqbot.keyboards import parse_interaction_eventevent = parse_interaction_event({"id": "i", "chat_type": 1,"group_openid": "g-1",@@ -1038,7 +1038,7 @@ class TestProfileNamespaceApprovalAuthz:orig = tools.approval.resolve_gateway_approvaltools.approval.resolve_gateway_approval = fake_resolvetry:- from gateway.platforms.qqbot.keyboards import parse_interaction_event+ from plugins.platforms.qqbot.keyboards import parse_interaction_eventevent = parse_interaction_event({"id": "i", "chat_type": 1,"group_openid": "g-1",@@ -1058,7 +1058,7 @@ class TestSendUpdatePrompt:"""Verify the cross-adapter send_update_prompt signature + behaviour."""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))@pytest.mark.asyncio@@ -1099,7 +1099,7 @@ class TestIdentifyIntents:"""Verify the WebSocket identify payload includes the INTERACTION intent bit."""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))@pytest.mark.asyncio@@ -1139,7 +1139,7 @@ class TestProcessAttachmentsPathExposure:"""Verify that video and file attachments include the cached local path."""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))@pytest.mark.asyncio@@ -1178,7 +1178,7 @@ class TestOp7ServerReconnect:"""Verify op 7 triggers WS close (which triggers reconnect in outer loop)."""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))def test_op7_closes_websocket(self):@@ -1206,7 +1206,7 @@ class TestOp9InvalidSession:"""Verify op 9 handles resumable vs non-resumable sessions."""def _make_adapter(self):- from gateway.platforms.qqbot.adapter import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b"))@@ -1243,7 +1243,7 @@ class TestReadEventsClosedWsGuard:busy-looping at 100% CPU (issues #31193 / #31771)."""def _make_adapter(self, **extra):- from gateway.platforms.qqbot import QQAdapter+ from plugins.platforms.qqbot.adapter import QQAdapterreturn QQAdapter(_make_config(app_id="a", client_secret="b", **extra))def test_read_events_raises_when_ws_closed_on_entry(self):diff --git a/tests/gateway/test_qqbot_credential_isolation.py b/tests/gateway/test_qqbot_credential_isolation.pyindex 5723ba03f6d..3330b2dcdca 100644--- a/tests/gateway/test_qqbot_credential_isolation.py+++ b/tests/gateway/test_qqbot_credential_isolation.py@@ -17,7 +17,7 @@ import pytestfrom agent import secret_scope as ssfrom gateway.config import PlatformConfig-from gateway.platforms.qqbot.adapter import QQAdapter+from plugins.platforms.qqbot.adapter import QQAdapter@pytest.fixture(autouse=True)diff --git a/tests/gateway/test_qqbot_scope_paths.py b/tests/gateway/test_qqbot_scope_paths.pyindex 30890e41d42..af906adceb3 100644--- a/tests/gateway/test_qqbot_scope_paths.py+++ b/tests/gateway/test_qqbot_scope_paths.py@@ -251,7 +251,7 @@ class TestDirectSendScope:@pytest.mark.asyncioasync def test_scoped_credentials_win_over_environ(self, monkeypatch):- from tools.send_message_tool import _send_qqbot+ from plugins.platforms.qqbot.send import send_qqbot as _send_qqbotcaptured = []monkeypatch.setitem(sys.modules, "httpx", self._fake_httpx(captured))@@ -273,7 +273,7 @@ class TestDirectSendScope:@pytest.mark.asyncioasync def test_unscoped_falls_back_to_environ(self, monkeypatch):- from tools.send_message_tool import _send_qqbot+ from plugins.platforms.qqbot.send import send_qqbot as _send_qqbotcaptured = []monkeypatch.setitem(sys.modules, "httpx", self._fake_httpx(captured))diff --git a/tests/gateway/test_qqbot_update_prompt_key.py b/tests/gateway/test_qqbot_update_prompt_key.pyindex 812e2f3bac3..c05c2e343d0 100644--- a/tests/gateway/test_qqbot_update_prompt_key.py+++ b/tests/gateway/test_qqbot_update_prompt_key.py@@ -6,8 +6,8 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom gateway.config import Platform-from gateway.platforms.qqbot.adapter import QQAdapter-from gateway.platforms.qqbot.keyboards import InteractionEvent+from plugins.platforms.qqbot.adapter import QQAdapter+from plugins.platforms.qqbot.keyboards import InteractionEventfrom gateway.session import SessionSource, build_session_keydiff --git a/tests/gateway/test_shared_adapter_utils.py b/tests/gateway/test_shared_adapter_utils.pyindex cf3de304678..f6477691c1d 100644--- a/tests/gateway/test_shared_adapter_utils.py+++ b/tests/gateway/test_shared_adapter_utils.py@@ -49,7 +49,7 @@ def test_bounded_put_refreshes_and_caps():def test_dedup_sites_keep_their_own_window(monkeypatch):- from gateway.platforms.qqbot import constants as qq+ from plugins.platforms.qqbot import constants as qqfrom plugins.platforms.photon import adapter as photonfrom plugins.platforms.wecom import callback_adapter as wecom_cbdiff --git a/tests/plugins/platforms/test_qqbot_plugin.py b/tests/plugins/platforms/test_qqbot_plugin.pynew file mode 100644index 00000000000..fb73a47ecce--- /dev/null+++ b/tests/plugins/platforms/test_qqbot_plugin.py@@ -0,0 +1,104 @@+"""QQ Bot is a bundled platform plugin: env seeding and cron delivery, no live gateway."""++import pytest+++def _clear_qq(monkeypatch):+ for key in (+ "QQ_APP_ID", "QQ_CLIENT_SECRET", "QQ_ALLOWED_USERS", "QQ_GROUP_ALLOWED_USERS",+ "QQ_ALLOW_ALL_USERS", "QQBOT_HOME_CHANNEL", "QQBOT_HOME_CHANNEL_NAME",+ "QQBOT_HOME_CHANNEL_THREAD_ID", "QQ_HOME_CHANNEL", "QQ_HOME_CHANNEL_NAME",+ "QQ_HOME_CHANNEL_THREAD_ID", "QQ_MARKDOWN_SUPPORT", "QQ_PORTAL_HOST",+ ):+ monkeypatch.delenv(key, raising=False)+++def test_unconfigured_plugin_does_not_enable(monkeypatch):+ _clear_qq(monkeypatch)+ from plugins.platforms.qqbot.register import env_enablement++ assert env_enablement() is None+++def test_group_allowlist_and_home_seed(monkeypatch):+ _clear_qq(monkeypatch)+ monkeypatch.setenv("QQ_APP_ID", "app")+ monkeypatch.setenv("QQ_CLIENT_SECRET", "sec")+ monkeypatch.setenv("QQ_GROUP_ALLOWED_USERS", "group-1, group-2")+ monkeypatch.setenv("QQBOT_HOME_CHANNEL", "home-chat")+ monkeypatch.setenv("QQBOT_HOME_CHANNEL_NAME", "Lounge")+ monkeypatch.setenv("QQBOT_HOME_CHANNEL_THREAD_ID", "thread-9")+ monkeypatch.setenv("QQ_HOME_CHANNEL", "ignored")+ from plugins.platforms.qqbot.register import env_enablement++ seed = env_enablement()++ assert seed["app_id"] == "app"+ assert seed["group_allow_from"] == "group-1, group-2"+ assert seed["home_channel"] == {+ "chat_id": "home-chat", "name": "Lounge", "thread_id": "thread-9",+ }+++def test_qq_prefixed_home_channel_still_seeds(monkeypatch):+ _clear_qq(monkeypatch)+ monkeypatch.setenv("QQ_APP_ID", "app")+ monkeypatch.setenv("QQ_CLIENT_SECRET", "sec")+ monkeypatch.setenv("QQ_HOME_CHANNEL", "renamed-chat")+ monkeypatch.setenv("QQ_HOME_CHANNEL_THREAD_ID", "thread-2")+ from plugins.platforms.qqbot.register import env_enablement++ seed = env_enablement()++ assert seed["home_channel"] == {+ "chat_id": "renamed-chat", "name": "Home", "thread_id": "thread-2",+ }+++def test_qqbot_platform_hint_comes_from_the_builtin_table():+ from agent.prompt_builder import PLATFORM_HINTS+ from agent.system_prompt import _default_platform_hint++ assert "MEDIA:" in PLATFORM_HINTS["qqbot"]+ assert _default_platform_hint("qqbot") == PLATFORM_HINTS["qqbot"]+++def test_qqbot_is_a_builtin_deliver_target():+ """Webhook and cron treat qqbot as a shipped platform before any plugin load."""+ from cron.scheduler_delivery import (+ _is_known_delivery_platform,+ _resolve_home_env_var,+ _home_env_lookup,+ )+ from gateway.platforms.webhook import _is_known_platform++ assert _is_known_platform("qqbot") is True+ assert _is_known_delivery_platform("qqbot") is True+ assert _resolve_home_env_var("qqbot") == "QQBOT_HOME_CHANNEL"+++def test_qq_prefixed_home_env_still_resolves_for_cron(monkeypatch):+ monkeypatch.delenv("QQBOT_HOME_CHANNEL", raising=False)+ monkeypatch.setenv("QQ_HOME_CHANNEL", "renamed-chat")+ from cron.scheduler_delivery import _home_env_lookup++ assert _home_env_lookup("QQBOT_HOME_CHANNEL") == "renamed-chat"+++def test_cron_deliver_qqbot_without_a_live_gateway():+ from hermes_cli.plugins import discover_plugins+ discover_plugins()+ from cron.scheduler_delivery import _is_known_delivery_platform, _resolve_home_env_var++ assert _is_known_delivery_platform("qqbot") is True+ assert _resolve_home_env_var("qqbot") == "QQBOT_HOME_CHANNEL"+++async def test_standalone_sender_reports_missing_credentials(monkeypatch):+ _clear_qq(monkeypatch)+ from gateway.config import PlatformConfig+ from plugins.platforms.qqbot.register import standalone_send++ result = await standalone_send(PlatformConfig(enabled=True, extra={}), "chat-1", "hi")+ assert "QQ_APP_ID" in result["error"]diff --git a/tests/tools/test_qqbot_send_message_media.py b/tests/tools/test_qqbot_send_message_media.pyindex 2760f65e706..54b8efea6eb 100644--- a/tests/tools/test_qqbot_send_message_media.py+++ b/tests/tools/test_qqbot_send_message_media.py@@ -7,15 +7,16 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, patchfrom gateway.config import Platform-from gateway.platforms.qqbot.constants import (+from plugins.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+from plugins.platforms.qqbot.send import _qqbot_media_file_type+from plugins.platforms.qqbot.send import send_qqbot as _send_qqbot+from tools.send_message_tool import _send_to_platformdef _pconfig():@@ -47,16 +48,17 @@ class TestSendToPlatformQqbotMediaRouting:img.write_bytes(b"\x89PNG\r\n\x1a\n")media = [(str(img), False)]+ mock_send = AsyncMock(+ return_value={+ "success": True,+ "platform": "qqbot",+ "chat_id": "openid-1",+ }+ )with patch(- "tools.send_message_tool._send_qqbot",- new=AsyncMock(- return_value={- "success": True,- "platform": "qqbot",- "chat_id": "openid-1",- }- ),- ) as mock_send:+ "tools.send_message_tool._plugin_standalone_sender",+ return_value=(mock_send, None),+ ):result = asyncio.run(_send_to_platform(Platform.QQBOT,@@ -77,12 +79,13 @@ class TestSendToPlatformQqbotMediaRouting:img.write_bytes(b"jpeg-bytes")media = [(str(img), False)]+ mock_send = AsyncMock(+ return_value={"success": True, "platform": "qqbot", "chat_id": "oid"}+ )with patch(- "tools.send_message_tool._send_qqbot",- new=AsyncMock(- return_value={"success": True, "platform": "qqbot", "chat_id": "oid"}- ),- ) as mock_send:+ "tools.send_message_tool._plugin_standalone_sender",+ return_value=(mock_send, None),+ ):result = asyncio.run(_send_to_platform(Platform.QQBOT,@@ -170,7 +173,7 @@ class TestSendQqbotMedia:)with patch.dict("sys.modules", {"httpx": _HttpxMod()}), patch(- "tools.send_message_senders._qqbot_deliver_one_media",+ "plugins.platforms.qqbot.send._qqbot_deliver_one_media",new=deliver,):result = asyncio.run(@@ -194,7 +197,7 @@ class TestSendQqbotMedia:assert str(img) in _argsdef test_deliver_one_media_falls_back_c2c_to_group(self, tmp_path):- from tools.send_message_senders import _qqbot_deliver_one_media+ from plugins.platforms.qqbot.send import _qqbot_deliver_one_mediaimg = tmp_path / "a.png"img.write_bytes(b"x")@@ -215,10 +218,10 @@ class TestSendQqbotMedia:return {"id": "mid-2"}with patch(- "tools.send_message_senders._qqbot_upload_local_file",+ "plugins.platforms.qqbot.send._qqbot_upload_local_file",new=AsyncMock(side_effect=_fake_upload_local),), patch(- "tools.send_message_senders._qqbot_send_media_message",+ "plugins.platforms.qqbot.send._qqbot_send_media_message",new=AsyncMock(side_effect=_fake_send_media),):result = asyncio.run(@@ -286,7 +289,7 @@ class TestQqbotMediaFailureFallsBackToText:return SimpleNamespace(status_code=200, json=lambda: {"id": "text-mid"})with patch.dict("sys.modules", {"httpx": _token_client(_post)}), patch(- "tools.send_message_senders._qqbot_deliver_one_media", new=AsyncMock(side_effect=_deliver)+ "plugins.platforms.qqbot.send._qqbot_deliver_one_media", new=AsyncMock(side_effect=_deliver)):result = asyncio.run(_send_qqbot(@@ -314,7 +317,7 @@ class TestQqbotMediaFailureFallsBackToText:return SimpleNamespace(status_code=200, json=lambda: {"id": "mid"})with patch.dict("sys.modules", {"httpx": _token_client(_post)}), patch(- "tools.send_message_senders._qqbot_deliver_one_media",+ "plugins.platforms.qqbot.send._qqbot_deliver_one_media",new=AsyncMock(return_value={"error": "QQBot media send failed: too large"}),):result = asyncio.run(@@ -336,7 +339,7 @@ class TestQqbotMediaFailureFallsBackToText:class TestQqbotSendMediaMessageBody:def test_body_uses_msg_type_media(self):- from tools.send_message_senders import _qqbot_send_media_message+ from plugins.platforms.qqbot.send import _qqbot_send_media_messagecaptured = {}@@ -347,7 +350,7 @@ class TestQqbotSendMediaMessageBody:return {"id": "x"}with patch(- "tools.send_message_senders._qqbot_api_json",+ "plugins.platforms.qqbot.send._qqbot_api_json",new=AsyncMock(side_effect=_fake_api),):asyncio.run(diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex 585ac0e0573..34ac093b5bd 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -566,11 +566,11 @@ plugins/platforms/ # plugin-packaged adapters (one dir each)├── irc/adapter.py # IRC (canonical scoped-lock example)├── bluebubbles/adapter.py # Apple iMessage via BlueBubbles macOS server├── weixin/adapter.py # Weixin (personal WeChat) via iLink Bot API+├── qqbot/ # QQ Bot (Tencent QQ) via Official API v2└── … # google_chat, ntfy, photon, raft, simplex, …gateway/platforms/ # core base + legacy direct adapters├── base.py # BasePlatformAdapter — shared logic for all platforms-├── qqbot/ # QQ Bot (Tencent QQ) via Official API v2 (sub-package)├── yuanbao.py # Yuanbao (Tencent) DM/group adapter├── msgraph_webhook.py # Microsoft Graph change-notification webhook (Teams, Outlook, etc.)├── webhook.py # Inbound/outbound webhook adapterdiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/architecture.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/architecture.mdindex dd72521a149..8085e38d676 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/architecture.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/architecture.md@@ -120,9 +120,9 @@ hermes-agent/│ └── platforms/ # 20 个适配器:telegram、discord、slack、whatsapp、│ # signal、matrix、mattermost、email、sms、│ # dingtalk、feishu、wecom、wecom_callback、weixin、-│ # bluebubbles、qqbot、webhook、api_server、-│ # yuanbao+│ # bluebubbles、webhook、api_server、yuanbao│+├── plugins/platforms/ # 随包平台插件:telegram、discord、feishu、qqbot 等├── acp_adapter/ # ACP 服务器(VS Code / Zed / JetBrains)├── cron/ # 调度器(jobs.py、scheduler.py)├── plugins/memory/ # 记忆提供者插件diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.mdindex 85861cdc4a3..98ccfb0a590 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md@@ -166,11 +166,11 @@ plugins/platforms/ # 插件打包的适配器(每个一个目├── irc/adapter.py # IRC(作用域锁的标准示例)├── bluebubbles/adapter.py # Apple iMessage(通过 BlueBubbles macOS 服务端)├── weixin/adapter.py # 微信(个人版,通过 iLink Bot API)+├── qqbot/ # QQ Bot(腾讯 QQ,通过官方 API v2)└── … # google_chat、ntfy、photon、raft、simplex 等gateway/platforms/ # 核心 base 与旧的直接适配器├── base.py # BasePlatformAdapter — 所有平台的共享逻辑-├── qqbot/ # QQ Bot(腾讯 QQ,通过官方 API v2,子包)├── yuanbao.py # 元宝(腾讯)私信/群组适配器├── msgraph_webhook.py # Microsoft Graph 变更通知 webhook(Teams、Outlook 等)├── webhook.py # 入站/出站 webhook 适配器