telegram_ids.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """Helpers for Telegram Bot API chat identifiers: a ``chat_id`` is a numeric ID (int) or an ``@username``
  2. string for public channels/groups; a bare ``int(chat_id)`` crashes on the username form."""
  3. from __future__ import annotations
  4. import re
  5. from typing import Any, Union
  6. from gateway.platforms.send_targets import parse_nonempty, regex_groups_parser
  7. # Usernames are 5-32 chars (letters, digits, underscores) with a leading "@"; 4-char legacy handles are tolerated.
  8. _TELEGRAM_USERNAME_RE = re.compile(r"@[A-Za-z0-9_]{4,32}")
  9. def normalize_telegram_chat_id(chat_id: Any) -> int | str:
  10. """Bot API-compatible chat_id: numeric values (incl. negative channel IDs) as ``int``, anything
  11. else (e.g. ``@username``) as a stripped string; never raises."""
  12. chat_id_str = str(chat_id).strip()
  13. try:
  14. return int(chat_id_str)
  15. except (TypeError, ValueError):
  16. return chat_id_str
  17. def looks_like_telegram_username(chat_id: Any) -> bool:
  18. """True when the value is an ``@username``-format Telegram chat identifier."""
  19. return bool(_TELEGRAM_USERNAME_RE.fullmatch(str(chat_id).strip()))
  20. def parse_telegram_username_target(target_ref: Any) -> str | None:
  21. """Return the value when it is an ``@username`` target, else ``None``."""
  22. value = str(target_ref).strip()
  23. return value if looks_like_telegram_username(value) else None
  24. _SEND_TARGET_RE = re.compile(r"^\s*(-?\d+)(?::(\d+))?\s*$")
  25. def parse_send_target(ref):
  26. """``target_ref_syntax_fn`` for the Telegram ``PlatformEntry``."""
  27. # "<chat_id>[:<topic_id>]" or an @username (usernames must not be force-int'd).
  28. parsed = regex_groups_parser(_SEND_TARGET_RE)(ref)
  29. if parsed:
  30. return parsed
  31. return parse_nonempty(parse_telegram_username_target(ref) or "")
  32. def parse_telegram_message_id(value: Any) -> int | None:
  33. """A reply anchor as a Telegram message id (a positive int), or ``None`` when it is not one.
  34. Anchors are opaque event ids upstream: a route wake (kanban-wake, loop-tick) carries a synthetic
  35. JSON identity, and raw ``int()`` on it failed every reply into the session (#139611); an
  36. unanchored reply is strictly better than a failed send."""
  37. if isinstance(value, bool):
  38. return None
  39. if isinstance(value, int):
  40. return value if value > 0 else None
  41. text = str(value).strip() if value is not None else ""
  42. return int(text) if text.isascii() and text.isdigit() and int(text) > 0 else None