adapter_reactions_context.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Compact emoji-reaction markers for Slack thread context.
  2. In channels where people answer by reacting instead of replying, a message
  3. with twelve :white_check_mark: and no replies otherwise reads as "nobody
  4. responded". ``conversations.replies`` already carries each message's
  5. ``reactions`` array under the history scopes the adapter requires, so this
  6. costs no extra API call and no new OAuth scope.
  7. """
  8. from __future__ import annotations
  9. import re
  10. from typing import Any
  11. # The marker conveys "people responded by reacting", not a full tally; the tail
  12. # of a heavily-reacted message collapses to "+N more".
  13. REACTION_MARKER_MAX = 8
  14. # Slack emoji names are word chars plus ``+ ' -`` (and ``::skin-tone-N``);
  15. # anything else is dropped so a crafted name can't fake context structure.
  16. _UNSAFE_NAME_CHARS = re.compile(r"[^\w+'\-:]+")
  17. def slack_reactions_marker(msg: dict[str, Any]) -> str:
  18. """``[reactions: :name:×count ...]`` for a Slack message, or ``""``.
  19. ``count`` is authoritative (Slack truncates each reaction's ``users``)."""
  20. reactions = msg.get("reactions")
  21. if not isinstance(reactions, list):
  22. return ""
  23. parts: list[str] = []
  24. for reaction in reactions:
  25. if not isinstance(reaction, dict):
  26. continue
  27. name = _UNSAFE_NAME_CHARS.sub("", str(reaction.get("name") or "")).strip(":")
  28. if not name:
  29. continue
  30. count = reaction.get("count")
  31. count = count if isinstance(count, int) else 0
  32. parts.append(f":{name}:×{count}" if count > 1 else f":{name}:")
  33. if not parts:
  34. return ""
  35. extra = len(parts) - REACTION_MARKER_MAX
  36. shown = parts[:REACTION_MARKER_MAX] + ([f"+{extra} more"] if extra > 0 else [])
  37. return "[reactions: " + " ".join(shown) + "]"