telegram_managed_bot.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. """Telegram Managed Bot onboarding client: creates a user-owned child bot via the Nous onboarding
  2. service (no BotFather copy-paste); the raw Telegram token is saved locally after one retrieval."""
  3. from __future__ import annotations
  4. from pm import install_hint
  5. import os
  6. import re
  7. import sys
  8. import time
  9. from dataclasses import dataclass
  10. from typing import Optional
  11. import httpx
  12. # Nous-hosted pairing API; override for PoC/staging with TELEGRAM_ONBOARDING_URL.
  13. DEFAULT_API_URL = "https://setup.hermes-agent.nousresearch.com"
  14. TELEGRAM_ONBOARDING_URL_ENV = "TELEGRAM_ONBOARDING_URL"
  15. DEFAULT_BOT_NAME = "Hermes Agent"
  16. DEFAULT_POLL_TIMEOUT = 180
  17. POLL_INTERVAL = 2
  18. _TELEGRAM_BOT_TOKEN_RE = re.compile(r"^\d+:[A-Za-z0-9_-]{30,}$")
  19. @dataclass(frozen=True)
  20. class TelegramPairing:
  21. """Pairing record returned by the Telegram onboarding service."""
  22. pairing_id: str
  23. poll_token: str
  24. suggested_username: str
  25. deep_link: str
  26. qr_payload: str
  27. expires_at: str | None = None
  28. @dataclass(frozen=True)
  29. class TelegramBotSetupResult:
  30. """Successful Telegram onboarding result returned by the setup service."""
  31. token: str
  32. bot_username: str | None = None
  33. owner_user_id: int | None = None
  34. def _api_url(api_url: str | None = None) -> str:
  35. """Resolve the onboarding API URL, honoring the PoC env override."""
  36. return (api_url or os.environ.get(TELEGRAM_ONBOARDING_URL_ENV) or DEFAULT_API_URL).rstrip("/")
  37. def is_valid_telegram_bot_token(token: object) -> bool:
  38. """Return True when *token* has Telegram's bot-token shape."""
  39. return isinstance(token, str) and bool(_TELEGRAM_BOT_TOKEN_RE.match(token))
  40. def _parse_owner_user_id(value: object) -> int | None:
  41. if isinstance(value, bool):
  42. return None
  43. if isinstance(value, str) and value.isdecimal():
  44. value = int(value)
  45. return value if isinstance(value, int) and value > 0 else None
  46. def render_qr_terminal(url: str) -> str:
  47. """Render a URL as a QR code string suitable for terminal output."""
  48. try:
  49. import io
  50. import qrcode # type: ignore[import-untyped]
  51. except ImportError:
  52. return ""
  53. qr = qrcode.QRCode(version=None, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=1, border=1)
  54. qr.add_data(url)
  55. qr.make(fit=True)
  56. buf = io.StringIO()
  57. qr.print_ascii(out=buf, invert=True)
  58. return buf.getvalue()
  59. def print_qr_code(url: str, *, include_link: bool = True) -> None:
  60. """Print a QR code to stdout, with URL fallback if qrcode is missing."""
  61. print(render_qr_terminal(url) or (
  62. " (QR code unavailable. From the Hermes environment, run: "
  63. f"{install_hint('messaging')}. "
  64. "Then restart Hermes.)"))
  65. if include_link:
  66. print(f" Link: {url}")
  67. def create_pairing(
  68. api_url: str | None = None, bot_name: str = DEFAULT_BOT_NAME, timeout: float = 10.0
  69. ) -> TelegramPairing | None:
  70. """POST a pairing; the returned poll token is only used as a bearer credential while polling."""
  71. try:
  72. resp = httpx.post(f"{_api_url(api_url)}/v1/telegram/pairings", json={"bot_name": bot_name}, timeout=timeout)
  73. if resp.status_code not in (200, 201):
  74. return None
  75. data = resp.json()
  76. except (httpx.HTTPError, ValueError):
  77. return None
  78. required = ("pairing_id", "poll_token", "suggested_username", "deep_link")
  79. if not all(isinstance(data.get(key), str) and data.get(key) for key in required):
  80. return None
  81. qr_payload = data.get("qr_payload") or data["deep_link"]
  82. if not isinstance(qr_payload, str):
  83. return None
  84. expires_at = data.get("expires_at")
  85. return TelegramPairing(*(data[key] for key in required), qr_payload=qr_payload,
  86. expires_at=expires_at if isinstance(expires_at, str) else None)
  87. def poll_pairing_result_once(
  88. api_url: str | None, pairing: TelegramPairing, timeout: float = 10.0
  89. ) -> TelegramBotSetupResult | None:
  90. """Poll the onboarding service once. Returns setup metadata when ready."""
  91. resp = httpx.get(f"{_api_url(api_url)}/v1/telegram/pairings/{pairing.pairing_id}",
  92. headers={"Authorization": f"Bearer {pairing.poll_token}"}, timeout=timeout)
  93. if resp.status_code != 200:
  94. return None
  95. data = resp.json()
  96. token = data.get("token")
  97. if data.get("status") != "ready" or not is_valid_telegram_bot_token(token):
  98. return None
  99. bot_username = data.get("bot_username")
  100. return TelegramBotSetupResult(
  101. token, bot_username if isinstance(bot_username, str) and bot_username else None,
  102. _parse_owner_user_id(data.get("owner_user_id")))
  103. def poll_for_setup_result(
  104. api_url: str | None, pairing: TelegramPairing, timeout: float = DEFAULT_POLL_TIMEOUT,
  105. interval: float = POLL_INTERVAL, on_tick=None) -> Optional[TelegramBotSetupResult]:
  106. """Poll the pairing API until setup metadata is available or timeout. ``on_tick(elapsed_s)``
  107. runs before each attempt (progress display)."""
  108. start = time.monotonic()
  109. deadline = start + timeout
  110. while time.monotonic() < deadline:
  111. if on_tick:
  112. on_tick(time.monotonic() - start)
  113. try: # transport/JSON errors count as 'not ready yet'
  114. if result := poll_pairing_result_once(api_url, pairing):
  115. return result
  116. except (httpx.HTTPError, ValueError):
  117. pass
  118. time.sleep(interval)
  119. return None
  120. def auto_setup_telegram_bot_result(
  121. api_url: str | None = None, manager_bot: str = "HermesSetupBot",
  122. profile_name: Optional[str] = None, poll_timeout: float = DEFAULT_POLL_TIMEOUT,
  123. ) -> Optional[TelegramBotSetupResult]:
  124. """Run the full automatic Telegram bot creation flow."""
  125. _ = manager_bot, profile_name # accepted for callers; the service decides both
  126. resolved_api_url = _api_url(api_url)
  127. print(f"\n Contacting Hermes Telegram onboarding service: {resolved_api_url}")
  128. sys.stdout.flush()
  129. pairing = create_pairing(resolved_api_url)
  130. if not pairing:
  131. print(" ✗ Could not reach the Hermes Telegram onboarding service.\n"
  132. " Try the manual setup instead, or check your network.")
  133. return None
  134. print(" ✓ Pairing created\n Rendering QR code...")
  135. sys.stdout.flush()
  136. print("\n Scan this QR code with your phone, or open the link below:\n")
  137. print_qr_code(pairing.qr_payload, include_link=False)
  138. print(f"\n Link: {pairing.deep_link}\n"
  139. " When Telegram opens, tap 'Create Bot' to confirm.\n"
  140. " (You can edit the bot display name before confirming)\n")
  141. spinner_chars = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
  142. ticks = iter(range(1 << 30))
  143. def spin(elapsed: float) -> None:
  144. char = spinner_chars[next(ticks) % len(spinner_chars)]
  145. remaining = max(0, int(poll_timeout - int(elapsed)))
  146. sys.stdout.write(f"\r {char} Waiting for bot creation... ({remaining}s remaining) ")
  147. sys.stdout.flush()
  148. result = poll_for_setup_result(resolved_api_url, pairing, poll_timeout, POLL_INTERVAL, on_tick=spin)
  149. if result:
  150. sys.stdout.write("\r ✓ Bot created successfully! \n")
  151. sys.stdout.flush()
  152. return result
  153. sys.stdout.write("\r ✗ Timed out waiting for bot creation. \n")
  154. sys.stdout.flush()
  155. print(" The bot may still be created — check Telegram.\n"
  156. " You can paste the token manually below, or re-run setup.")
  157. return None