telegram_context.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. """Telegram group addressing helpers, kept out of the adapter facade.
  2. The identity line lives in ``channel_prompt`` and therefore in the cached-agent signature: it
  3. must be stable for the life of a session (username only — never a per-message fact).
  4. """
  5. from typing import TYPE_CHECKING, Optional
  6. if TYPE_CHECKING:
  7. from telegram import Message
  8. from plugins.platforms.telegram.adapter import TelegramAdapter
  9. def mentions_other_participants(adapter: "TelegramAdapter", message: "Message") -> bool:
  10. """True when a ``mention``/``text_mention`` entity names someone other than this bot."""
  11. return any(
  12. _is_other_participant(adapter, text, entity)
  13. for text, entity in _mention_entities(adapter, message)
  14. )
  15. def _mention_entities(adapter: "TelegramAdapter", message: "Message"):
  16. """``(source_text, entity)`` for every ``mention``/``text_mention`` in the text and caption."""
  17. for source_text, entities in adapter._entity_sources(message):
  18. for entity in entities:
  19. if adapter._entity_type(entity) in {"mention", "text_mention"}:
  20. yield source_text, entity
  21. def _is_other_participant(adapter: "TelegramAdapter", source_text: str, entity) -> bool:
  22. if adapter._entity_type(entity) == "text_mention":
  23. user = getattr(entity, "user", None)
  24. bot_id = getattr(adapter._bot, "id", None) if adapter._bot else None
  25. return user is not None and getattr(user, "id", None) != bot_id
  26. handle = (adapter._entity_span(source_text, entity) or "").strip().lstrip("@").lower()
  27. return bool(handle) and handle != adapter._current_bot_username()
  28. def starts_with_other_participant_mention(adapter: "TelegramAdapter", message: "Message") -> bool:
  29. return any(
  30. getattr(entity, "offset", None) == len(text) - len(text.lstrip())
  31. and _is_other_participant(adapter, text, entity)
  32. for text, entity in _mention_entities(adapter, message)
  33. )
  34. def _quoted_reply(message: "Message") -> Optional["Message"]:
  35. """The message this one replies to, or None. In a forum topic Telegram also sets ``reply_to_message``
  36. to the topic's root on every plain message; that anchor is not a reply to a person."""
  37. replied = getattr(message, "reply_to_message", None)
  38. if replied is None or (getattr(message, "is_topic_message", False)
  39. and getattr(replied, "message_id", None) == getattr(message, "message_thread_id", None)):
  40. return None
  41. return replied
  42. def group_reply_expected(adapter: "TelegramAdapter", message: "Message", chat_type: str) -> Optional[bool]:
  43. """Whether an admitted message needs a reply; None keeps the visible silence fallback."""
  44. if chat_type != "group":
  45. return True if chat_type == "dm" else None
  46. text = getattr(message, "text", None) or getattr(message, "caption", None) or ""
  47. addressed_to_bot = (
  48. text.lstrip().startswith("/")
  49. or adapter._is_reply_to_bot(message)
  50. or adapter._message_mentions_bot(message)
  51. or adapter._message_matches_mention_patterns(message)
  52. )
  53. if addressed_to_bot:
  54. return True
  55. if not adapter._bot or not adapter._current_bot_username():
  56. return None
  57. if (replied := _quoted_reply(message)) is not None:
  58. # Only a reply to another known member is chatter. An unknown author, or a post signed by a chat
  59. # (a linked channel's auto-forward, an anonymous admin; Telegram fills from_user with a service
  60. # account there), may still be meant for the bot.
  61. unknown = getattr(replied, "from_user", None) is None or getattr(replied, "sender_chat", None) is not None
  62. return None if unknown else False
  63. if starts_with_other_participant_mention(adapter, message):
  64. return False
  65. # Words in a voice note, video note or audio file are not in the message text, so the "?" rule cannot read them.
  66. spoken = not text and any(getattr(message, kind, None) for kind in ("voice", "video_note", "audio"))
  67. return None if "?" in text or spoken else False
  68. def group_trigger_text(adapter: "TelegramAdapter", message: "Message", text: Optional[str]) -> Optional[str]:
  69. """Strip our own handle only when we are the sole addressee. With other participants named,
  70. ``@research_bot , @ops_bot are you both listening?`` must not reach us as ``, @ops_bot …``."""
  71. if adapter._is_group_chat(message) and mentions_other_participants(adapter, message):
  72. return text
  73. return adapter._clean_bot_trigger_text(text)
  74. def group_identity_prompt(
  75. adapter: "TelegramAdapter", message: "Message", channel_prompt: Optional[str],
  76. ) -> Optional[str]:
  77. """Session-stable identity line so the model can read retained @mentions as itself or not."""
  78. if not adapter._is_group_chat(message) or not getattr(adapter, "_bot", None):
  79. return channel_prompt
  80. username = adapter._current_bot_username()
  81. if not username:
  82. return channel_prompt
  83. identity = (
  84. f"Your Telegram bot username in this group: @{username}. "
  85. "Mentions of other bots are not requests for you to relay the message."
  86. )
  87. return f"{channel_prompt}\n\n{identity}" if channel_prompt else identity