The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): let a silence marker stand on group messages not addressed to the bot
Diego Sánchezdc6519da4a76
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..7571e79fca4--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1,2 @@+diegoasanch+# PR: fix(telegram) reply_expected for group messages (#120051)diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex ee3390a0e93..c8cfc1298a1 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -6649,11 +6649,11 @@ class TelegramAdapter(TelegramHeldInboundMixin, TelegramTopicRoutingMixin, BasePlambda ev: logger.info("[Telegram] Flushing photo batch %s with %d image(s)", batch_key, len(ev.media_urls)))def _merge_into_pending(self, pending: dict, key: str, event: MessageEvent) -> None:- """Merge ``event`` into ``pending[key]`` (media + caption) or seed it."""- existing = pending.get(key)- if existing is None:- pending[key] = event+ """Merge ``event`` into ``pending[key]`` (media, caption, reply expectation) or seed it."""+ existing = pending.setdefault(key, event)+ if existing is event:return+ existing.absorb_reply_expected(event)existing.media_urls.extend(event.media_urls)existing.media_types.extend(event.media_types)if event.text:@@ -7135,14 +7135,14 @@ class TelegramAdapter(TelegramHeldInboundMixin, TelegramTopicRoutingMixin, BasePis_bot=bool(getattr(user, "is_bot", False)) if user else False)reply_to_id, reply_to_text = self._reply_context(message)from gateway.platforms.base import resolve_channel_prompt # per-channel/topic ephemeral prompt- from plugins.platforms.telegram.telegram_context import group_identity_prompt+ from plugins.platforms.telegram.telegram_context import group_identity_prompt, group_reply_expected_chat_id_str = str(chat.id)channel_prompt = resolve_channel_prompt(self.config.extra, thread_id_str or _chat_id_str, _chat_id_str if thread_id_str else None)return MessageEvent(text=expand_link_entities(message), message_type=msg_type, source=source, raw_message=message,message_id=str(message.message_id), platform_update_id=update_id,reply_to_message_id=reply_to_id, reply_to_text=reply_to_text, auto_skill=topic_skill,- channel_prompt=group_identity_prompt(self, message, channel_prompt),+ channel_prompt=group_identity_prompt(self, message, channel_prompt), reply_expected=group_reply_expected(self, message, chat_type),edit_revision=self._edit_revision(message, update_id), timestamp=message.date)@staticmethoddiff --git a/plugins/platforms/telegram/telegram_context.py b/plugins/platforms/telegram/telegram_context.pyindex b02f9ca3134..3b02abfa903 100644--- a/plugins/platforms/telegram/telegram_context.py+++ b/plugins/platforms/telegram/telegram_context.py@@ -13,20 +13,68 @@ if TYPE_CHECKING:def mentions_other_participants(adapter: "TelegramAdapter", message: "Message") -> bool:"""True when a ``mention``/``text_mention`` entity names someone other than this bot."""- own = adapter._current_bot_username()- bot_id = getattr(adapter._bot, "id", None) if adapter._bot else None+ return any(+ _is_other_participant(adapter, text, entity)+ for text, entity in _mention_entities(adapter, message)+ )+++def _mention_entities(adapter: "TelegramAdapter", message: "Message"):+ """``(source_text, entity)`` for every ``mention``/``text_mention`` in the text and caption."""for source_text, entities in adapter._entity_sources(message):for entity in entities:- entity_type = adapter._entity_type(entity)- if entity_type == "mention":- handle = (adapter._entity_span(source_text, entity) or "").strip().lstrip("@").lower()- if handle and handle != own:- return True- elif entity_type == "text_mention":- user = getattr(entity, "user", None)- if user is not None and getattr(user, "id", None) != bot_id:- return True- return False+ if adapter._entity_type(entity) in {"mention", "text_mention"}:+ yield source_text, entity+++def _is_other_participant(adapter: "TelegramAdapter", source_text: str, entity) -> bool:+ if adapter._entity_type(entity) == "text_mention":+ user = getattr(entity, "user", None)+ bot_id = getattr(adapter._bot, "id", None) if adapter._bot else None+ return user is not None and getattr(user, "id", None) != bot_id+ handle = (adapter._entity_span(source_text, entity) or "").strip().lstrip("@").lower()+ return bool(handle) and handle != adapter._current_bot_username()+++def starts_with_other_participant_mention(adapter: "TelegramAdapter", message: "Message") -> bool:+ return any(+ getattr(entity, "offset", None) == len(text) - len(text.lstrip())+ and _is_other_participant(adapter, text, entity)+ for text, entity in _mention_entities(adapter, message)+ )+++def _replies_to_other_member(adapter: "TelegramAdapter", message: "Message") -> bool:+ """A reply to someone else's message. In a forum topic Telegram also sets ``reply_to_message``+ to the topic's root on every plain message; that anchor is not a reply to a person."""+ replied = getattr(message, "reply_to_message", None)+ if replied is None or adapter._is_reply_to_bot(message):+ return False+ topic_root = (+ getattr(message, "is_topic_message", False)+ and replied.message_id == getattr(message, "message_thread_id", None)+ )+ return not topic_root+++def group_reply_expected(adapter: "TelegramAdapter", message: "Message", chat_type: str) -> Optional[bool]:+ """Whether an admitted message needs a reply; None keeps the visible silence fallback."""+ if chat_type != "group":+ return True if chat_type == "dm" else None+ text = getattr(message, "text", None) or getattr(message, "caption", None) or ""+ addressed_to_bot = (+ text.startswith("/")+ or adapter._is_reply_to_bot(message)+ or adapter._message_mentions_bot(message)+ or adapter._message_matches_mention_patterns(message)+ )+ if addressed_to_bot:+ return True+ if not adapter._bot or not adapter._current_bot_username():+ return None+ if _replies_to_other_member(adapter, message) or starts_with_other_participant_mention(adapter, message):+ return False+ return None if "?" in text else Falsedef group_trigger_text(adapter: "TelegramAdapter", message: "Message", text: Optional[str]) -> Optional[str]:diff --git a/tests/gateway/test_telegram_group_gating.py b/tests/gateway/test_telegram_group_gating.pyindex 10a455cfccf..7b7f96ed445 100644--- a/tests/gateway/test_telegram_group_gating.py+++ b/tests/gateway/test_telegram_group_gating.py@@ -1012,3 +1012,42 @@ def test_sibling_bot_explicit_mention_still_dispatches_and_is_not_observed():human = _group_message("hermes, hello")assert adapter._should_process_message(human) is Trueassert adapter._should_observe_unmentioned_group_message(human) is False+++def _replying_to(message, *, user_id, message_id=10):+ message.reply_to_message = SimpleNamespace(+ from_user=SimpleNamespace(id=user_id), message_id=message_id, text="earlier", caption=None)+ return message++[email protected]("message, expected", [+ (_group_message("@hermes_bot when is rent due?", entities=[_mention_entity("@hermes_bot when is rent due?")]), True),+ (_group_message("sure, saturday", reply_to_bot=True), True),+ (_group_message("hermes, add milk to the list"), True),+ (_group_message("", caption="/status"), True),+ (_dm_message("hello"), True),+ (_replying_to(_group_message("yes, saturday"), user_id=222), False),+ (_group_message("@alice are we buying the fridge?", entities=[_mention_entity("@alice are we buying the fridge?", "@alice")]), False),+ (_group_message("the fridge arrives on saturday"), False),+ (_group_message("are we buying the fridge on saturday?"), None),+ (_group_message("what did @alice say?", entities=[_mention_entity("what did @alice say?", "@alice")]), None),+ (_replying_to(_group_message("anyone up for dinner?", thread_id=5), user_id=222, message_id=5), None),+], ids=[+ "mention", "reply-to-bot", "wake-word", "caption-command", "dm",+ "reply-to-other-member", "opens-with-other-mention", "chatter",+ "question", "mentions-other-mid-question", "forum-topic-root",+])+def test_reply_expected_follows_who_the_group_message_addresses(message, expected):+ adapter = _make_adapter(require_mention=False, mention_patterns=["hermes"])++ assert adapter._build_message_event(message, MessageType.TEXT).reply_expected is expected+++def test_photo_batch_keeps_the_reply_expectation_of_an_addressed_photo():+ adapter = _make_adapter(require_mention=False)+ pending = {}+ for caption in ("just a photo", "/status"):+ event = adapter._build_message_event(_group_message("", caption=caption), MessageType.PHOTO)+ adapter._merge_into_pending(pending, "album", event)++ assert pending["album"].reply_expected is Truediff --git a/tests/gateway/test_telegram_thread_fallback.py b/tests/gateway/test_telegram_thread_fallback.pyindex 9ffd15a3862..21c1ac5fdc3 100644--- a/tests/gateway/test_telegram_thread_fallback.py+++ b/tests/gateway/test_telegram_thread_fallback.py@@ -134,6 +134,8 @@ def _make_adapter():adapter._polling_network_error_count = 0adapter._polling_error_callback_ref = Noneadapter.platform = Platform.TELEGRAM+ adapter._bot = None+ adapter._mention_patterns = []return adapterdiff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.mdindex 4ead952eadd..2e832d57ae2 100644--- a/website/docs/user-guide/messaging/index.md+++ b/website/docs/user-guide/messaging/index.md@@ -154,7 +154,7 @@ user: next messageFailed turns still surface as errors; Hermes does not hide failures just because the text resembles a silence token.-On a message from a person, a bare silence token is replaced by a short notice, because a message that needed a reply must not vanish. Internal wakes such as background-process notifications may stay silent, and so may a message the platform adapter reports as not addressed to the bot. Slack reports this for messages that open by @mentioning someone else and for unmentioned top-level messages that start a new thread in a free-response channel; other platforms always get the notice.+On a message from a person, a bare silence token is replaced by a short notice, because a message that needed a reply must not vanish. Internal wakes such as background-process notifications may stay silent, and so may a message the platform adapter reports as not addressed to the bot. Slack reports this for messages that open by @mentioning someone else and for unmentioned top-level messages that start a new thread in a free-response channel. Telegram reports it for [group messages not addressed to the bot](telegram.md#letting-the-bot-stay-silent-in-a-group). Other platforms always get the notice.## Quick Setupdiff --git a/website/docs/user-guide/messaging/telegram.md b/website/docs/user-guide/messaging/telegram.mdindex 557ecc24a24..84cfbbef7bb 100644--- a/website/docs/user-guide/messaging/telegram.md+++ b/website/docs/user-guide/messaging/telegram.md@@ -645,6 +645,17 @@ Hermes Agent works in Telegram group chats with a few considerations:- Use `telegram.ignored_threads` to keep Hermes silent in specific Telegram forum topics, even when the group would otherwise allow free responses or mention-triggered replies- If `telegram.require_mention` is left unset or false, Hermes keeps the previous open-group behavior and responds to normal group messages it can see+### Letting the bot stay silent in a group++A bot that reads every group message can answer exactly `[SILENT]` (or another [silence token](index.md#intentional-silence-tokens)) when a message doesn't need it. Whether that silence stands depends on who the message addresses:++| Group message | Bare silence token |+|---|---|+| Mentions the bot, replies to it, matches `mention_patterns`, or is a `/command` | Replaced by a short notice, so a question to the bot never vanishes |+| Replies to another member, or opens by @mentioning someone else | Stays silent |+| Any other message without a `?` | Stays silent |+| Any other message with a `?` (it may be a question for the bot) | Replaced by the notice |+### Multiple Hermes bots in one groupIf you run several Hermes profiles in the same Telegram group, create one Telegram bot token per profile and start one gateway per profile. Do not reuse the same bot token in multiple running gateways; Telegram will reject concurrent polling for the same token.