send.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """Out-of-process QQ Bot sender (cron / CLI). Text tries guild, then C2C, then group.
  2. Media uploads through C2C then group; guild channels have no native media path.
  3. """
  4. from __future__ import annotations
  5. import asyncio
  6. import logging
  7. import os
  8. import time
  9. from tools.send_message_senders import (
  10. _AUDIO_EXTS, _IMAGE_EXTS, _VIDEO_EXTS, _VOICE_EXTS, _error, _success)
  11. logger = logging.getLogger("tools.send_message_tool")
  12. def _qqbot_media_file_type(media_path: str, is_voice: bool) -> int:
  13. """Map a local path / voice flag to QQ Bot ``file_type`` constants."""
  14. from .constants import (
  15. MEDIA_TYPE_FILE, MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, MEDIA_TYPE_VOICE)
  16. ext = os.path.splitext(media_path)[1].lower()
  17. if is_voice or ext in _VOICE_EXTS:
  18. return MEDIA_TYPE_VOICE
  19. if ext in _IMAGE_EXTS:
  20. return MEDIA_TYPE_IMAGE
  21. if ext in _VIDEO_EXTS:
  22. return MEDIA_TYPE_VIDEO
  23. if ext in _AUDIO_EXTS:
  24. return MEDIA_TYPE_VOICE
  25. return MEDIA_TYPE_FILE
  26. async def _qqbot_api_json(client, headers: dict, method: str, path: str,
  27. body: dict | None = None, *, timeout: float = 30.0) -> dict:
  28. """POST/GET JSON against ``api.sgroup.qq.com``; raise RuntimeError on failure."""
  29. from .constants import API_BASE
  30. resp = await client.request(method, f"{API_BASE}{path}", json=body, headers=headers, timeout=timeout)
  31. try:
  32. data = resp.json() if resp.content else {}
  33. except Exception:
  34. data = {}
  35. if resp.status_code >= 400:
  36. raise RuntimeError(
  37. f"QQ Bot API error [{resp.status_code}] {path}: "
  38. f"{data.get('message', data) or resp.text[:200]}")
  39. return data if isinstance(data, dict) else {}
  40. async def _qqbot_upload_local_file(client, headers, chat_type, chat_id, media_path, file_type) -> dict:
  41. """Chunked-upload a local file; returns the ``/files`` complete response."""
  42. from pathlib import Path as _Path
  43. from .chunked_upload import ChunkedUploader
  44. from .constants import FILE_UPLOAD_TIMEOUT
  45. local_path = _Path(media_path).expanduser()
  46. if not local_path.is_absolute():
  47. local_path = (_Path.cwd() / local_path).resolve()
  48. if not local_path.exists() or not local_path.is_file():
  49. raise FileNotFoundError(f"Media file not found: {local_path}")
  50. async def _api_request(method, path, body=None, timeout=FILE_UPLOAD_TIMEOUT):
  51. return await _qqbot_api_json(client, headers, method, path, body, timeout=timeout)
  52. uploader = ChunkedUploader(api_request=_api_request, http_put=client.put, log_tag="send_message.qqbot")
  53. return await uploader.upload(
  54. chat_type=chat_type, target_id=chat_id, file_path=str(local_path),
  55. file_type=file_type, file_name=local_path.name)
  56. async def _qqbot_upload_url(client, headers, chat_type, chat_id, url, file_type,
  57. file_name=None) -> dict:
  58. """Ask QQ to fetch ``url`` into the media store; returns upload JSON."""
  59. from .constants import FILE_UPLOAD_TIMEOUT, MEDIA_TYPE_FILE
  60. path = f"/v2/users/{chat_id}/files" if chat_type == "c2c" else f"/v2/groups/{chat_id}/files"
  61. body = {"file_type": file_type, "srv_send_msg": False, "url": url}
  62. if file_type == MEDIA_TYPE_FILE and file_name:
  63. body["file_name"] = file_name
  64. return await _qqbot_api_json(client, headers, "POST", path, body, timeout=FILE_UPLOAD_TIMEOUT)
  65. def _qqbot_extract_file_info(upload: dict):
  66. if not isinstance(upload, dict):
  67. return None
  68. file_info = upload.get("file_info") or (upload.get("data") or {}).get("file_info")
  69. return file_info if file_info else None
  70. async def _qqbot_send_media_message(client, headers, chat_type, chat_id, file_info,
  71. caption=None) -> dict:
  72. """POST a RichMedia message referencing an uploaded ``file_info``."""
  73. from .constants import MAX_MESSAGE_LENGTH, MSG_TYPE_MEDIA
  74. path = f"/v2/users/{chat_id}/messages" if chat_type == "c2c" else f"/v2/groups/{chat_id}/messages"
  75. body = {"msg_type": MSG_TYPE_MEDIA, "media": {"file_info": file_info},
  76. "msg_seq": int(time.time() * 1000) % 1_000_000_000}
  77. if caption and caption.strip():
  78. body["content"] = caption.strip()[:MAX_MESSAGE_LENGTH]
  79. return await _qqbot_api_json(client, headers, "POST", path, body)
  80. async def _qqbot_send_text_message(client, headers, chat_id, message: str) -> dict:
  81. """Try channel → C2C → group text endpoints (pre-media standalone behavior)."""
  82. payload = {"content": (message or "")[:4000], "msg_type": 0}
  83. endpoints = (("channel", f"https://api.sgroup.qq.com/channels/{chat_id}/messages"),
  84. ("c2c", f"https://api.sgroup.qq.com/v2/users/{chat_id}/messages"),
  85. ("group", f"https://api.sgroup.qq.com/v2/groups/{chat_id}/messages"))
  86. statuses = []
  87. for kind, url in endpoints:
  88. resp = await client.post(url, json=payload, headers=headers)
  89. if resp.status_code in {200, 201}:
  90. return _success("qqbot", chat_id, message_id=resp.json().get("id"))
  91. statuses.append(f"{kind}={resp.status_code}")
  92. return _error(f"QQBot send failed: {' '.join(statuses)}")
  93. async def _qqbot_deliver_one_media(client, headers, chat_id, media_path, is_voice,
  94. caption=None) -> dict:
  95. """Upload one attachment and send it, trying C2C then group (no guild)."""
  96. from pathlib import Path as _Path
  97. from urllib.parse import urlparse
  98. file_type = _qqbot_media_file_type(media_path, is_voice)
  99. is_url = urlparse(str(media_path)).scheme in {"http", "https"}
  100. errors: list[str] = []
  101. for chat_type in ("c2c", "group"):
  102. try:
  103. if is_url:
  104. upload = await _qqbot_upload_url(
  105. client, headers, chat_type, chat_id, media_path, file_type,
  106. file_name=_Path(urlparse(media_path).path).name or "media")
  107. else:
  108. upload = await _qqbot_upload_local_file(
  109. client, headers, chat_type, chat_id, media_path, file_type)
  110. file_info = _qqbot_extract_file_info(upload)
  111. if not file_info:
  112. errors.append(f"{chat_type}: upload returned no file_info: {upload}")
  113. continue
  114. send_data = await _qqbot_send_media_message(
  115. client, headers, chat_type, chat_id, file_info, caption=caption)
  116. return _success("qqbot", chat_id, message_id=send_data.get("id"), chat_type=chat_type)
  117. except Exception as exc:
  118. errors.append(f"{chat_type}: {exc}")
  119. continue
  120. return _error(
  121. "QQBot media send failed (guild/channel native media is unsupported; "
  122. f"tried c2c and group): {'; '.join(errors)}")
  123. async def send_qqbot(pconfig, chat_id, message, media_files=None, caption=None, *,
  124. thread_id=None, force_document=False):
  125. """Send via the QQ Bot Open Platform REST API (no WebSocket needed).
  126. Guild channels, C2C (private) chats and groups are tried in order for text.
  127. When ``media_files`` is provided, each attachment is uploaded (C2C then
  128. group — guild has no native media upload path) and sent as a
  129. ``msg_type=MEDIA`` RichMedia message (#37315). Optional ``caption`` rides on
  130. the first media bubble; non-empty ``message`` is sent as a separate text
  131. message before the media.
  132. """
  133. try:
  134. import httpx
  135. except ImportError:
  136. return _error("QQBot direct send requires httpx. Run: hermes pm repair")
  137. # Profile-scoped lookup so a multiplex profile never borrows another's QQ credentials.
  138. from gateway.platforms._shared import get_scoped_secret
  139. from .constants import FILE_UPLOAD_TIMEOUT
  140. extra = pconfig.extra or {}
  141. appid = extra.get("app_id") or get_scoped_secret("QQ_APP_ID", "")
  142. secret = pconfig.token or extra.get("client_secret") or get_scoped_secret("QQ_CLIENT_SECRET", "")
  143. if not appid or not secret:
  144. return _error("QQBot: QQ_APP_ID / QQ_CLIENT_SECRET not configured.")
  145. media_files = media_files or []
  146. # Longer timeout when uploading; text-only stays snappy.
  147. client_timeout = FILE_UPLOAD_TIMEOUT if media_files else 15.0
  148. try:
  149. async with httpx.AsyncClient(timeout=client_timeout) as client:
  150. token_resp = await client.post("https://bots.qq.com/app/getAppAccessToken",
  151. json={"appId": str(appid), "clientSecret": str(secret)})
  152. if token_resp.status_code != 200:
  153. return _error(f"QQBot token request failed: {token_resp.status_code}")
  154. access_token = token_resp.json().get("access_token")
  155. if not access_token:
  156. return _error("QQBot: no access_token in response")
  157. headers = {"Authorization": f"QQBot {access_token}", "Content-Type": "application/json"}
  158. # --- Media path (#37315) ---
  159. if media_files:
  160. last_result = None
  161. text = (message or "").strip()
  162. warnings: list[str] = []
  163. if text and not (caption and caption.strip()):
  164. text_result = await _qqbot_send_text_message(client, headers, chat_id, text)
  165. if isinstance(text_result, dict) and text_result.get("error"):
  166. return text_result
  167. last_result = text_result
  168. for index, (media_path, is_voice) in enumerate(media_files):
  169. if not media_path:
  170. continue
  171. # Caption applies to the first bubble only (single-file
  172. # caption split already enforced by the caller).
  173. media_caption = caption if index == 0 else None
  174. if not await asyncio.to_thread(os.path.exists, media_path):
  175. from urllib.parse import urlparse as _urlparse
  176. if _urlparse(str(media_path)).scheme not in {"http", "https"}:
  177. warnings.append(f"QQBot media file not found, skipping: {media_path}")
  178. logger.warning(warnings[-1])
  179. continue
  180. result = await _qqbot_deliver_one_media(
  181. client, headers, chat_id, media_path, bool(is_voice), caption=media_caption)
  182. if isinstance(result, dict) and result.get("error"):
  183. # Media failure must not discard the send (main degraded to text +
  184. # omission warning): collect it and keep delivering.
  185. warnings.append(result["error"])
  186. logger.warning("QQBot media delivery failed, omitting attachment: %s",
  187. result["error"])
  188. continue
  189. last_result = result
  190. if last_result is None:
  191. # Nothing was deliverable (caption rides the media, which all failed):
  192. # degrade to the text alone, as the pre-media generic path did.
  193. fallback_text = text or (caption or "").strip()
  194. if not fallback_text:
  195. return {"error": "QQBot: no deliverable media attachments",
  196. **({"warnings": warnings} if warnings else {})}
  197. text_result = await _qqbot_send_text_message(client, headers, chat_id, fallback_text)
  198. if isinstance(text_result, dict) and text_result.get("error"):
  199. return {**text_result, **({"warnings": warnings} if warnings else {})}
  200. last_result = text_result
  201. if warnings and isinstance(last_result, dict):
  202. last_result["warnings"] = [*last_result.get("warnings", []), *warnings]
  203. return last_result
  204. # --- Text-only path: first 2xx wins (pre-media behavior) ---
  205. return await _qqbot_send_text_message(client, headers, chat_id, message or "")
  206. except Exception as e:
  207. logger.debug("QQBot standalone send failed", exc_info=True)
  208. return _error(f"QQBot send failed: {e}")