inline_picker.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/usr/bin/env python3
  2. """Telegram inline command picker — searchable access to EVERY command/skill.
  3. The BotCommand menu is capped (100/scope, Hermes uses 60), so inline mode (``@yourbot <query>``, 50 per
  4. page) exposes the rest; tapping a result sends ``/cmd args`` as the user through the normal command path.
  5. PTB-object-free on purpose: plain dicts keep catalog/filter/pagination unit-testable; the adapter converts
  6. to ``InlineQueryResultArticle``. Inert until inline mode is enabled via BotFather ``/setinline``.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. from typing import Any, Dict, List, Tuple
  11. logger = logging.getLogger(__name__)
  12. # Telegram hard limit: max 50 results per answerInlineQuery call.
  13. PAGE_SIZE = 50
  14. # Results depend on caller auth + installed skills: never share across users, keep short.
  15. CACHE_TIME_SECONDS = 10
  16. def collect_inline_catalog() -> list[dict[str, str]]:
  17. """Every dispatchable command as ``{name, description}``, first occurrence wins: core gateway commands
  18. first (menu gating), then plugin + skill commands with ``max_slots=None`` (no cap)."""
  19. catalog: list[dict[str, str]] = []
  20. seen: set[str] = set()
  21. def _add(name, desc):
  22. if name and name not in seen:
  23. seen.add(name)
  24. catalog.append({"name": name, "description": desc or ""})
  25. try:
  26. from hermes_cli.commands_platforms import _collect_gateway_skill_entries, _sanitize_telegram_name, telegram_bot_commands
  27. except Exception: # pragma: no cover - defensive
  28. logger.debug("inline picker: commands registry unavailable", exc_info=True)
  29. return catalog
  30. try:
  31. for name, desc in telegram_bot_commands():
  32. _add(name, desc)
  33. except Exception:
  34. logger.debug("inline picker: core command collection failed", exc_info=True)
  35. try:
  36. entries, _hidden = _collect_gateway_skill_entries(
  37. platform="telegram", max_slots=None, reserved_names=set(seen), desc_limit=100, sanitize_name=_sanitize_telegram_name,
  38. )
  39. for entry in entries: # shape is (name, desc, cmd_key[, raw_name])
  40. _add(entry[0], entry[1])
  41. except Exception:
  42. logger.debug("inline picker: skill/plugin collection failed", exc_info=True)
  43. return catalog
  44. def filter_catalog(catalog: list[dict[str, str]], term: str) -> list[dict[str, str]]:
  45. """Rank *catalog* against *term*: prefix > name-substring > description.
  46. Empty term returns the full catalog in collection order (the "browse" view)."""
  47. term = (term or "").strip().lower().lstrip("/")
  48. if not term:
  49. return list(catalog)
  50. prefix: list[dict[str, str]] = []
  51. name_sub: list[dict[str, str]] = []
  52. desc_sub: list[dict[str, str]] = []
  53. norm_term = term.replace("-", "_") # hyphens/underscores equivalent, mirroring command dispatch
  54. for item in catalog:
  55. norm_name = item["name"].lower().replace("-", "_")
  56. if norm_name.startswith(norm_term):
  57. prefix.append(item)
  58. elif norm_term in norm_name:
  59. name_sub.append(item)
  60. elif term in (item.get("description") or "").lower():
  61. desc_sub.append(item)
  62. return prefix + name_sub + desc_sub
  63. def build_inline_results(query: str, offset: str = "", page_size: int = PAGE_SIZE) -> tuple[list[dict[str, Any]], str]:
  64. """One page of inline results for *query*: first token filters the catalog; the remainder becomes the
  65. command argument (``@bot plan migrate auth`` → ``/plan migrate auth``). ``next_offset == ""`` = last page."""
  66. parts = (query or "").strip().split(None, 1)
  67. term = parts[0] if parts else ""
  68. args = parts[1].strip() if len(parts) > 1 else ""
  69. matches = filter_catalog(collect_inline_catalog(), term)
  70. try:
  71. # Client-controlled text: negatives must not slice the catalog from the tail.
  72. start = max(0, int(offset)) if offset else 0
  73. except (TypeError, ValueError):
  74. start = 0
  75. next_offset = str(start + page_size) if len(matches) > start + page_size else ""
  76. results: list[dict[str, Any]] = []
  77. for item in matches[start:start + page_size]:
  78. message_text = f"/{item['name']}" + (f" {args}" if args else "")
  79. results.append({
  80. "id": f"{start}:{item['name']}"[:64], # offset-scoped: unique across pages
  81. "title": f"/{item['name']}",
  82. "description": (item.get("description") or "")[:100],
  83. "message_text": message_text[:4096],
  84. })
  85. return results, next_offset