Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(partners): add Telegram per-chat response policies (#1667)

XZHfaac4ec7a3aa
diff --git a/deeptutor/partners/channels/telegram.py b/deeptutor/partners/channels/telegram.py
index 1a8b582f9..5f240375a 100644
--- a/deeptutor/partners/channels/telegram.py
+++ b/deeptutor/partners/channels/telegram.py
@@ -10,7 +10,7 @@ from typing import Any, Literal
import unicodedata
from loguru import logger
-from pydantic import Field
+from pydantic import Field, model_validator
from telegram import BotCommand, ReplyParameters, Update
from telegram.error import BadRequest, TimedOut
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
@@ -19,7 +19,7 @@ from telegram.request import HTTPXRequest
from deeptutor.partners.bus.events import OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
from deeptutor.partners.channels.base import BaseChannel
-from deeptutor.partners.config.schema import DeliveryOverrides, StreamingSupport
+from deeptutor.partners.config.schema import Base, DeliveryOverrides, StreamingSupport
from deeptutor.partners.helpers import (
is_markdown_table_separator_row,
split_markdown_table_row,
@@ -48,6 +48,28 @@ class _StreamBuf:
stream_id: str | None = None
+class TelegramChatPolicy(Base):
+ """Per-chat inbound response policy."""
+
+ chat_id: int = Field(description="Telegram chat id this rule applies to.")
+ policy: Literal["open", "mention", "topics_only"] = Field(
+ description=(
+ "open responds to every message; mention requires an explicit mention or bot reply; "
+ "topics_only responds without a mention only in allowed_topics."
+ )
+ )
+ allowed_topics: list[int] = Field(
+ default_factory=list,
+ description="Telegram message_thread_id values that may receive automatic replies.",
+ )
+
+ @model_validator(mode="after")
+ def _require_allowed_topics(self) -> "TelegramChatPolicy":
+ if self.policy == "topics_only" and not self.allowed_topics:
+ raise ValueError("topics_only policy requires at least one allowed topic")
+ return self
+
+
def _strip_md_block(text: str) -> str:
"""Strip block-level and inline markdown for readable plain-text preview.
@@ -201,6 +223,10 @@ class TelegramConfig(DeliveryOverrides, StreamingSupport):
proxy: str | None = None
reply_to_message: bool = False
group_policy: Literal["open", "mention"] = "mention"
+ chat_policies: list[TelegramChatPolicy] = Field(
+ default_factory=list,
+ description="Per-chat overrides; the first matching chat_id wins.",
+ )
# Outbound API connection pool; long-polling uses its own small pool so
# getUpdates never starves sends.
connection_pool_size: int = 16
@@ -746,6 +772,12 @@ class TelegramChannel(BaseChannel):
return None
return f"telegram:{message.chat_id}:topic:{message_thread_id}"
+ def _matching_chat_policy(self, chat_id: int) -> TelegramChatPolicy | None:
+ for rule in self.config.chat_policies:
+ if rule.chat_id == chat_id:
+ return rule
+ return None
+
@staticmethod
def _build_message_metadata(message, user) -> dict:
"""Build common Telegram inbound metadata payload."""
@@ -865,7 +897,17 @@ class TelegramChannel(BaseChannel):
async def _is_group_message_for_bot(self, message) -> bool:
"""Allow group messages when policy is open, @mentioned, or replying to the bot."""
- if message.chat.type == "private" or self.config.group_policy == "open":
+ if message.chat.type == "private":
+ return True
+
+ chat_policy = self._matching_chat_policy(message.chat_id)
+ policy = chat_policy.policy if chat_policy is not None else self.config.group_policy
+ if policy == "open":
+ return True
+ if (
+ policy == "topics_only"
+ and getattr(message, "message_thread_id", None) in chat_policy.allowed_topics
+ ):
return True
bot_id, bot_username = await self._ensure_bot_identity()
diff --git a/tests/services/partners/test_telegram_channel.py b/tests/services/partners/test_telegram_channel.py
new file mode 100644
index 000000000..9089502f1
--- /dev/null
+++ b/tests/services/partners/test_telegram_channel.py
@@ -0,0 +1,218 @@
+"""Unit tests for the Telegram inbound chat and topic response policy."""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+from pydantic import ValidationError
+import pytest
+
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.telegram import TelegramChannel, TelegramConfig
+
+
+def _make_channel(**overrides) -> TelegramChannel:
+ defaults = {
+ "enabled": True,
+ "token": "secret-token-123",
+ "allow_from": ["*"],
+ "group_policy": "mention",
+ }
+ defaults.update(overrides)
+ config = TelegramConfig.model_validate(defaults)
+ bus = MagicMock(spec=MessageBus)
+ bus.publish_inbound = AsyncMock()
+ channel = TelegramChannel(config, bus)
+ channel._bot_user_id = 999
+ channel._bot_username = "tutorbot"
+ return channel
+
+
+def _group_message(
+ *,
+ chat_id: int = -1003921765626,
+ topic_id: int | None = None,
+ text: str = "hello",
+ reply_to_bot: bool = False,
+) -> SimpleNamespace:
+ reply_from = SimpleNamespace(id=999) if reply_to_bot else SimpleNamespace(id=42)
+ return SimpleNamespace(
+ chat=SimpleNamespace(type="supergroup"),
+ chat_id=chat_id,
+ message_thread_id=topic_id,
+ message_id=1000,
+ text=text,
+ caption=None,
+ entities=None,
+ caption_entities=None,
+ reply_to_message=SimpleNamespace(message_id=900, from_user=reply_from),
+ )
+
+
+class TestTelegramConfig:
+ def test_chat_policies_default_to_empty(self) -> None:
+ config = TelegramConfig()
+
+ assert config.group_policy == "mention"
+ assert config.chat_policies == []
+
+ def test_accepts_chat_policy_rules(self) -> None:
+ config = TelegramConfig.model_validate(
+ {
+ "groupPolicy": "mention",
+ "chatPolicies": [
+ {
+ "chatId": -1003921765626,
+ "policy": "topics_only",
+ "allowedTopics": [1, 44, 115],
+ }
+ ],
+ }
+ )
+
+ assert config.chat_policies[0].chat_id == -1003921765626
+ assert config.chat_policies[0].policy == "topics_only"
+ assert config.chat_policies[0].allowed_topics == [1, 44, 115]
+
+ def test_topics_only_requires_topics(self) -> None:
+ with pytest.raises(ValidationError, match="at least one allowed topic"):
+ TelegramConfig(chat_policies=[{"chat_id": -100, "policy": "topics_only"}])
+
+ def test_policy_values_are_not_camel_case(self) -> None:
+ with pytest.raises(ValidationError, match="topics_only"):
+ TelegramConfig.model_validate(
+ {"chat_policies": [{"chat_id": -100, "policy": "topicsOnly"}]}
+ )
+
+ def test_default_config_exposes_chat_policies(self) -> None:
+ default = TelegramChannel.default_config()
+
+ assert default["chatPolicies"] == []
+
+
+class TestGroupMessagePolicy:
+ def test_default_mention_policy_ignores_plain_message(self) -> None:
+ channel = _make_channel()
+
+ assert asyncio.run(channel._is_group_message_for_bot(_group_message())) is False
+
+ def test_global_open_still_applies_to_unlisted_chat(self) -> None:
+ channel = _make_channel(
+ group_policy="open",
+ chat_policies=[{"chat_id": -100, "policy": "mention"}],
+ )
+
+ assert asyncio.run(channel._is_group_message_for_bot(_group_message())) is True
+
+ def test_chat_open_overrides_global_mention(self) -> None:
+ channel = _make_channel(chat_policies=[{"chat_id": -1003921765626, "policy": "open"}])
+
+ assert asyncio.run(channel._is_group_message_for_bot(_group_message())) is True
+
+ def test_chat_mention_overrides_global_open(self) -> None:
+ channel = _make_channel(
+ group_policy="open",
+ chat_policies=[{"chat_id": -1003921765626, "policy": "mention"}],
+ )
+
+ assert asyncio.run(channel._is_group_message_for_bot(_group_message())) is False
+
+ def test_first_matching_chat_policy_wins(self) -> None:
+ channel = _make_channel(
+ chat_policies=[
+ {"chat_id": -1003921765626, "policy": "mention"},
+ {"chat_id": -1003921765626, "policy": "open"},
+ ]
+ )
+
+ assert asyncio.run(channel._is_group_message_for_bot(_group_message())) is False
+
+ def test_topics_only_allows_allowlisted_topic_without_mention(self) -> None:
+ channel = _make_channel(
+ chat_policies=[
+ {
+ "chat_id": -1003921765626,
+ "policy": "topics_only",
+ "allowed_topics": [1, 44, 115],
+ }
+ ]
+ )
+
+ assert asyncio.run(channel._is_group_message_for_bot(_group_message(topic_id=44))) is True
+
+ def test_topics_only_ignores_general_topic(self) -> None:
+ channel = _make_channel(
+ chat_policies=[
+ {
+ "chat_id": -1003921765626,
+ "policy": "topics_only",
+ "allowed_topics": [1, 44, 115],
+ }
+ ]
+ )
+
+ assert (
+ asyncio.run(channel._is_group_message_for_bot(_group_message(topic_id=None))) is False
+ )
+
+ def test_topics_only_ignores_unlisted_topic(self) -> None:
+ channel = _make_channel(
+ chat_policies=[
+ {
+ "chat_id": -1003921765626,
+ "policy": "topics_only",
+ "allowed_topics": [1, 44, 115],
+ }
+ ]
+ )
+
+ assert asyncio.run(channel._is_group_message_for_bot(_group_message(topic_id=116))) is False
+
+ def test_topics_only_still_accepts_mention_in_nonallowed_topic(self) -> None:
+ channel = _make_channel(
+ chat_policies=[
+ {
+ "chat_id": -1003921765626,
+ "policy": "topics_only",
+ "allowed_topics": [44],
+ }
+ ]
+ )
+ message = _group_message(topic_id=116, text="@tutorbot please answer")
+
+ assert asyncio.run(channel._is_group_message_for_bot(message)) is True
+
+ def test_mention_policy_accepts_reply_to_bot(self) -> None:
+ channel = _make_channel()
+
+ assert (
+ asyncio.run(channel._is_group_message_for_bot(_group_message(reply_to_bot=True)))
+ is True
+ )
+
+ def test_private_chat_ignores_chat_policy(self) -> None:
+ channel = _make_channel(chat_policies=[{"chat_id": 42, "policy": "mention"}])
+ message = _group_message(chat_id=42)
+ message.chat.type = "private"
+
+ assert asyncio.run(channel._is_group_message_for_bot(message)) is True
+
+ def test_allow_from_remains_orthogonal(self) -> None:
+ channel = _make_channel(
+ allow_from=[],
+ chat_policies=[{"chat_id": -1003921765626, "policy": "open"}],
+ )
+
+ assert channel.is_allowed("42") is False
+
+
+def test_channel_schema_inlines_chat_policy_items() -> None:
+ from deeptutor.api.routers._partners_channel_schema import channel_schema_payload
+
+ payload = channel_schema_payload(TelegramChannel)
+ rule_schema = payload["json_schema"]["properties"]["chat_policies"]["items"]
+
+ assert rule_schema["type"] == "object"
+ assert {"chat_id", "policy", "allowed_topics"} <= set(rule_schema["properties"])