telegram_topic_routing.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. """Route a client-created Telegram DM topic's thread-less opener into that topic (#136567).
  2. Telegram for Android (13.0.x) delivers the opening message of a topic created from the "All
  3. messages" view with no ``message_thread_id``. The ``Message`` carrying ``forum_topic_created`` is then
  4. the only update that names the new topic (``ForumTopicCreated`` itself has only name/icon fields).
  5. Recording authorized, non-bot private-chat creations lets the thread-less messages that follow adopt
  6. the new topic instead of arriving lobby-shaped, where gateway topic recovery would pin them to the
  7. most recently bound topic.
  8. Adoption follows time and per-chat order, never message-id adjacency: private-chat message ids come
  9. from one sequence shared by every private chat of the bot account (bot replies included), so a send
  10. elsewhere between the creation and the opener breaks ``creation + 1``. Per-chat FIFO update
  11. processing guarantees nothing from this chat lands in between.
  12. """
  13. import logging
  14. import time
  15. from typing import Any, Optional
  16. logger = logging.getLogger("plugins.platforms.telegram.adapter")
  17. class TelegramTopicRoutingMixin:
  18. """Topic-creation bookkeeping for ``TelegramAdapter`` (relies on its ``_chat_type_str``/``_chat_id_str``)."""
  19. # A thread-less message from the creator adopts the new topic while it was SENT within this many
  20. # seconds of the creation or of the previous adopted message (the client sends the opener
  21. # ~0.2-1 s after the creation; a split long text or an album follows within the same second).
  22. # Measured on Telegram's ``Message.date`` stamps, never on handler time: per-chat FIFO holds a
  23. # follow-up behind the previous handler (a photo download, STT), and it must not age out there.
  24. _NEW_TOPIC_FOLLOW_SECONDS = 5.0
  25. _NEW_TOPIC_OPENER_MAX_PENDING = 256
  26. # Memory bound only (local clock), far above any handler backlog; adoption never reads it.
  27. _NEW_TOPIC_RECORD_TTL_SECONDS = 600.0
  28. @staticmethod
  29. def _creator_key(message) -> str:
  30. return str(getattr(getattr(message, "from_user", None), "id", ""))
  31. @staticmethod
  32. def _sent_at(message) -> Optional[float]:
  33. """Telegram's send stamp (whole seconds); an edit keeps its message's original ``date``."""
  34. date = getattr(message, "date", None)
  35. return date.timestamp() if hasattr(date, "timestamp") else None
  36. async def _handle_forum_topic_created(self, update: Any, context: Any) -> None:
  37. """Record an authorized, non-bot private-chat topic creation (#136567).
  38. Routing signal only, never an agent turn. The user-chosen name is NOT cached in ``_dm_topics``:
  39. entries there mark operator-declared topics, which session-title auto-rename skips.
  40. """
  41. message = getattr(update, "effective_message", None)
  42. if message is None or getattr(message, "forum_topic_created", None) is None:
  43. return
  44. # Private chats only: in a forum group a thread-less message is General, never an opener.
  45. if self._chat_type_str(getattr(message, "chat", None)) != "private":
  46. return
  47. thread_id = getattr(message, "message_thread_id", None)
  48. sender = getattr(message, "from_user", None)
  49. sent_at = self._sent_at(message)
  50. if thread_id is None or sent_at is None or sender is None or getattr(sender, "is_bot", False) is True:
  51. return
  52. if not self._is_user_authorized_from_message(message):
  53. return
  54. pending = self.__dict__.setdefault("_pending_created_topics", {})
  55. now = time.monotonic()
  56. for key in [k for k, rec in pending.items() if now - rec[2] > self._NEW_TOPIC_RECORD_TTL_SECONDS]:
  57. del pending[key]
  58. while len(pending) >= self._NEW_TOPIC_OPENER_MAX_PENDING:
  59. del pending[min(pending, key=lambda k: pending[k][2])]
  60. chat_id = self._chat_id_str(message)
  61. pending[(chat_id, self._creator_key(message))] = (str(thread_id), sent_at, now)
  62. logger.debug("[%s] Recorded new Telegram topic %s (chat=%s)", self.name, thread_id, chat_id)
  63. def _adopt_created_topic_thread(self, message: Any, chat_type: str, thread_id: Optional[str]) -> Optional[str]:
  64. """Thread id of the topic this sender just created, for its thread-less follow-up messages.
  65. A threaded message (the topic now routes normally) or a send gap longer than
  66. ``_NEW_TOPIC_FOLLOW_SECONDS`` ends the follow; each adoption extends it, so every chunk of a
  67. split opener lands in the same topic.
  68. """
  69. # .get: adapters built without __init__ (object.__new__ in tests) have no store yet.
  70. pending = self.__dict__.get("_pending_created_topics")
  71. if chat_type != "dm" or not pending:
  72. return thread_id
  73. key = (self._chat_id_str(message), self._creator_key(message))
  74. record = pending.get(key)
  75. sent_at = self._sent_at(message)
  76. # An edit of a message sent before the creation stays where that message lived and leaves
  77. # the record for the real opener.
  78. if record is None or sent_at is None or sent_at < record[1]:
  79. return thread_id
  80. del pending[key]
  81. if thread_id is not None or getattr(message, "message_thread_id", None) is not None:
  82. return thread_id
  83. created_thread_id, last_sent_at, _recorded = record
  84. if sent_at - last_sent_at > self._NEW_TOPIC_FOLLOW_SECONDS:
  85. return thread_id
  86. pending[key] = (created_thread_id, sent_at, time.monotonic())
  87. logger.info("[%s] Thread-less message %s adopted by new Telegram topic %s (chat=%s)",
  88. self.name, getattr(message, "message_id", "?"), created_thread_id, key[0])
  89. return created_thread_id