send_message_senders.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. """Standalone per-platform senders and error helpers for send_message."""
  2. from pm import install_hint
  3. import asyncio
  4. import contextlib
  5. import logging
  6. import os
  7. import re
  8. import time
  9. from agent.redact import redact_sensitive_text
  10. logger = logging.getLogger("tools.send_message_tool")
  11. _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
  12. _VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}
  13. _AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".m2a", ".wav", ".m4a", ".flac"}
  14. _VOICE_EXTS = {".ogg", ".opus"}
  15. _TELEGRAM_SEND_AUDIO_EXTS = {".mp3", ".m4a"} # sendAudio accepts only these; other audio -> sendVoice / document
  16. # Captionable on the media bubble; voice/audio notes excluded (a caption there reads as a separate label).
  17. _CAPTIONABLE_EXTS = _IMAGE_EXTS | _VIDEO_EXTS | {".pdf", ".doc", ".docx", ".txt", ".md", ".csv", ".xlsx", ".zip"}
  18. # Native caption limits (chars): Telegram caps photo/video at 1024; one conservative shared ceiling elsewhere.
  19. _TELEGRAM_CAPTION_LIMIT = 1024
  20. _DEFAULT_CAPTION_LIMIT = 4096
  21. def _media_caption_split(text, media_files, *, max_caption_len):
  22. """Single chokepoint deciding whether text rides on the media bubble as its caption:
  23. ``(caption, "")`` only for exactly one captionable file (not a voice/audio note) whose
  24. text fits ``max_caption_len``, else ``(None, text)`` — multi-file caption→file association
  25. is ambiguous. Length is codepoints (never under-counts Telegram's UTF-16 units for BMP
  26. text); the Telegram sender re-checks the *formatted* caption since escaping inflates it."""
  27. stripped = (text or "").strip()
  28. media = media_files or []
  29. if (not stripped or len(media) != 1 or len(stripped) > max_caption_len or media[0][1]
  30. or os.path.splitext(media[0][0])[1].lower() not in _CAPTIONABLE_EXTS):
  31. return None, text
  32. return stripped, ""
  33. _URL_SECRET_QUERY_RE = re.compile(
  34. r"([?&](?:access_token|api[_-]?key|auth[_-]?token|token|signature|sig)=)([^&#\s]+)", re.IGNORECASE)
  35. _GENERIC_SECRET_ASSIGN_RE = re.compile(
  36. r"\b(access_token|api[_-]?key|auth[_-]?token|signature|sig)\s*=\s*([^\s,;]+)", re.IGNORECASE)
  37. def _sanitize_error_text(text) -> str:
  38. """Redact secrets from error text before surfacing it to users/models."""
  39. redacted = _URL_SECRET_QUERY_RE.sub(lambda m: f"{m.group(1)}***", redact_sensitive_text(text))
  40. return _GENERIC_SECRET_ASSIGN_RE.sub(lambda m: f"{m.group(1)}=***", redacted)
  41. def _error(message: str) -> dict:
  42. """Build a standardized error payload with redacted content."""
  43. return {"error": _sanitize_error_text(message)}
  44. def _success(platform: str, chat_id, warnings=None, **fields) -> dict:
  45. """Standard success payload; ``warnings`` is only included when non-empty."""
  46. return {"success": True, "platform": platform, "chat_id": chat_id, **fields,
  47. **({"warnings": warnings} if warnings else {})}
  48. _NO_DELIVERABLE = "No deliverable text or media remained after processing MEDIA tags"
  49. _TELEGRAM_TRANSIENT_MARKERS = ("bad gateway", "502", "too many requests", "429", "service unavailable", "503",
  50. "gateway timeout", "504")
  51. def _telegram_retry_delay(exc: Exception, attempt: int) -> float | None:
  52. """Retry delay in seconds, or None when final: honours ``retry_after``; timeouts are
  53. never retried (the send may have gone through); 5xx/429 back off exponentially."""
  54. retry_after = getattr(exc, "retry_after", None)
  55. if retry_after is not None:
  56. try:
  57. return max(float(retry_after), 0.0)
  58. except (TypeError, ValueError):
  59. return 1.0
  60. text = str(exc).lower()
  61. if "timed out" in text or "timeout" in text:
  62. return None
  63. return float(2 ** attempt) if any(marker in text for marker in _TELEGRAM_TRANSIENT_MARKERS) else None
  64. async def _send_telegram_message_with_retry(bot, *, attempts: int = 3, **kwargs):
  65. """``bot.send_message`` with bounded retries on transient failures."""
  66. for attempt in range(attempts):
  67. try:
  68. return await bot.send_message(**kwargs)
  69. except Exception as exc:
  70. delay = _telegram_retry_delay(exc, attempt)
  71. if delay is None or attempt >= attempts - 1:
  72. raise
  73. logger.warning("Transient Telegram send failure (attempt %d/%d), retrying in %.1fs: %s",
  74. attempt + 1, attempts, delay, _sanitize_error_text(exc))
  75. await asyncio.sleep(delay)
  76. def _is_telegram_thread_not_found(error: Exception) -> bool:
  77. """Mirror of the gateway adapter's ``_is_thread_not_found_error``.
  78. Matches the gateway adapter's ``_is_thread_not_found_error`` for the standalone ``_send_telegram`` path
  79. (issue #27012).
  80. """
  81. return "thread not found" in str(error).lower()
  82. def _telegram_bot(token):
  83. """Bot honouring TELEGRAM_PROXY (standalone sends time out where api.telegram.org is
  84. blocked); falls back to a direct connection."""
  85. from telegram import Bot
  86. try:
  87. from gateway.platforms.base import resolve_proxy_url
  88. proxy = resolve_proxy_url("TELEGRAM_PROXY", target_hosts=["api.telegram.org"])
  89. if not proxy:
  90. return Bot(token=token)
  91. from telegram.request import HTTPXRequest
  92. logger.info("send_message: standalone Telegram send routed through proxy %s", proxy)
  93. return Bot(token=token, request=HTTPXRequest(proxy=proxy), get_updates_request=HTTPXRequest(proxy=proxy))
  94. except Exception as proxy_err:
  95. logger.warning("send_message: failed to attach Telegram proxy (%s), falling back to direct connection", proxy_err)
  96. return Bot(token=token)
  97. def _telegram_thread_kwargs(thread_id):
  98. """Topic id -> ``message_thread_id`` kwargs. Forum "General" is thread "1" inbound but
  99. the Bot API rejects message_thread_id=1, so it maps to no thread — same as the adapter."""
  100. if thread_id is None:
  101. return {}
  102. try:
  103. from plugins.platforms.telegram.adapter import TelegramAdapter
  104. effective = TelegramAdapter._message_thread_id_for_send(str(thread_id))
  105. except Exception: # adapter import failed (python-telegram-bot missing): explicit mapping
  106. effective = None if str(thread_id) == "1" else int(thread_id)
  107. return {} if effective is None else {"message_thread_id": effective}
  108. def _strip_mdv2_safe(text):
  109. """Strip MarkdownV2 escapes for the plain-text fallback; identity if unavailable."""
  110. try:
  111. from plugins.platforms.telegram.adapter import _strip_mdv2
  112. return _strip_mdv2(text)
  113. except Exception:
  114. return text
  115. def _adapter_media_method(ext, voice, force_document=False):
  116. """``(adapter method, kind)``: document when forced, else image / video / voice by
  117. extension (``voice`` already folds in the caller's audio rule)."""
  118. if force_document:
  119. return "send_document", "document"
  120. if ext in _IMAGE_EXTS:
  121. return "send_image_file", "image"
  122. if ext in _VIDEO_EXTS:
  123. return "send_video", "video"
  124. return ("send_voice", "audio") if voice else ("send_document", "document")
  125. async def _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **kwargs):
  126. """Bot API media method by extension: photo (unless forced document), video, voice note,
  127. sendAudio (MP3/M4A only), else document."""
  128. kind = next((k for exts, k in ((() if force_document else _IMAGE_EXTS, "photo"), (_VIDEO_EXTS, "video"),
  129. (_VOICE_EXTS if is_voice else (), "voice"), (_TELEGRAM_SEND_AUDIO_EXTS, "audio"))
  130. if ext in exts), "document")
  131. return await getattr(bot, f"send_{kind}")(chat_id=chat_id, **{kind: f}, **kwargs)
  132. async def _telegram_send_text_chunk(bot, chat_id, chunk, parse_mode, has_html, text_kwargs):
  133. """One text chunk with adapter-matching fallbacks: thread-not-found -> retry without
  134. ``message_thread_id`` (dropped from ``text_kwargs`` for later chunks too); parse failure
  135. -> plain text."""
  136. async def send(text, mode):
  137. return await _send_telegram_message_with_retry(bot, chat_id=chat_id, text=text, parse_mode=mode, **text_kwargs)
  138. try:
  139. return await send(chunk, parse_mode)
  140. except Exception as md_error:
  141. # Thread not found — retry without message_thread_id so the message still delivers (matching the
  142. # gateway adapter's fallback behaviour, issue #27012).
  143. if _is_telegram_thread_not_found(md_error) and text_kwargs.get("message_thread_id") is not None:
  144. logger.warning("Thread %s not found in _send_telegram, retrying without message_thread_id",
  145. text_kwargs.pop("message_thread_id"))
  146. return await send(chunk, parse_mode)
  147. err_text = str(md_error).lower()
  148. if "parse" in err_text or "markdown" in err_text or "html" in err_text:
  149. logger.warning("Parse mode %s failed in _send_telegram, falling back to plain text: %s",
  150. parse_mode, _sanitize_error_text(md_error))
  151. return await send(chunk if has_html else _strip_mdv2_safe(chunk), None)
  152. raise
  153. async def _telegram_send_one_media(bot, chat_id, media_path, is_voice, *, caption, parse_mode, has_html,
  154. thread_kwargs, force_document):
  155. """Upload one file with adapter-matching fallbacks (thread-not-found -> no
  156. ``message_thread_id``; caption parse failure -> plain caption); retries re-seek the file."""
  157. ext = os.path.splitext(media_path)[1].lower()
  158. voice_note = ext in _VOICE_EXTS and is_voice
  159. # ``caption`` is only set for a single captionable file, so this never double-captions
  160. # a multi-file send or a voice note.
  161. media_kwargs = {**thread_kwargs, **({"caption": caption, "parse_mode": parse_mode}
  162. if caption is not None and not voice_note else {})}
  163. if voice_note or ext in _TELEGRAM_SEND_AUDIO_EXTS:
  164. with contextlib.suppress(Exception):
  165. from plugins.platforms.telegram.adapter import _probe_voice_duration_seconds
  166. duration = await asyncio.to_thread(_probe_voice_duration_seconds, media_path)
  167. if duration is not None:
  168. media_kwargs["duration"] = duration
  169. thumb_path = None
  170. if ext in _VIDEO_EXTS:
  171. # Telegram processes only small video uploads itself; past that the message carries no
  172. # geometry and no thumbnail, so clients draw a square tile (see the adapter helpers).
  173. # Keyed on the extension because ``_telegram_send_media`` routes every video extension to
  174. # ``sendVideo`` regardless of ``force_document`` (which only forces images to documents).
  175. with contextlib.suppress(Exception):
  176. from plugins.platforms.telegram.adapter import _probe_video_geometry, _video_thumbnail_jpeg
  177. geometry = await asyncio.to_thread(_probe_video_geometry, media_path)
  178. if geometry:
  179. media_kwargs.update(geometry)
  180. thumb_path = await asyncio.to_thread(_video_thumbnail_jpeg, media_path, geometry.get("duration"))
  181. if thumb_path:
  182. media_kwargs["thumbnail"] = thumb_path
  183. try:
  184. with open(media_path, "rb") as f: # noqa: ASYNC230 -- file handle is streamed to the upload; a local open() is non-blocking in practice
  185. try:
  186. return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)
  187. except Exception as media_err:
  188. err_text = str(media_err).lower()
  189. if _is_telegram_thread_not_found(media_err) and media_kwargs.get("message_thread_id"):
  190. logger.warning("Thread %s not found for media send, retrying without message_thread_id",
  191. media_kwargs.pop("message_thread_id"))
  192. elif media_kwargs.get("parse_mode") and ("parse" in err_text or "caption" in err_text):
  193. logger.warning("Caption parse failed for media send, retrying plain: %s",
  194. _sanitize_error_text(media_err))
  195. media_kwargs.pop("parse_mode", None)
  196. if not has_html and media_kwargs.get("caption"):
  197. media_kwargs["caption"] = _strip_mdv2_safe(media_kwargs["caption"])
  198. else:
  199. raise
  200. f.seek(0)
  201. return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)
  202. finally:
  203. if thumb_path:
  204. with contextlib.suppress(OSError):
  205. os.remove(thumb_path)
  206. def _telegram_format(message):
  207. """``(formatted, parse_mode, has_html)``: text already containing HTML tags is sent as
  208. HTML; otherwise Markdown -> MarkdownV2 via the adapter's ``format_message``."""
  209. from telegram.constants import ParseMode
  210. if re.search(r'<[a-zA-Z/][^>]*>', message):
  211. return message, ParseMode.HTML, True
  212. try:
  213. from plugins.platforms.telegram.adapter import TelegramAdapter
  214. return TelegramAdapter.__new__(TelegramAdapter).format_message(message), ParseMode.MARKDOWN_V2, False
  215. except Exception:
  216. return message, ParseMode.MARKDOWN_V2, False # formatting unavailable: send as-is
  217. async def _send_telegram(token, chat_id, message, media_files=None, thread_id=None, disable_link_previews=False, force_document=False):
  218. """One-shot Telegram Bot API send; parse failures fall back to plain text."""
  219. try:
  220. formatted, send_parse_mode, _has_html = _telegram_format(message)
  221. bot = _telegram_bot(token)
  222. from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id
  223. from gateway.platforms.base import BasePlatformAdapter, utf16_len
  224. # Telegram accepts a numeric chat_id OR an @username string; never force-int.
  225. # See #13206.
  226. int_chat_id = normalize_telegram_chat_id(chat_id)
  227. media_files = media_files or []
  228. thread_kwargs = _telegram_thread_kwargs(thread_id)
  229. # disable_web_page_preview is only valid for send_message, not media sends.
  230. text_kwargs = {**thread_kwargs, **({"disable_web_page_preview": True} if disable_link_previews else {})}
  231. last_msg, warnings, _tg_caption = None, [], None
  232. # MEDIA caption rides on the bubble as its *formatted* caption; formatting can inflate a
  233. # raw <1024 string past Telegram's cap, so re-check in UTF-16 units.
  234. _cap, _ = _media_caption_split(message, media_files, max_caption_len=_TELEGRAM_CAPTION_LIMIT)
  235. if _cap is not None and utf16_len(formatted) <= _TELEGRAM_CAPTION_LIMIT:
  236. _tg_caption, formatted = formatted, "" # suppress the separate text send below
  237. # Chunk *after* formatting, in UTF-16 units: escaping can push a raw-<4096 message over.
  238. for chunk in BasePlatformAdapter.truncate_message(formatted, 4096, len_fn=utf16_len) if formatted.strip() else ():
  239. last_msg = await _telegram_send_text_chunk(bot, int_chat_id, chunk, send_parse_mode, _has_html, text_kwargs)
  240. for media_path, is_voice in media_files:
  241. if not os.path.exists(media_path):
  242. warnings.append(f"Media file not found, skipping: {media_path}")
  243. logger.warning(warnings[-1])
  244. # Caption mode suppressed the text send; the file is gone, so deliver the words alone.
  245. if _tg_caption is not None and last_msg is None:
  246. try:
  247. last_msg = await _send_telegram_message_with_retry(
  248. bot, chat_id=int_chat_id, text=_tg_caption, parse_mode=send_parse_mode, **text_kwargs)
  249. _tg_caption = None # delivered — don't re-caption a later file
  250. except Exception as _cap_err:
  251. logger.warning("Telegram caption-fallback send failed for missing media: %s",
  252. _sanitize_error_text(_cap_err))
  253. continue
  254. try:
  255. last_msg = await _telegram_send_one_media(
  256. bot, int_chat_id, media_path, is_voice, caption=_tg_caption, parse_mode=send_parse_mode,
  257. has_html=_has_html, thread_kwargs=thread_kwargs, force_document=force_document)
  258. except Exception as e:
  259. warnings.append(_sanitize_error_text(f"Failed to send media {media_path}: {e}"))
  260. logger.error(warnings[-1])
  261. if last_msg is None:
  262. return {"error": _NO_DELIVERABLE, **({"warnings": warnings} if warnings else {})}
  263. return _success("telegram", chat_id, warnings, message_id=str(last_msg.message_id))
  264. except ImportError:
  265. return {"error": "python-telegram-bot not installed. Run: "
  266. f"{install_hint('telegram')}"}
  267. except Exception as e:
  268. return _error(f"Telegram send failed: {e}")
  269. def _live_adapter(platform, *, lookup_failed_warning=None):
  270. """``(runner, adapter)`` for the in-process gateway; ``(None, None)`` standalone (cron);
  271. ``(runner, None)`` when the lookup fails — logged when a warning is given, never silently
  272. swallowed (a silent fall-through could recreate a reconnect storm).
  273. Multiplex: the adapter is the ACTIVE PROFILE's (``_profile_adapters[profile]``), never a bare
  274. ``runner.adapters`` hit — that map holds the default profile's bots, so a secondary profile's turn
  275. would post/react with the default bot's identity. A profile with no adapter for the platform
  276. yields ``None`` (fail closed → the caller's scoped standalone sender or an error), never the
  277. default bot. Same resolver shape as ``hermes_cli/platform_actions.py::_resolve_adapter``."""
  278. try:
  279. from gateway.run import _gateway_runner_ref
  280. runner = _gateway_runner_ref()
  281. except Exception:
  282. runner = None
  283. if runner is None:
  284. return None, None
  285. try:
  286. resolve = getattr(runner, "_authorization_adapter", None)
  287. if not callable(resolve): # bare runner stubs without the authz mixin
  288. return runner, runner.adapters.get(platform)
  289. from hermes_cli.profiles import get_active_profile_name
  290. return runner, resolve(platform, get_active_profile_name())
  291. except Exception:
  292. if lookup_failed_warning:
  293. logger.warning(lookup_failed_warning, exc_info=True)
  294. return runner, None
  295. def _plugin_standalone_sender(platform_name, *, label=None, discover=True):
  296. """``(standalone_sender_fn, None)`` for a registered plugin or ``(None, error_dict)``;
  297. ``discover`` runs the idempotent plugin scan first."""
  298. from gateway.platform_registry import platform_registry
  299. if discover:
  300. from hermes_cli.plugins import discover_plugins
  301. discover_plugins()
  302. entry = platform_registry.get(platform_name)
  303. if entry is None or entry.standalone_sender_fn is None:
  304. return None, {"error": f"{label or platform_name} plugin not registered or missing standalone_sender_fn"}
  305. return entry.standalone_sender_fn, None
  306. async def _registry_standalone_send(platform_name, pconfig, chat_id, message, thread_id=None):
  307. """One-shot text send through a plugin's ``standalone_sender_fn``."""
  308. sender, err = _plugin_standalone_sender(platform_name)
  309. return err or await sender(pconfig, chat_id, message, thread_id=thread_id)
  310. async def _resolve_slack_user_target(token, chat_id):
  311. """Resolve ``user:U...`` / ``user_name:<handle>`` to a D... DM conversation (chat.postMessage
  312. needs a conversation ID); ``user_name:`` goes through users.list first (stable handle match
  313. only); other ids pass through. ``(chat_id, None)`` or ``(None, error_dict)``."""
  314. if not (chat_id.startswith("user:") or chat_id.startswith("user_name:")):
  315. return chat_id, None
  316. try:
  317. import aiohttp
  318. except ImportError:
  319. return None, {"error": "aiohttp not installed. Run: "
  320. f"{install_hint('messaging')}"}
  321. try:
  322. from gateway.platforms.base import resolve_proxy_url, proxy_kwargs_for_aiohttp
  323. _sess_kw, _req_kw = proxy_kwargs_for_aiohttp(resolve_proxy_url())
  324. headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
  325. async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30), **_sess_kw) as session:
  326. async def post_api(method, payload):
  327. async with session.post(f"https://slack.com/api/{method}", headers=headers, json=payload,
  328. **_req_kw) as resp:
  329. return await resp.json()
  330. if chat_id.startswith("user_name:"):
  331. name = chat_id[len("user_name:"):]
  332. query = name.strip().lstrip("@").lower()
  333. matches, cursor = [], None
  334. for _page in range(20):
  335. data = await post_api("users.list", {"limit": 200, **({"cursor": cursor} if cursor else {})})
  336. if not data.get("ok"):
  337. return None, _error(f"Slack users.list error: {data.get('error', 'unknown')}")
  338. # Stable handle only: display/real names are mutable and non-unique.
  339. matches += [m for m in data.get("members", []) if not (m.get("deleted") or m.get("is_bot"))
  340. and str(m.get("name", "")).strip().lower() == query]
  341. cursor = (data.get("response_metadata") or {}).get("next_cursor")
  342. if not cursor:
  343. break
  344. if not matches:
  345. return None, _error(f"Could not resolve Slack user '@{name}'.")
  346. if len(matches) > 1:
  347. return None, _error(f"Slack user '@{name}' matched multiple Slack users. Use a Slack user ID instead.")
  348. chat_id = f"user:{matches[0].get('id')}"
  349. opened = await post_api("conversations.open", {"users": chat_id[len("user:"):]})
  350. if not opened.get("ok"):
  351. return None, _error(f"Slack conversations.open error: {opened.get('error', 'unknown')}. "
  352. "Check bot permissions (im:write).")
  353. dm_id = (opened.get("channel") or {}).get("id")
  354. return (dm_id, None) if dm_id else (None, _error("Slack conversations.open did not return a DM channel ID"))
  355. except Exception as e:
  356. return None, _error(f"Slack DM resolution failed: {e}")
  357. # "ephemeral connect (may re-init E2EE per send, see #46310)",
  358. async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None, thread_id=None):
  359. """Matrix adapter send (native media preserved). Prefer the live gateway adapter's persistent
  360. olm/megolm session: ephemeral per-send connects re-init E2EE and claim one-time keys, which
  361. under bursts exhausts recipient OTKs and silently drops messages — ephemeral is cron-only.
  362. When a live gateway adapter is available (i.e. the tool runs inside a running gateway), the persistent
  363. connection is reused — one olm/megolm session for all sends. This avoids per-message E2EE re-init storms
  364. that exhaust recipient OTKs and silently drop messages (issue #46310).
  365. """
  366. media_files = media_files or []
  367. metadata = {"thread_id": thread_id} if thread_id else None
  368. from gateway.config import Platform
  369. _, live_adapter = _live_adapter(Platform.MATRIX, lookup_failed_warning=(
  370. "Matrix: live gateway adapter lookup failed; falling back to an "
  371. "ephemeral connect (may re-init E2EE per send)"))
  372. if live_adapter is not None:
  373. # Owned by the gateway — must NOT be disconnected (return before the ephemeral ``finally``).
  374. return await _matrix_send_core(live_adapter, chat_id, message, media_files, metadata)
  375. try:
  376. from plugins.platforms.matrix.adapter import MatrixAdapter
  377. except ImportError:
  378. return {"error": "Matrix dependencies not installed. Run: "
  379. f"{install_hint('matrix')}"}
  380. adapter = MatrixAdapter(pconfig)
  381. try:
  382. if not await adapter.connect():
  383. return _error("Matrix connect failed")
  384. return await _matrix_send_core(adapter, chat_id, message, media_files, metadata)
  385. except Exception as e:
  386. return _error(f"Matrix send failed: {e}")
  387. finally:
  388. with contextlib.suppress(Exception):
  389. await adapter.disconnect()
  390. async def _matrix_send_core(adapter, chat_id, message, media_files, metadata):
  391. """Core send logic shared by live and ephemeral Matrix adapters."""
  392. last_result = None
  393. if message.strip():
  394. last_result = await adapter.send(chat_id, message, metadata=metadata)
  395. if not last_result.success:
  396. return _error(f"Matrix send failed: {last_result.error}")
  397. for media_path, is_voice in media_files:
  398. if not os.path.exists(media_path):
  399. return _error(f"Media file not found: {media_path}")
  400. ext = os.path.splitext(media_path)[1].lower()
  401. method, _ = _adapter_media_method(ext, (ext in _VOICE_EXTS and is_voice) or ext in _AUDIO_EXTS)
  402. last_result = await getattr(adapter, method)(chat_id, media_path, metadata=metadata)
  403. if not last_result.success:
  404. return _error(f"Matrix media send failed: {last_result.error}")
  405. return {"error": _NO_DELIVERABLE} if last_result is None else _success("matrix", chat_id, message_id=last_result.message_id)