Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
merge: resolve PR #1796 conflicts with main
Protocol Zeroc9cc16060002
diff --cc nanobot/channels/telegram.pyindex f11c1e10e,9ffc20825..f62537cb2--- a/nanobot/channels/telegram.py+++ b/nanobot/channels/telegram.py@@@ -460,8 -482,137 +482,138 @@@ class TelegramChannel(BaseChannel)"is_group": message.chat.type != "private","message_thread_id": getattr(message, "message_thread_id", None),"is_forum": bool(getattr(message.chat, "is_forum", False)),+ "reply_to_message_id": getattr(reply_to, "message_id", None) if reply_to else None,}+ @staticmethod+ def _extract_reply_context(message) -> str | None:+ """Extract text from the message being replied to, if any."""+ reply = getattr(message, "reply_to_message", None)+ if not reply:+ return None+ text = getattr(reply, "text", None) or getattr(reply, "caption", None) or ""+ if len(text) > TELEGRAM_REPLY_CONTEXT_MAX_LEN:+ text = text[:TELEGRAM_REPLY_CONTEXT_MAX_LEN] + "..."+ return f"[Reply to: {text}]" if text else None++ async def _download_message_media(+ self, msg, *, add_failure_content: bool = False+ ) -> tuple[list[str], list[str]]:+ """Download media from a message (current or reply). Returns (media_paths, content_parts)."""+ media_file = None+ media_type = None+ if getattr(msg, "photo", None):+ media_file = msg.photo[-1]+ media_type = "image"+ elif getattr(msg, "voice", None):+ media_file = msg.voice+ media_type = "voice"+ elif getattr(msg, "audio", None):+ media_file = msg.audio+ media_type = "audio"+ elif getattr(msg, "document", None):+ media_file = msg.document+ media_type = "file"+ elif getattr(msg, "video", None):+ media_file = msg.video+ media_type = "video"+ elif getattr(msg, "video_note", None):+ media_file = msg.video_note+ media_type = "video"+ elif getattr(msg, "animation", None):+ media_file = msg.animation+ media_type = "animation"+ if not media_file or not self._app:+ return [], []+ try:+ file = await self._app.bot.get_file(media_file.file_id)+ ext = self._get_extension(+ media_type,+ getattr(media_file, "mime_type", None),+ getattr(media_file, "file_name", None),+ )+ media_dir = get_media_dir("telegram")- file_path = media_dir / f"{media_file.file_id[:16]}{ext}"++ unique_id = getattr(media_file, "file_unique_id", media_file.file_id)++ file_path = media_dir / f"{unique_id}{ext}"+ await file.download_to_drive(str(file_path))+ path_str = str(file_path)+ if media_type in ("voice", "audio"):+ transcription = await self.transcribe_audio(file_path)+ if transcription:+ logger.info("Transcribed {}: {}...", media_type, transcription[:50])+ return [path_str], [f"[transcription: {transcription}]"]+ return [path_str], [f"[{media_type}: {path_str}]"]+ return [path_str], [f"[{media_type}: {path_str}]"]+ except Exception as e:+ logger.warning("Failed to download message media: {}", e)+ if add_failure_content:+ return [], [f"[{media_type}: download failed]"]+ return [], []++ async def _ensure_bot_identity(self) -> tuple[int | None, str | None]:+ """Load bot identity once and reuse it for mention/reply checks."""+ if self._bot_user_id is not None or self._bot_username is not None:+ return self._bot_user_id, self._bot_username+ if not self._app:+ return None, None+ bot_info = await self._app.bot.get_me()+ self._bot_user_id = getattr(bot_info, "id", None)+ self._bot_username = getattr(bot_info, "username", None)+ return self._bot_user_id, self._bot_username++ @staticmethod+ def _has_mention_entity(+ text: str,+ entities,+ bot_username: str,+ bot_id: int | None,+ ) -> bool:+ """Check Telegram mention entities against the bot username."""+ handle = f"@{bot_username}".lower()+ for entity in entities or []:+ entity_type = getattr(entity, "type", None)+ if entity_type == "text_mention":+ user = getattr(entity, "user", None)+ if user is not None and bot_id is not None and getattr(user, "id", None) == bot_id:+ return True+ continue+ if entity_type != "mention":+ continue+ offset = getattr(entity, "offset", None)+ length = getattr(entity, "length", None)+ if offset is None or length is None:+ continue+ if text[offset : offset + length].lower() == handle:+ return True+ return handle in text.lower()++ 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":+ return True++ bot_id, bot_username = await self._ensure_bot_identity()+ if bot_username:+ text = message.text or ""+ caption = message.caption or ""+ if self._has_mention_entity(+ text,+ getattr(message, "entities", None),+ bot_username,+ bot_id,+ ):+ return True+ if self._has_mention_entity(+ caption,+ getattr(message, "caption_entities", None),+ bot_username,+ bot_id,+ ):+ return True++ reply_user = getattr(getattr(message, "reply_to_message", None), "from_user", None)+ return bool(bot_id and reply_user and reply_user.id == bot_id)+def _remember_thread_context(self, message) -> None:"""Cache topic thread id by chat/message id for follow-up replies."""message_thread_id = getattr(message, "message_thread_id", None)diff --cc tests/test_telegram_channel.pyindex 6b0e8d2a9,70feef5d4..be09e82ab--- a/tests/test_telegram_channel.py+++ b/tests/test_telegram_channel.py@@@ -189,53 -232,368 +232,418 @@@ async def test_send_reply_infers_topic_@pytest.mark.asyncio- async def test_on_message_uses_file_unique_id_for_downloaded_media(monkeypatch, tmp_path) -> None:- config = TelegramConfig(enabled=True, token="123:abc", allow_from=["*"])- channel = TelegramChannel(config, MessageBus())+ async def test_group_policy_mention_ignores_unmentioned_group_message() -> None:+ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="mention"),+ MessageBus(),+ )channel._app = _FakeApp(lambda: None)- downloaded: dict[str, str] = {}+ handled = []++ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)++ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ await channel._on_message(_make_telegram_update(text="hello everyone"), None)++ assert handled == []+ assert channel._app.bot.get_me_calls == 1- class _FakeDownloadedFile:- async def download_to_drive(self, path: str) -> None:- downloaded["path"] = path-- channel._app.bot.file = _FakeDownloadedFile()-- captured: dict[str, object] = {}-- async def _capture_message(**kwargs) -> None:- captured.update(kwargs)-- monkeypatch.setattr(channel, "_handle_message", _capture_message)- monkeypatch.setattr(channel, "_start_typing", lambda _chat_id: None)- monkeypatch.setattr("nanobot.channels.telegram.get_media_dir", lambda _name=None: tmp_path)-- update = SimpleNamespace(- effective_user=SimpleNamespace(id=123, username="alice", first_name="Alice"),- message=SimpleNamespace(- message_id=1,- chat=SimpleNamespace(type="private", is_forum=False),- chat_id=456,- text=None,- caption=None,- photo=[- SimpleNamespace(- file_id="file-id-that-should-not-be-used",- file_unique_id="stable-unique-id",- mime_type="image/jpeg",- file_name=None,- )- ],- voice=None,- audio=None,- document=None,- media_group_id=None,- message_thread_id=None,- ),++ @pytest.mark.asyncio+ async def test_group_policy_mention_accepts_text_mention_and_caches_bot_identity() -> None:+ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="mention"),+ MessageBus(),)+ channel._app = _FakeApp(lambda: None)++ handled = []++ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)++ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ mention = SimpleNamespace(type="mention", offset=0, length=13)+ await channel._on_message(_make_telegram_update(text="@nanobot_test hi", entities=[mention]), None)+ await channel._on_message(_make_telegram_update(text="@nanobot_test again", entities=[mention]), None)++ assert len(handled) == 2+ assert channel._app.bot.get_me_calls == 1+++ @pytest.mark.asyncio+ async def test_group_policy_mention_accepts_caption_mention() -> None:+ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="mention"),+ MessageBus(),+ )+ channel._app = _FakeApp(lambda: None)++ handled = []++ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)++ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ mention = SimpleNamespace(type="mention", offset=0, length=13)+ await channel._on_message(+ _make_telegram_update(caption="@nanobot_test photo", caption_entities=[mention]),+ None,+ )++ assert len(handled) == 1+ assert handled[0]["content"] == "@nanobot_test photo"+++ @pytest.mark.asyncio+ async def test_group_policy_mention_accepts_reply_to_bot() -> None:+ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="mention"),+ MessageBus(),+ )+ channel._app = _FakeApp(lambda: None)++ handled = []++ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)++ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ reply = SimpleNamespace(from_user=SimpleNamespace(id=999))+ await channel._on_message(_make_telegram_update(text="reply", reply_to_message=reply), None)++ assert len(handled) == 1+++ @pytest.mark.asyncio+ async def test_group_policy_open_accepts_plain_group_message() -> None:+ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="open"),+ MessageBus(),+ )+ channel._app = _FakeApp(lambda: None)++ handled = []++ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)++ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ await channel._on_message(_make_telegram_update(text="hello group"), None)++ assert len(handled) == 1+ assert channel._app.bot.get_me_calls == 0+++ def test_extract_reply_context_no_reply() -> None:+ """When there is no reply_to_message, _extract_reply_context returns None."""+ message = SimpleNamespace(reply_to_message=None)+ assert TelegramChannel._extract_reply_context(message) is None+++ def test_extract_reply_context_with_text() -> None:+ """When reply has text, return prefixed string."""+ reply = SimpleNamespace(text="Hello world", caption=None)+ message = SimpleNamespace(reply_to_message=reply)+ assert TelegramChannel._extract_reply_context(message) == "[Reply to: Hello world]"+++ def test_extract_reply_context_with_caption_only() -> None:+ """When reply has only caption (no text), caption is used."""+ reply = SimpleNamespace(text=None, caption="Photo caption")+ message = SimpleNamespace(reply_to_message=reply)+ assert TelegramChannel._extract_reply_context(message) == "[Reply to: Photo caption]"+++ def test_extract_reply_context_truncation() -> None:+ """Reply text is truncated at TELEGRAM_REPLY_CONTEXT_MAX_LEN."""+ long_text = "x" * (TELEGRAM_REPLY_CONTEXT_MAX_LEN + 100)+ reply = SimpleNamespace(text=long_text, caption=None)+ message = SimpleNamespace(reply_to_message=reply)+ result = TelegramChannel._extract_reply_context(message)+ assert result is not None+ assert result.startswith("[Reply to: ")+ assert result.endswith("...]")+ assert len(result) == len("[Reply to: ]") + TELEGRAM_REPLY_CONTEXT_MAX_LEN + len("...")+++ def test_extract_reply_context_no_text_returns_none() -> None:+ """When reply has no text/caption, _extract_reply_context returns None (media handled separately)."""+ reply = SimpleNamespace(text=None, caption=None)+ message = SimpleNamespace(reply_to_message=reply)+ assert TelegramChannel._extract_reply_context(message) is None++ @pytest.mark.asyncio+ async def test_on_message_includes_reply_context() -> None:+ """When user replies to a message, content passed to bus starts with reply context."""+ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="open"),+ MessageBus(),+ )+ channel._app = _FakeApp(lambda: None)+ handled = []+ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)+ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ reply = SimpleNamespace(text="Hello", message_id=2, from_user=SimpleNamespace(id=1))+ update = _make_telegram_update(text="translate this", reply_to_message=reply)await channel._on_message(update, None)+ assert len(handled) == 1+ assert handled[0]["content"].startswith("[Reply to: Hello]")+ assert "translate this" in handled[0]["content"]+++ @pytest.mark.asyncio+ async def test_download_message_media_returns_path_when_download_succeeds(+ monkeypatch, tmp_path+ ) -> None:+ """_download_message_media returns (paths, content_parts) when bot.get_file and download succeed."""+ media_dir = tmp_path / "media" / "telegram"+ media_dir.mkdir(parents=True)+ monkeypatch.setattr(+ "nanobot.channels.telegram.get_media_dir",+ lambda channel=None: media_dir if channel else tmp_path / "media",+ )++ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),+ MessageBus(),+ )+ channel._app = _FakeApp(lambda: None)+ channel._app.bot.get_file = AsyncMock(+ return_value=SimpleNamespace(download_to_drive=AsyncMock(return_value=None))+ )++ msg = SimpleNamespace(+ photo=[SimpleNamespace(file_id="fid123", mime_type="image/jpeg")],+ voice=None,+ audio=None,+ document=None,+ video=None,+ video_note=None,+ animation=None,+ )+ paths, parts = await channel._download_message_media(msg)+ assert len(paths) == 1+ assert len(parts) == 1+ assert "fid123" in paths[0]+ assert "[image:" in parts[0]++++async def test_download_message_media_uses_file_unique_id_when_available(++ monkeypatch, tmp_path++) -> None:++ media_dir = tmp_path / "media" / "telegram"++ media_dir.mkdir(parents=True)++ monkeypatch.setattr(++ "nanobot.channels.telegram.get_media_dir",++ lambda channel=None: media_dir if channel else tmp_path / "media",++ )++++ downloaded: dict[str, str] = {}++++ async def _download_to_drive(path: str) -> None:++ downloaded["path"] = path++++ channel = TelegramChannel(++ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),++ MessageBus(),++ )++ app = _FakeApp(lambda: None)++ app.bot.get_file = AsyncMock(++ return_value=SimpleNamespace(download_to_drive=_download_to_drive)++ )++ channel._app = app++++ msg = SimpleNamespace(++ photo=[++ SimpleNamespace(++ file_id="file-id-that-should-not-be-used",++ file_unique_id="stable-unique-id",++ mime_type="image/jpeg",++ file_name=None,++ )++ ],++ voice=None,++ audio=None,++ document=None,++ video=None,++ video_note=None,++ animation=None,++ )++++ paths, parts = await channel._download_message_media(msg)+++ assert downloaded["path"].endswith("stable-unique-id.jpg")- assert captured["media"] == [str(tmp_path / "stable-unique-id.jpg")]++ assert paths == [str(media_dir / "stable-unique-id.jpg")]++ assert parts == [f"[image: {media_dir / 'stable-unique-id.jpg'}]"]+++++ @pytest.mark.asyncio+ async def test_on_message_attaches_reply_to_media_when_available(monkeypatch, tmp_path) -> None:+ """When user replies to a message with media, that media is downloaded and attached to the turn."""+ media_dir = tmp_path / "media" / "telegram"+ media_dir.mkdir(parents=True)+ monkeypatch.setattr(+ "nanobot.channels.telegram.get_media_dir",+ lambda channel=None: media_dir if channel else tmp_path / "media",+ )++ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="open"),+ MessageBus(),+ )+ app = _FakeApp(lambda: None)+ app.bot.get_file = AsyncMock(+ return_value=SimpleNamespace(download_to_drive=AsyncMock(return_value=None))+ )+ channel._app = app+ handled = []+ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)+ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ reply_with_photo = SimpleNamespace(+ text=None,+ caption=None,+ photo=[SimpleNamespace(file_id="reply_photo_fid", mime_type="image/jpeg")],+ document=None,+ voice=None,+ audio=None,+ video=None,+ video_note=None,+ animation=None,+ )+ update = _make_telegram_update(+ text="what is the image?",+ reply_to_message=reply_with_photo,+ )+ await channel._on_message(update, None)++ assert len(handled) == 1+ assert handled[0]["content"].startswith("[Reply to: [image:")+ assert "what is the image?" in handled[0]["content"]+ assert len(handled[0]["media"]) == 1+ assert "reply_photo_fid" in handled[0]["media"][0]+++ @pytest.mark.asyncio+ async def test_on_message_reply_to_media_fallback_when_download_fails() -> None:+ """When reply has media but download fails, no media attached and no reply tag."""+ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="open"),+ MessageBus(),+ )+ channel._app = _FakeApp(lambda: None)+ channel._app.bot.get_file = None+ handled = []+ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)+ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ reply_with_photo = SimpleNamespace(+ text=None,+ caption=None,+ photo=[SimpleNamespace(file_id="x", mime_type="image/jpeg")],+ document=None,+ voice=None,+ audio=None,+ video=None,+ video_note=None,+ animation=None,+ )+ update = _make_telegram_update(text="what is this?", reply_to_message=reply_with_photo)+ await channel._on_message(update, None)++ assert len(handled) == 1+ assert "what is this?" in handled[0]["content"]+ assert handled[0]["media"] == []+++ @pytest.mark.asyncio+ async def test_on_message_reply_to_caption_and_media(monkeypatch, tmp_path) -> None:+ """When replying to a message with caption + photo, both text context and media are included."""+ media_dir = tmp_path / "media" / "telegram"+ media_dir.mkdir(parents=True)+ monkeypatch.setattr(+ "nanobot.channels.telegram.get_media_dir",+ lambda channel=None: media_dir if channel else tmp_path / "media",+ )++ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="open"),+ MessageBus(),+ )+ app = _FakeApp(lambda: None)+ app.bot.get_file = AsyncMock(+ return_value=SimpleNamespace(download_to_drive=AsyncMock(return_value=None))+ )+ channel._app = app+ handled = []+ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)+ channel._handle_message = capture_handle+ channel._start_typing = lambda _chat_id: None++ reply_with_caption_and_photo = SimpleNamespace(+ text=None,+ caption="A cute cat",+ photo=[SimpleNamespace(file_id="cat_fid", mime_type="image/jpeg")],+ document=None,+ voice=None,+ audio=None,+ video=None,+ video_note=None,+ animation=None,+ )+ update = _make_telegram_update(+ text="what breed is this?",+ reply_to_message=reply_with_caption_and_photo,+ )+ await channel._on_message(update, None)++ assert len(handled) == 1+ assert "[Reply to: A cute cat]" in handled[0]["content"]+ assert "what breed is this?" in handled[0]["content"]+ assert len(handled[0]["media"]) == 1+ assert "cat_fid" in handled[0]["media"][0]+++ @pytest.mark.asyncio+ async def test_forward_command_does_not_inject_reply_context() -> None:+ """Slash commands forwarded via _forward_command must not include reply context."""+ channel = TelegramChannel(+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], group_policy="open"),+ MessageBus(),+ )+ channel._app = _FakeApp(lambda: None)+ handled = []+ async def capture_handle(**kwargs) -> None:+ handled.append(kwargs)+ channel._handle_message = capture_handle++ reply = SimpleNamespace(text="some old message", message_id=2, from_user=SimpleNamespace(id=1))+ update = _make_telegram_update(text="/new", reply_to_message=reply)+ await channel._forward_command(update, None)++ assert len(handled) == 1+ assert handled[0]["content"] == "/new"