Skip to content

The agent that grows with you

refactor(qqbot): drop core wiring

cxyhhhhh57a81d030407
diff --git a/gateway/run.py b/gateway/run.py
index 45980e5f645..a16d3daa93a 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3325,8 +3325,6 @@ _BUILTIN_ADAPTERS: dict[Platform, tuple[str, str, str, str]] = {
"Webhook: aiohttp not installed"),
Platform.MSGRAPH_WEBHOOK: ("msgraph_webhook", "MSGraphWebhookAdapter", "check_msgraph_webhook_requirements",
"MSGraph webhook: aiohttp not installed"),
- Platform.QQBOT: ("qqbot", "QQAdapter", "check_qq_requirements",
- "QQBot: aiohttp/httpx missing or QQ_APP_ID/QQ_CLIENT_SECRET not configured"),
Platform.YUANBAO: ("yuanbao", "YuanbaoAdapter", "WEBSOCKETS_AVAILABLE",
"Yuanbao: websockets not installed. Run: pip install websockets")}
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index b2d37479e25..ddc9330b38f 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -4659,7 +4659,6 @@ from hermes_cli.gateway_setup_wizard import (
_clean_discord_ids,
_prompt_allowlist_var,
_setup_standard_platform,
- _setup_qqbot,
_builtin_setup_fn,
_configure_platform,
_wizard_offer_service_action,
diff --git a/hermes_cli/gateway_setup_wizard.py b/hermes_cli/gateway_setup_wizard.py
index c99648007b1..d010f71e59d 100644
--- a/hermes_cli/gateway_setup_wizard.py
+++ b/hermes_cli/gateway_setup_wizard.py
@@ -47,28 +47,6 @@ _PLATFORMS = [
"help": "off = flat channel messages, thread = replies nest under your message."},
],
},
- {
- "key": "qqbot", "label": "QQ Bot", "emoji": "🐧", "token_var": "QQ_APP_ID",
- "setup_instructions": [
- "1. Register a QQ Bot application at q.qq.com",
- "2. Note your App ID and App Secret from the application page",
- "3. Enable the required intents (C2C, Group, Guild messages)",
- "4. Configure sandbox or publish the bot",
- ],
- "vars": [
- {"name": "QQ_APP_ID", "prompt": "QQ Bot App ID", "password": False,
- "help": "Your QQ Bot App ID from q.qq.com."},
- {"name": "QQ_CLIENT_SECRET", "prompt": "QQ Bot App Secret", "password": True,
- "help": "Your QQ Bot App Secret from q.qq.com."},
- {"name": "QQ_ALLOWED_USERS",
- "prompt": "Allowed user OpenIDs (comma-separated, leave empty for open access)",
- "password": False, "is_allowlist": True,
- "help": "Optional β€” restrict DM access to specific user OpenIDs."},
- {"name": "QQBOT_HOME_CHANNEL",
- "prompt": "Home channel (user/group OpenID for cron delivery, or empty)", "password": False,
- "help": "OpenID to deliver cron results and notifications to."},
- ],
- },
{
"key": "yuanbao", "label": "Yuanbao", "emoji": "πŸ’Ž", "token_var": "YUANBAO_APP_ID",
"setup_instructions": [
@@ -354,83 +332,6 @@ def _setup_standard_platform(platform: dict):
_gw().print_success(f"{emoji} {label} configured!")
-def _setup_qqbot():
- """Interactive setup for QQ Bot β€” scan-to-configure or manual credentials."""
- _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 gateway.platforms.qqbot 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 _builtin_setup_fn(key: str):
@@ -439,7 +340,6 @@ def _builtin_setup_fn(key: str):
return {
# telegram/discord/slack/whatsapp/dingtalk/feishu/wecom setup_fns come from their plugins.
"webhooks": _gw().setup_platforms._setup_webhooks,
- "qqbot": _setup_qqbot,
}.get(key)
diff --git a/tools/send_message_senders.py b/tools/send_message_senders.py
index 71a6d5e9f8e..8a9668f6056 100644
--- a/tools/send_message_senders.py
+++ b/tools/send_message_senders.py
@@ -474,238 +474,6 @@ def _gateway_platform_module(name, *, unavailable, unmet):
-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:
- 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.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=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}")
-
-
async def _send_yuanbao(chat_id, message, media_files=None):
"""Send via the running Yuanbao adapter's persistent WebSocket (no throwaway client possible)."""
try:
diff --git a/tools/send_message_tool.py b/tools/send_message_tool.py
index 3ae1ff53a50..35ad0965356 100644
--- a/tools/send_message_tool.py
+++ b/tools/send_message_tool.py
@@ -18,7 +18,7 @@ from tools.send_message_senders import (
_AUDIO_EXTS, _DEFAULT_CAPTION_LIMIT, _IMAGE_EXTS, _NO_DELIVERABLE, _VIDEO_EXTS, _VOICE_EXTS,
_adapter_media_method, _error, _live_adapter, _media_caption_split, _plugin_standalone_sender,
_registry_standalone_send, _resolve_slack_user_target, _sanitize_error_text,
- _send_matrix_via_adapter, _send_qqbot, _send_telegram, _send_yuanbao)
+ _send_matrix_via_adapter, _send_telegram, _send_yuanbao)
from tools.registry import tool_error
# NOTE: ``send_message`` is intentionally NOT registered as an agent-callable model tool
@@ -617,6 +617,7 @@ def _platform_max_length(platform):
# WhatsApp: Baileys /send-media). platform -> (error label, run discover_plugins first,
# caption-capable, media_files sentinel for non-final chunks, forward force_document)
_PLUGIN_STANDALONE_MEDIA = {"discord": ("Discord", False, True, [], False), "feishu": ("Feishu", True, False, None, False),
+ "qqbot": ("QQ Bot", True, True, None, False),
"slack": ("Slack", True, True, [], False), "whatsapp": ("WhatsApp", True, True, None, True),
# Signal: attachments ride the JSON-RPC param on the final chunk.
"signal": ("Signal", True, False, [], False),
@@ -670,8 +671,7 @@ _CHUNKED_ROUTES = {
# warning). Signature: (pconfig, chat_id, chunk, thread_id) -> result.
_TEXT_SENDERS = {
**{name: partial(_registry_standalone_send, name)
- for name in ("whatsapp", "email", "sms", "dingtalk", "feishu", "wecom", "signal")},
- "qqbot": lambda pc, cid, chunk, tid: _send_qqbot(pc, cid, chunk),
+ for name in ("whatsapp", "email", "sms", "dingtalk", "feishu", "wecom", "signal", "qqbot")},
"yuanbao": lambda pc, cid, chunk, tid: _send_yuanbao(cid, chunk)}
_MEDIA_PLATFORMS_NOTE = "telegram, discord, matrix, weixin, signal, yuanbao, feishu, whatsapp, slack and qqbot"
@@ -707,24 +707,6 @@ 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":