The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): bots_require_mention gates bot quote-replies behind an explicit @mention (closes #106430)
Konstantin Khlopkov1a981d8e83f9
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 5dcccfb2063..e1a9fef9780 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -5049,6 +5049,13 @@ class TelegramAdapter(BasePlatformAdapter):"""Return whether explicit @...bot mentions exclusively route group messages."""return self._extra_bool("exclusive_bot_mentions", "TELEGRAM_EXCLUSIVE_BOT_MENTIONS", "true")+ def _telegram_bots_require_mention(self) -> bool:+ """Whether another bot's message must explicitly @mention us (a quote-reply alone won't);+ breaks two-bot reply loops in groups while human replies stay unaffected."""+ return self._extra_bool(+ "bots_require_mention", "TELEGRAM_BOTS_REQUIRE_MENTION", "false"+ )+def _telegram_free_response_chats(self) -> set[str]:return self._extra_str_set("free_response_chats", "TELEGRAM_FREE_RESPONSE_CHATS")@@ -5608,6 +5615,16 @@ class TelegramAdapter(BasePlatformAdapter):user_id = getattr(from_user, "id", None)return bot_id is not None and user_id is not None and bot_id == user_id+ def _sender_is_other_bot(self, message: Message) -> bool:+ """True when the sender is a bot other than this one (this bot's own echoes are already+ filtered by ``_is_own_message``)."""+ sender = getattr(message, "from_user", None)+ if sender is None or not getattr(sender, "is_bot", False):+ return False+ bot_id = getattr(self._bot, "id", None)+ sender_id = getattr(sender, "id", None)+ return bot_id is None or sender_id is None or sender_id != bot_id+def _should_process_message(self, message: Message, *, is_command: bool = False) -> bool:"""Apply Telegram group trigger rules: DMs unrestricted; group messages pass ``allowed_chats`` (hard gate; onlythe ``guest_mode`` @mention bypass crosses it) and then any of free_response chat/topic, ``require_mention``@@ -5637,6 +5654,14 @@ class TelegramAdapter(BasePlatformAdapter):return guest_mentionif guest_mention or chat_id_str in self._telegram_free_response_chats() or self._telegram_is_free_response_topic(message):return True+ # Bot-to-bot loop breaker: another bot must explicitly @mention us; its quote-reply or+ # plain chatter does not count (two bots answering each other's replies never stop otherwise).+ if (+ self._telegram_bots_require_mention()+ and self._sender_is_other_bot(message)+ and not self._message_mentions_bot(message)+ ):+ return Falseif not self._telegram_require_mention() or self._is_reply_to_bot(message):return Trueif not self._telegram_guest_mode() and self._message_mentions_bot(message):@@ -6484,6 +6509,7 @@ def _apply_yaml_config(yaml_cfg: dict, telegram_cfg: dict) -> dict | None:_set_env("TELEGRAM_MENTION_PATTERNS", _json.dumps(telegram_cfg["mention_patterns"]))for key, env in (("exclusive_bot_mentions", "TELEGRAM_EXCLUSIVE_BOT_MENTIONS"), ("allow_bots", "TELEGRAM_ALLOW_BOTS"),+ ("bots_require_mention", "TELEGRAM_BOTS_REQUIRE_MENTION"),("guest_mode", "TELEGRAM_GUEST_MODE", ), ("observe_unmentioned_group_messages", "TELEGRAM_OBSERVE_UNMENTIONED_GROUP_MESSAGES")):_bridge_lower(key, env)# No extras seed for allowed_chats / allowed_topics / group_allowed_chats: the shared-key loop alreadydiff --git a/tests/gateway/test_telegram_group_gating.py b/tests/gateway/test_telegram_group_gating.pyindex 73c932b929b..5a51c56e502 100644--- a/tests/gateway/test_telegram_group_gating.py+++ b/tests/gateway/test_telegram_group_gating.py@@ -22,6 +22,7 @@ def _make_adapter(group_allowed_chats=None,guest_mode=None,observe_unmentioned_group_messages=None,+ bots_require_mention=None,bot_username="hermes_bot",):from plugins.platforms.telegram.adapter import TelegramAdapter@@ -65,6 +66,8 @@ def _make_adapter(extra["guest_mode"] = guest_modeif observe_unmentioned_group_messages is not None:extra["observe_unmentioned_group_messages"] = observe_unmentioned_group_messages+ if bots_require_mention is not None:+ extra["bots_require_mention"] = bots_require_mentionadapter = object.__new__(TelegramAdapter)adapter.platform = Platform.TELEGRAM@@ -883,3 +886,91 @@ def test_identity_freshness_does_not_depend_on_host_uptime(monkeypatch):adapter._note_bot_username("new_helper_bot")assert adapter._bot_identity_is_fresh() is True+++def _bot_sender_message(+ text="hello", *, chat_id=-100, sender_id=555, reply_to_bot=False, entities=None+):+ """Group message authored by another bot (is_bot=True, id != this bot's 999)."""+ msg = _group_message(+ text,+ chat_id=chat_id,+ from_user_id=sender_id,+ reply_to_bot=reply_to_bot,+ entities=entities,+ )+ msg.from_user.is_bot = True+ return msg+++def test_bots_require_mention_defaults_off():+ adapter = _make_adapter(require_mention=True)++ assert adapter._telegram_bots_require_mention() is False+++def test_bot_quote_reply_loop_is_broken_by_bots_require_mention():+ """With require_mention alone the quote-reply-to-bot branch returns True unconditionally, so+ two bots admitting each other's messages answer each other forever. The flag closes exactly+ that path; a bot message that does @mention this bot still goes through."""+ loop_adapter = _make_adapter(require_mention=True)+ assert (+ loop_adapter._should_process_message(+ _bot_sender_message("auto-reply", reply_to_bot=True)+ )+ is True+ )++ gated = _make_adapter(require_mention=True, bots_require_mention=True)+ assert (+ gated._should_process_message(+ _bot_sender_message("auto-reply", reply_to_bot=True)+ )+ is False+ )++ text = "@hermes_bot ping"+ assert (+ gated._should_process_message(+ _bot_sender_message(text, entities=[_mention_entity(text)])+ )+ is True+ )+++def test_bot_command_at_botname_passes_bots_require_mention():+ gated = _make_adapter(require_mention=True, bots_require_mention=True)+ text = "/status@hermes_bot"+ msg = _bot_sender_message(text, entities=[_bot_command_entity(text, text)])++ assert gated._should_process_message(msg, is_command=True) is True+++def test_bot_chatter_without_mention_dropped_by_bots_require_mention():+ gated = _make_adapter(require_mention=True, bots_require_mention=True)++ assert (+ gated._should_process_message(+ _bot_sender_message("status update, no addressee")+ )+ is False+ )+++def test_human_reply_unaffected_by_bots_require_mention():+ gated = _make_adapter(require_mention=True, bots_require_mention=True)++ assert (+ gated._should_process_message(_group_message("replying", reply_to_bot=True))+ is True+ )+++def test_own_echoes_not_treated_as_other_bot():+ """This bot's own echoed messages are dropped by _is_own_message before the sender gate; the+ gate must not re-admit them as another bot even if the echo carries a stale is_bot flag."""+ gated = _make_adapter(require_mention=True, bots_require_mention=True)+ own = _bot_sender_message("echo", sender_id=999)++ assert gated._is_own_message(own) is True+ assert gated._sender_is_other_bot(own) is Falsediff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.mdindex 0849306b17a..66557f8a740 100644--- a/website/docs/reference/environment-variables.md+++ b/website/docs/reference/environment-variables.md@@ -330,6 +330,7 @@ These are set automatically by the Docker terminal backend when `proxy.enabled:| `TELEGRAM_REQUIRE_MENTION` | Require an explicit trigger before responding in Telegram groups. Equivalent to `telegram.require_mention` in `config.yaml`. || `TELEGRAM_MENTION_PATTERNS` | JSON array, newline-separated list, or comma-separated list of regex wake-word patterns accepted when Telegram group mention gating is enabled. Equivalent to `telegram.mention_patterns`. || `TELEGRAM_EXCLUSIVE_BOT_MENTIONS` | When enabled, explicit `@...bot` mentions in Telegram groups route only to the mentioned bot usernames before reply or wake-word fallbacks run. Default: `true`. Equivalent to `telegram.exclusive_bot_mentions`. |+| `TELEGRAM_BOTS_REQUIRE_MENTION` | When enabled, a message sent by another bot must explicitly `@thisbot` to trigger a response — a quote-reply alone is ignored, which stops two bots from replying to each other forever. Human replies are unaffected. Default: `false`. Equivalent to `telegram.bots_require_mention`. || `TELEGRAM_REPLY_TO_MODE` | Reply-reference behavior: `off`, `first` (default), or `all`. Matches the Discord pattern. || `TELEGRAM_IGNORED_THREADS` | Comma-separated Telegram forum topic/thread IDs where the bot never responds || `TELEGRAM_PROXY` | Proxy URL for Telegram connections — overrides `HTTPS_PROXY`. Supports `http://`, `https://`, `socks5://` |diff --git a/website/docs/user-guide/messaging/telegram.md b/website/docs/user-guide/messaging/telegram.mdindex 79afe3d1d46..d638d4c1f7a 100644--- a/website/docs/user-guide/messaging/telegram.md+++ b/website/docs/user-guide/messaging/telegram.md@@ -578,6 +578,8 @@ telegram:With this setup, a group message like `@research_bot @ops_bot summarize this` is processed by `research_bot` and `ops_bot` only. Other Hermes bots in the group stay silent, even if the message is a reply to one of their earlier messages or would otherwise match a shared wake word.+Two Hermes bots that answer each other's quote-replies can still loop forever with `TELEGRAM_ALLOW_BOTS=all`, because a reply to the bot always passes the `require_mention` gate. Setting `telegram.bots_require_mention: true` (env `TELEGRAM_BOTS_REQUIRE_MENTION`) closes that path: a message from another bot only triggers a response when it explicitly `@mentions` this bot, while human replies keep working unchanged.+Group conversation text and media captions keep every mention when the message names other participants too (`@research_bot , @ops_bot are you both listening?` reaches `research_bot` verbatim); when this bot is the only one addressed, its own handle is still stripped so short answers such as `@hermes_bot 2` keep working. Group turns also carry the bot's own Telegram username in the per-channel context so the model can tell which retained mentions are for it. Slash commands still use the normal command-trigger cleanup.Set `exclusive_bot_mentions: false` only for legacy groups where explicit mentions should not override reply and wake-word triggers.diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.mdindex 2076f2b0fd8..344da8bfe97 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md@@ -252,6 +252,7 @@ description: "Hermes Agent 使用的所有环境变量完整参考"| `TELEGRAM_REQUIRE_MENTION` | 在 Telegram 群组中响应前要求显式触发。等同于 `config.yaml` 中的 `telegram.require_mention`。 || `TELEGRAM_MENTION_PATTERNS` | 启用 Telegram 群组 mention 门控时接受的正则唤醒词模式,JSON 数组、换行分隔列表或逗号分隔列表。等同于 `telegram.mention_patterns`。 || `TELEGRAM_EXCLUSIVE_BOT_MENTIONS` | 启用后,Telegram 群组中的显式 `@...bot` mention 仅路由到被 mention 的 bot 用户名,然后再执行回复或唤醒词回退。默认:`true`。等同于 `telegram.exclusive_bot_mentions`。 |+| `TELEGRAM_BOTS_REQUIRE_MENTION` | 启用后,其他 bot 发送的消息必须显式 `@本bot` 才会触发回复——仅引用回复会被忽略,从而避免两个 bot 互相回复形成死循环。人类用户的回复不受影响。默认:`false`。等同于 `telegram.bots_require_mention`。 || `TELEGRAM_REPLY_TO_MODE` | 回复引用行为:`off`、`first`(默认)或 `all`。与 Discord 模式一致。 || `TELEGRAM_IGNORED_THREADS` | bot 永不响应的逗号分隔 Telegram 论坛话题/线程 ID || `TELEGRAM_PROXY` | Telegram 连接的代理 URL——覆盖 `HTTPS_PROXY`。支持 `http://`、`https://`、`socks5://` |