adapter_slash_payload.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """Slack slash-command payload decoding: the gateway text and the thread anchor of a slash."""
  2. from __future__ import annotations
  3. from typing import Optional
  4. def slash_command_text(command: dict) -> str:
  5. """Gateway message text for a slash payload. Native slashes keep Slack's raw argument
  6. payload verbatim (internal/trailing spacing). ``/hermes`` (or a missing ``command``) maps
  7. ``<subcommand> [args]`` via the registry, else free-form text is a regular question."""
  8. slash_name = (command.get("command") or "").lstrip("/").strip()
  9. raw_text = str(command.get("text") or "")
  10. if slash_name not in {"hermes", ""}:
  11. return f"/{slash_name}" if not raw_text else f"/{slash_name} {raw_text}"
  12. legacy_text = raw_text.strip()
  13. from hermes_cli.commands_platforms import slack_subcommand_map
  14. subcommand_map = slack_subcommand_map()
  15. subcommand_map["compact"] = "/compress"
  16. first_word = legacy_text.split()[0] if legacy_text.split() else ""
  17. if first_word in subcommand_map:
  18. rest = legacy_text[len(first_word) :].strip()
  19. mapped = subcommand_map[first_word]
  20. return f"{mapped} {rest}".strip() if rest else mapped
  21. return legacy_text or "/help"
  22. def slash_thread_id(command: dict) -> Optional[str]:
  23. """Thread anchor for a slash payload so session-scoped commands (``/model``)
  24. hit the same thread session. Shape varies by surface: top-level or nested
  25. ``message``/``container``; ``thread_ts`` preferred over ``message_ts``."""
  26. nested = (command.get(k) for k in ("message", "container"))
  27. candidates = [command] + [n for n in nested if isinstance(n, dict)]
  28. for ts_key in ("thread_ts", "message_ts"):
  29. for payload in candidates:
  30. value = payload.get(ts_key)
  31. if value:
  32. return str(value)
  33. return None