AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(backend/copilot-bot): Telegram adapter — third platform on the chat bus (#13561)
Bently963a6fd2fa55
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex 4b13d27336..fbfd2ecd94 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -235,6 +235,13 @@ AUTOPILOT_BOT_SLACK_CLIENT_ID=AUTOPILOT_BOT_SLACK_CLIENT_SECRET=AUTOPILOT_BOT_SLACK_SIGNING_SECRET=AUTOPILOT_BOT_SLACK_TOKEN=+# Telegram adapter — set the BotFather token + a webhook secret of your choice+# to mount the Telegram webhook route, then register the webhook once:+# curl "https://api.telegram.org/bot<TOKEN>/setWebhook" # -d "url=<PLATFORM_BASE_URL>/api/copilot-webhooks/telegram/updates" # -d "secret_token=<AUTOPILOT_BOT_TELEGRAM_WEBHOOK_SECRET>" # -d "allowed_updates=[\"message\",\"my_chat_member\"]"+# The username (without @) powers the "Add bot to Telegram" t.me link.+AUTOPILOT_BOT_TELEGRAM_TOKEN=+AUTOPILOT_BOT_TELEGRAM_USERNAME=+AUTOPILOT_BOT_TELEGRAM_WEBHOOK_SECRET=# Communication ServicesDISCORD_BOT_TOKEN=diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/registry.py b/autogpt_platform/backend/backend/api/features/platform_linking/registry.pyindex 7bea0dc182..4879df1adc 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/registry.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/registry.py@@ -11,6 +11,7 @@ from pydantic import BaseModel, ConfigDictfrom backend.copilot.bot.adapters.discord import config as discord_configfrom backend.copilot.bot.adapters.slack import config as slack_config+from backend.copilot.bot.adapters.telegram import config as telegram_configfrom backend.util.settings import Settings# Backend route that starts the Slack "Add to Slack" OAuth install (kept in sync@@ -37,7 +38,7 @@ def enabled_platforms() -> list[PlatformMeta]:Platforms whose adapter isn't configured (missing credentials) areomitted entirely so the Bots page hides them."""- all_platforms = [_discord_meta(), _slack_meta()]+ all_platforms = [_discord_meta(), _slack_meta(), _telegram_meta()]return [platform for platform in all_platforms if platform.enabled]@@ -71,6 +72,27 @@ def _slack_meta() -> PlatformMeta:)+def _telegram_meta() -> PlatformMeta:+ # Enabled on the same gate the webhook adapter mounts on. The t.me+ # startgroup deep link opens Telegram's own "add to group" picker, so the+ # button only renders when the bot's public username is configured.+ enabled = bool(+ telegram_config.get_bot_token() and telegram_config.get_webhook_secret()+ )+ username = telegram_config.get_bot_username().lstrip("@")+ return PlatformMeta(+ platform="TELEGRAM",+ display_name="Telegram",+ icon="telegram.png",+ enabled=enabled,+ add_bot_url=(+ f"https://t.me/{username}?startgroup=true"+ if (enabled and username)+ else None+ ),+ )++def _slack_install_url() -> str | None:base = Settings().config.platform_base_url.rstrip("/")if not base:diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py b/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.pyindex 4f7c56cae6..b815f1701c 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py@@ -26,14 +26,19 @@ def _discord_off():return patch(f"{_REG}.discord_config.get_bot_token", return_value="")+def _telegram_off():+ return patch(f"{_REG}.telegram_config.get_bot_token", return_value="")++def test_no_platforms_when_none_configured():- with _discord_off(), _slack_off():+ with _discord_off(), _slack_off(), _telegram_off():assert enabled_platforms() == []def test_discord_appears_with_invite_url_when_client_id_set():with (_slack_off(),+ _telegram_off(),patch(f"{_REG}.discord_config.get_bot_token", return_value="token"),patch(f"{_REG}.discord_config.get_client_id", return_value="my-client-id"),patch(f"{_REG}.discord_config.get_invite_permissions", return_value="123"),@@ -51,6 +56,7 @@ def test_discord_appears_with_invite_url_when_client_id_set():def test_discord_appears_without_invite_url_when_client_id_missing():with (_slack_off(),+ _telegram_off(),patch(f"{_REG}.discord_config.get_bot_token", return_value="token"),patch(f"{_REG}.discord_config.get_client_id", return_value=""),):@@ -66,6 +72,7 @@ def test_slack_appears_in_single_workspace_mode_without_install_url():oauth_id_off, oauth_secret_off = _slack_oauth_off()with (_discord_off(),+ _telegram_off(),patch(f"{_REG}.slack_config.get_bot_token", return_value="xoxb-x"),patch(f"{_REG}.slack_config.get_signing_secret", return_value="secret"),oauth_id_off,@@ -84,6 +91,7 @@ def test_slack_appears_in_single_workspace_mode_without_install_url():def test_slack_add_to_slack_url_when_oauth_configured():with (_discord_off(),+ _telegram_off(),patch(f"{_REG}.slack_config.get_bot_token", return_value=""),patch(f"{_REG}.slack_config.get_signing_secret", return_value="secret"),patch(f"{_REG}.slack_config.get_client_id", return_value="cid"),@@ -105,6 +113,7 @@ def test_slack_add_to_slack_url_when_oauth_configured():def test_slack_hidden_when_signing_secret_missing():with (_discord_off(),+ _telegram_off(),patch(f"{_REG}.slack_config.get_bot_token", return_value="xoxb-x"),patch(f"{_REG}.slack_config.get_signing_secret", return_value=""),):@@ -114,6 +123,7 @@ def test_slack_hidden_when_signing_secret_missing():def test_both_platforms_when_both_configured():oauth_id_off, oauth_secret_off = _slack_oauth_off()with (+ _telegram_off(),patch(f"{_REG}.discord_config.get_bot_token", return_value="token"),patch(f"{_REG}.discord_config.get_client_id", return_value=""),patch(f"{_REG}.slack_config.get_bot_token", return_value="xoxb-x"),@@ -124,3 +134,44 @@ def test_both_platforms_when_both_configured():platforms = enabled_platforms()assert {p.platform for p in platforms} == {"DISCORD", "SLACK"}+++def test_telegram_appears_with_tme_link_when_username_set():+ with (+ _discord_off(),+ _slack_off(),+ patch(f"{_REG}.telegram_config.get_bot_token", return_value="123:abc"),+ patch(f"{_REG}.telegram_config.get_webhook_secret", return_value="s3cret"),+ patch(f"{_REG}.telegram_config.get_bot_username", return_value="AutoGPTBot"),+ ):+ platforms = enabled_platforms()++ assert [p.platform for p in platforms] == ["TELEGRAM"]+ telegram = platforms[0]+ assert telegram.display_name == "Telegram"+ assert telegram.icon == "telegram.png"+ assert telegram.add_bot_url == "https://t.me/AutoGPTBot?startgroup=true"+++def test_telegram_without_username_has_no_add_bot_url():+ with (+ _discord_off(),+ _slack_off(),+ patch(f"{_REG}.telegram_config.get_bot_token", return_value="123:abc"),+ patch(f"{_REG}.telegram_config.get_webhook_secret", return_value="s3cret"),+ patch(f"{_REG}.telegram_config.get_bot_username", return_value=""),+ ):+ platforms = enabled_platforms()++ assert [p.platform for p in platforms] == ["TELEGRAM"]+ assert platforms[0].add_bot_url is None+++def test_telegram_hidden_without_webhook_secret():+ with (+ _discord_off(),+ _slack_off(),+ patch(f"{_REG}.telegram_config.get_bot_token", return_value="123:abc"),+ patch(f"{_REG}.telegram_config.get_webhook_secret", return_value=""),+ ):+ assert enabled_platforms() == []diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/routes.py b/autogpt_platform/backend/backend/api/features/platform_linking/routes.pyindex a65e70dbf8..b583752e32 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/routes.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/routes.py@@ -5,7 +5,10 @@ from typing import Annotatedfrom autogpt_libs import authfrom fastapi import APIRouter, HTTPException, Path, Security+from pydantic import BaseModel, Field+from backend.copilot.bot.adapters.telegram import config as telegram_config+from backend.copilot.bot.adapters.telegram.login import verify_loginfrom backend.data.db_accessors import platform_linking_dbfrom backend.platform_linking.models import (BotPlatformInfo,@@ -36,6 +39,26 @@ TokenPath = Annotated[]+class ConfirmLinkRequest(BaseModel):+ """Optional confirm payload. ``telegram_auth`` carries the signed identity+ Telegram appends when the user reached this page via a login_url button —+ when present it must verify, and the link token must belong to that same+ Telegram user."""++ telegram_auth: dict[str, str] | None = Field(default=None)+++def _verified_platform_user(body: ConfirmLinkRequest | None) -> str | None:+ if body is None or not body.telegram_auth:+ return None+ verified = verify_login(body.telegram_auth, telegram_config.get_bot_token())+ if verified is None:+ raise HTTPException(+ status_code=403, detail="Telegram login data failed verification."+ )+ return verified++def _translate(exc: Exception) -> HTTPException:if isinstance(exc, NotFoundError):return HTTPException(status_code=404, detail=str(exc))@@ -72,11 +95,15 @@ async def get_link_token_info_route(token: TokenPath) -> LinkTokenInfoResponse:async def confirm_link_token(token: TokenPath,user_id: Annotated[str, Security(auth.get_user_id)],+ body: ConfirmLinkRequest | None = None,) -> ConfirmLinkResponse:try:- return await platform_linking_db().confirm_server_link(token, user_id)+ return await platform_linking_db().confirm_server_link(+ token, user_id, verified_platform_user_id=_verified_platform_user(body)+ )except (NotFoundError,+ NotAuthorizedError,LinkFlowMismatchError,LinkTokenExpiredError,LinkAlreadyExistsError,@@ -93,11 +120,15 @@ async def confirm_link_token(async def confirm_user_link_token(token: TokenPath,user_id: Annotated[str, Security(auth.get_user_id)],+ body: ConfirmLinkRequest | None = None,) -> ConfirmUserLinkResponse:try:- return await platform_linking_db().confirm_user_link(token, user_id)+ return await platform_linking_db().confirm_user_link(+ token, user_id, verified_platform_user_id=_verified_platform_user(body)+ )except (NotFoundError,+ NotAuthorizedError,LinkFlowMismatchError,LinkTokenExpiredError,LinkAlreadyExistsError,diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py b/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.pyindex 34aef91af8..3315beb4e9 100644--- a/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py@@ -411,3 +411,90 @@ class TestListBotPlatforms:result = await list_bot_platforms(user_id="u1")assert result == []+++class TestTelegramLoginVerification:+ @pytest.mark.asyncio+ async def test_invalid_telegram_auth_is_403_before_any_db_call(self):+ from backend.api.features.platform_linking.routes import (+ ConfirmLinkRequest,+ confirm_user_link_token,+ )++ confirm = AsyncMock()+ db = _db_mock(confirm_user_link=confirm)+ with (+ patch(+ "backend.api.features.platform_linking.routes.platform_linking_db",+ return_value=db,+ ),+ patch(+ "backend.api.features.platform_linking.routes.verify_login",+ return_value=None,+ ),+ ):+ with pytest.raises(HTTPException) as exc:+ await confirm_user_link_token(+ "tok",+ "user-1",+ body=ConfirmLinkRequest(telegram_auth={"id": "1", "hash": "x"}),+ )+ assert exc.value.status_code == 403+ confirm.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_verified_identity_is_forwarded_to_confirm(self):+ from backend.api.features.platform_linking.routes import (+ ConfirmLinkRequest,+ confirm_user_link_token,+ )++ confirm = AsyncMock(return_value=MagicMock())+ db = _db_mock(confirm_user_link=confirm)+ with (+ patch(+ "backend.api.features.platform_linking.routes.platform_linking_db",+ return_value=db,+ ),+ patch(+ "backend.api.features.platform_linking.routes.verify_login",+ return_value="424242",+ ),+ ):+ await confirm_user_link_token(+ "tok",+ "user-1",+ body=ConfirmLinkRequest(telegram_auth={"id": "424242", "hash": "x"}),+ )+ confirm.assert_awaited_once_with(+ "tok", "user-1", verified_platform_user_id="424242"+ )++ @pytest.mark.asyncio+ async def test_no_body_confirms_without_verification(self):+ from backend.api.features.platform_linking.routes import confirm_user_link_token++ confirm = AsyncMock(return_value=MagicMock())+ db = _db_mock(confirm_user_link=confirm)+ with patch(+ "backend.api.features.platform_linking.routes.platform_linking_db",+ return_value=db,+ ):+ await confirm_user_link_token("tok", "user-1", body=None)+ confirm.assert_awaited_once_with(+ "tok", "user-1", verified_platform_user_id=None+ )++ @pytest.mark.asyncio+ async def test_identity_mismatch_from_db_maps_to_403(self):+ from backend.api.features.platform_linking.routes import confirm_user_link_token++ confirm = AsyncMock(side_effect=NotAuthorizedError("different user"))+ db = _db_mock(confirm_user_link=confirm)+ with patch(+ "backend.api.features.platform_linking.routes.platform_linking_db",+ return_value=db,+ ):+ with pytest.raises(HTTPException) as exc:+ await confirm_user_link_token("tok", "user-1", body=None)+ assert exc.value.status_code == 403diff --git a/autogpt_platform/backend/backend/copilot/bot/README.md b/autogpt_platform/backend/backend/copilot/bot/README.mdindex ccb144e818..dd4ab1c330 100644--- a/autogpt_platform/backend/backend/copilot/bot/README.md+++ b/autogpt_platform/backend/backend/copilot/bot/README.md@@ -1,6 +1,6 @@# CoPilot Bot-Multi-platform chat bot that bridges AutoPilot to Discord (and later Telegram, Slack, etc).+Multi-platform chat bot that bridges AutoGPT to Discord, Slack, and Telegram (Teams/WhatsApp next).## Running@@ -38,6 +38,7 @@ See `backend/.env.default` for the full list with documentation. Minimum setup:|----------|---------|| `AUTOPILOT_BOT_DISCORD_TOKEN` | Discord bot token — enables the Discord (socket) adapter || `AUTOPILOT_BOT_SLACK_TOKEN` + `AUTOPILOT_BOT_SLACK_SIGNING_SECRET` | Slack bot token + signing secret — set **both** to mount the Slack (webhook / Events API) adapter on the main backend API |+| `AUTOPILOT_BOT_TELEGRAM_TOKEN` + `AUTOPILOT_BOT_TELEGRAM_WEBHOOK_SECRET` | Telegram BotFather token + webhook secret — set **both** to mount the Telegram (webhook / Bot API) adapter, then register the webhook once with `setWebhook` (see `.env.default`). Also disable group privacy mode via BotFather `/setprivacy` or the bot can't see @mentions in groups || `FRONTEND_BASE_URL` | Frontend base URL for link confirmation pages (shared with the rest of the backend) || `REDIS_HOST` / `REDIS_PORT` | Session + thread subscription state + copilot stream subscription (inherited from the shared backend config) || `PLATFORMLINKINGMANAGER_HOST` | DNS name of the `PlatformLinkingManager` service pod (cluster-internal RPC) |@@ -64,13 +65,19 @@ bot/│ ├── adapter.py # Gateway connection, events, sends, thread creation│ ├── commands.py # Slash commands (/setup, /help, /unlink)│ └── config.py # Discord token + platform limits- └── slack/ # WebhookAdapter — Slack Events API- ├── adapter.py # Inbound event/command routes, sends, mrkdwn, attachments- ├── commands.py # Slash commands (/setup, /help, /unlink)- ├── config.py # Slack token + signing secret + platform limits- ├── signing.py # HMAC-SHA256 request signature verification- ├── text.py # CommonMark → Slack mrkdwn- └── app-manifest.yaml # Importable Slack app definition (scopes, events, commands)+ ├── slack/ # WebhookAdapter — Slack Events API+ │ ├── adapter.py # Inbound event/command routes, sends, mrkdwn, attachments+ │ ├── commands.py # Slash commands (/setup, /help, /unlink)+ │ ├── config.py # Slack token + signing secret + platform limits+ │ ├── signing.py # HMAC-SHA256 request signature verification+ │ ├── text.py # CommonMark → Slack mrkdwn+ │ └── app-manifest.yaml # Importable Slack app definition (scopes, events, commands)+ └── telegram/ # WebhookAdapter — Telegram Bot API+ ├── adapter.py # Inbound updates route, sends, chat-model mapping+ ├── api_client.py # Thin httpx Bot API client (JSON + multipart + getFile)+ ├── commands.py # Bot commands (/setup, /help, /unlink)+ ├── config.py # BotFather token + webhook secret + platform limits+ └── text.py # CommonMark → Telegram HTML```**Connector taxonomy.** `PlatformAdapter` is the outbound contract the corediff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/__init__.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.pynew file mode 100644index 0000000000..f29da35761--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py@@ -0,0 +1,507 @@+"""Telegram adapter — webhook-based (Bot API), single bot for all chats.++Mounts one inbound updates route on the main backend API. Telegram signs+nothing — instead the webhook is registered with a secret token that Telegram+echoes back in the ``X-Telegram-Bot-Api-Secret-Token`` header on every POST;+verification is a constant-time compare of that header.++Chat model mapping: a private chat is a DM (auto-converse); a group or+supergroup message engages the bot only when it @mentions the bot or replies+to one of the bot's messages — the bot never subscribes itself to a+human-owned group conversation. Forum-topic placement rides along in the+encoded target (``chat_id|thread_id``) so replies land in the right topic.+"""++import asyncio+import hmac+import html+import json+import logging+import re+from typing import Any, Optional++from fastapi import FastAPI, Request, Response+from fastapi.responses import PlainTextResponse++from backend.copilot.bot.adapters.base import (+ ChannelInfo,+ ChannelType,+ FileAttachment,+ MessageCallback,+ MessageContext,+ PostedRef,+ WebhookAdapter,+ read_verified_webhook_body,+ unauthorized_webhook_response,+)+from backend.copilot.bot.adapters.shared import InboundFile, collect_attachments+from backend.copilot.bot.bot_backend import BotBackend+from backend.copilot.bot.config import MAX_INBOUND_ATTACHMENTS+from backend.copilot.bot.text import iter_chunks, resolve_mentions++from . import commands, config+from .api_client import TelegramClient+from .targets import decode_target as _decode_target+from .targets import encode_target as _encode_target+from .text import to_html++logger = logging.getLogger(__name__)++UPDATES_PATH = "/api/copilot-webhooks/telegram/updates"++# Telegram chat IDs are integers of any length; groups/supergroups are+# negative (supergroups start with -100). Used to tell a raw proactive chat+# ref from a name (names are never purely numeric).+_CHAT_ID_RE = re.compile(r"^-?\d+$")++# Message fields that carry a downloadable file, with a fallback filename for+# the kinds Telegram doesn't name.+_FILE_FIELDS = (+ ("document", None),+ ("video", "video.mp4"),+ ("audio", "audio.mp3"),+ ("voice", "voice.ogg"),+)+++class TelegramAdapter(WebhookAdapter):+ def __init__(self, api: BotBackend):+ self._api = api+ self._client = TelegramClient(config.get_bot_token())+ self._on_message_callback: Optional[MessageCallback] = None+ # getMe identity, resolved once (truthy-only cache).+ self._bot_id: str = ""+ self._bot_username: str = ""+ # Strong-ref set so the GC doesn't drop fire-and-forget update tasks.+ self._update_tasks: set[asyncio.Task[None]] = set()++ @property+ def platform_name(self) -> str:+ return "telegram"++ @property+ def max_message_length(self) -> int:+ return config.MAX_MESSAGE_LENGTH++ @property+ def chunk_flush_at(self) -> int:+ return config.CHUNK_FLUSH_AT++ @property+ def max_attachment_bytes(self) -> int:+ return config.MAX_ATTACHMENT_BYTES++ @property+ def max_thread_name_length(self) -> int:+ return config.MAX_THREAD_NAME_LENGTH++ @property+ def typing_refresh_interval(self) -> float:+ return config.TYPING_REFRESH_SECONDS++ def looks_like_channel_id(self, ref: str) -> bool:+ return bool(_CHAT_ID_RE.match(ref))++ def localize_markup(self, text: str) -> str:+ return to_html(text)++ def on_message(self, callback: MessageCallback) -> None:+ self._on_message_callback = callback++ def register_routes(self, app: FastAPI) -> None:+ app.add_api_route(UPDATES_PATH, self._handle_update_request, methods=["POST"])+ # Publish the command menu on startup so BotFather needs no manual+ # /setcommands step and the menu can't drift from the code.+ app.add_event_handler("startup", self._register_command_menu)++ async def _register_command_menu(self) -> None:+ try:+ await self._client.call("setMyCommands", commands=commands.COMMAND_MENU)+ except Exception:+ logger.warning("Failed to register Telegram command menu", exc_info=True)++ # -- Inbound --++ async def _handle_update_request(self, request: Request) -> Response:+ raw = await read_verified_webhook_body(request, _verify_secret)+ if raw is None:+ return unauthorized_webhook_response()+ update = json.loads(raw)+ # Fire-and-forget so we ACK immediately — Telegram retries slow+ # webhooks, which would double-process the turn.+ task = asyncio.create_task(self._dispatch_update(update))+ self._update_tasks.add(task)+ task.add_done_callback(self._update_tasks.discard)+ return PlainTextResponse("ok")++ async def _dispatch_update(self, update: dict[str, Any]) -> None:+ membership = update.get("my_chat_member")+ if membership:+ self._track_membership_change(membership)+ return+ message = update.get("message")+ if not message:+ return # Edits, reactions, other member updates — not conversation input.+ sender = message.get("from") or {}+ if sender.get("is_bot"):+ return # Skip bot messages (including our own) to avoid loops.+ _bot_id, bot_username = await self._bot_identity()+ command = commands.parse_command(message, bot_username)+ if command is not None:+ # This runs as a fire-and-forget task — an unhandled error would+ # only surface as asyncio's deferred "exception never retrieved".+ try:+ await commands.handle(self._api, self._client, message, command)+ except Exception:+ logger.exception("Telegram command handler failed")+ return+ if self._on_message_callback is None:+ return+ ctx = await self._build_context(message)+ if ctx is None:+ return+ await self._ack_reaction(message)+ try:+ await self._on_message_callback(ctx, self)+ except Exception:+ logger.exception("Telegram update handler failed")++ async def _ack_reaction(self, message: dict[str, Any]) -> None:+ """Best-effort 👀 on the triggering message — instant feedback that+ the bot picked it up, ahead of the (slower) typing indicator."""+ try:+ await self._client.call(+ "setMessageReaction",+ chat_id=str((message.get("chat") or {}).get("id", "")),+ message_id=message.get("message_id"),+ reaction=[{"type": "emoji", "emoji": "👀"}],+ )+ except Exception:+ logger.debug("Telegram reaction ack failed", exc_info=True)++ def _track_membership_change(self, membership: dict[str, Any]) -> None:+ """Keep the admin server roster current: the bot being added to /+ removed from a group arrives as a my_chat_member update."""+ chat = membership.get("chat") or {}+ if chat.get("type") not in ("group", "supergroup"):+ return+ status = (membership.get("new_chat_member") or {}).get("status")+ chat_id = str(chat.get("id", ""))+ if not chat_id or not status:+ return+ if status in ("member", "administrator"):+ self._api.track_guild_joined("telegram", chat_id, chat.get("title"))+ elif status in ("left", "kicked"):+ self._api.track_guild_left("telegram", chat_id)++ async def _build_context(self, message: dict[str, Any]) -> Optional[MessageContext]:+ chat = message.get("chat") or {}+ sender = message.get("from") or {}+ chat_id = str(chat.get("id", ""))+ message_id = message.get("message_id")+ if not chat_id or message_id is None:+ return None+ is_private = chat.get("type") == "private"+ text = message.get("text") or message.get("caption") or ""++ if is_private:+ channel_type: ChannelType = "dm"+ bot_mentioned = True+ else:+ # In groups the bot engages only when addressed: an @mention in+ # the text or a direct reply to one of its messages.+ bot_id, bot_username = await self._bot_identity()+ mentioned = bool(+ bot_username+ and re.search(rf"@{re.escape(bot_username)}\b", text, re.IGNORECASE)+ )+ reply_to = (message.get("reply_to_message") or {}).get("from") or {}+ replied_to_bot = bool(bot_id) and str(reply_to.get("id", "")) == bot_id+ if not mentioned and not replied_to_bot:+ return None+ channel_type = "channel"+ bot_mentioned = True+ if bot_username:+ text = re.sub(+ rf"@{re.escape(bot_username)}\b", "", text, flags=re.IGNORECASE+ ).strip()++ target_id = _encode_target(chat_id, message.get("message_thread_id"))+ attachments, skipped = await self._extract_attachments(message)+ return MessageContext(+ platform="telegram",+ channel_type=channel_type,+ # DMs bill to the user (no server); group chats are the "server".+ server_id=None if is_private else chat_id,+ channel_id=target_id,+ message_id=str(message_id),+ user_id=str(sender.get("id", "")),+ username=sender.get("username") or sender.get("first_name") or "unknown",+ text=text,+ bot_mentioned=bot_mentioned,+ mentionable_users=_collect_mentionable_users(message),+ attachments=attachments,+ skipped_attachments=skipped,+ )++ async def _extract_attachments(+ self, message: dict[str, Any]+ ) -> tuple[tuple, tuple]:+ inbound: list[InboundFile] = []+ for field, fallback_name in _FILE_FIELDS:+ f = message.get(field)+ if not f:+ continue+ size = int(f.get("file_size") or 0)+ if size <= 0:+ # The size cap is enforced against the declared size before+ # fetching — a file without one can't be admitted safely.+ logger.info("Skipping %s attachment without a declared size", field)+ continue+ inbound.append(+ InboundFile(+ filename=f.get("file_name") or fallback_name or field,+ size=size,+ mime_type=f.get("mime_type"),+ fetch=lambda f=f: self._client.download_file(f["file_id"]),+ )+ )+ photos = [+ p for p in message.get("photo") or [] if int(p.get("file_size") or 0) > 0+ ]+ if photos:+ # Telegram sends one photo in several resolutions — take the largest.+ best = max(photos, key=lambda p: int(p["file_size"]))+ inbound.append(+ InboundFile(+ filename="photo.jpg",+ size=int(best["file_size"]),+ mime_type="image/jpeg",+ fetch=lambda b=best: self._client.download_file(b["file_id"]),+ )+ )+ return await collect_attachments(+ inbound,+ max_count=MAX_INBOUND_ATTACHMENTS,+ max_bytes=self.max_attachment_bytes,+ )++ # -- Outbound --++ def _render(self, text: str, mentionable_users: tuple[tuple[str, str], ...]) -> str:+ # Localize (which HTML-escapes) FIRST, then inject mention anchors —+ # the anchors are HTML and must survive escaping. The allowlist IS the+ # ping safety: non-allowlisted names stay plain text.+ rendered, _pinged = resolve_mentions(+ self.localize_markup(text),+ mentionable_users,+ lambda name, uid: f'<a href="tg://user?id={uid}">@{html.escape(name)}</a>',+ )+ return rendered++ async def send_message(+ self,+ channel_id: str,+ text: str,+ mentionable_users: tuple[tuple[str, str], ...] = (),+ ) -> None:+ chat_id, thread_id = _decode_target(channel_id)+ await self._client.call(+ "sendMessage",+ chat_id=chat_id,+ text=self._render(text, mentionable_users),+ parse_mode="HTML",+ message_thread_id=thread_id,+ )++ async def send_reply(+ self,+ channel_id: str,+ text: str,+ reply_to_message_id: str,+ mentionable_users: tuple[tuple[str, str], ...] = (),+ ) -> None:+ chat_id, thread_id = _decode_target(channel_id)+ await self._client.call(+ "sendMessage",+ chat_id=chat_id,+ text=self._render(text, mentionable_users),+ parse_mode="HTML",+ message_thread_id=thread_id,+ reply_parameters={"message_id": int(reply_to_message_id)},+ )++ async def send_link(+ self, channel_id: str, text: str, link_label: str, link_url: str+ ) -> None:+ chat_id, thread_id = _decode_target(channel_id)+ params: dict[str, Any] = {+ "chat_id": chat_id,+ "text": self.localize_markup(text),+ "parse_mode": "HTML",+ "message_thread_id": thread_id,+ }+ # Prefer a login_url button: Telegram attaches a signed identity to+ # the opened URL, so our /link page can verify WHO tapped it (seamless+ # linking). Requires the domain to be registered with @BotFather+ # (/setdomain) and HTTPS — fall back to a plain URL button otherwise+ # so local/dev setups keep working.+ if link_url.startswith("https://"):+ try:+ await self._client.call(+ "sendMessage",+ **params,+ reply_markup={+ "inline_keyboard": [+ [{"text": link_label, "login_url": {"url": link_url}}]+ ]+ },+ )+ return+ except Exception:+ logger.info(+ "login_url button rejected (domain not registered with "+ "BotFather?); falling back to a plain URL button"+ )+ try:+ await self._client.call(+ "sendMessage",+ **params,+ reply_markup={+ "inline_keyboard": [[{"text": link_label, "url": link_url}]]+ },+ )+ except Exception:+ # Telegram validates button URLs and rejects e.g. localhost (local+ # dev). The URL is still fine as plain text — degrade so the flow+ # keeps working everywhere.+ logger.info("URL button rejected; sending the link as plain text")+ # Escaped because parse_mode stays HTML — a bare & in the URL+ # would read as a malformed entity and kill the fallback too.+ params["text"] += html.escape(f"\n\n{link_label}: {link_url}")+ await self._client.call("sendMessage", **params)++ async def send_file(self, channel_id: str, text: str, file: FileAttachment) -> None:+ chat_id, thread_id = _decode_target(channel_id)+ # Images render inline as photos; everything else arrives as a document.+ send = (+ self._client.send_photo+ if (file.mime_type or "").startswith("image/")+ else self._client.send_document+ )+ await send(+ chat_id=chat_id,+ content=file.content,+ filename=file.filename or "file",+ caption=self.localize_markup(text) if text else None,+ message_thread_id=thread_id,+ )++ async def send_ephemeral(self, channel_id: str, user_id: str, text: str) -> None:+ # Telegram has no ephemeral messages — send normally.+ await self.send_message(channel_id, text)++ async def start_typing(self, channel_id: str) -> None:+ chat_id, thread_id = _decode_target(channel_id)+ try:+ await self._client.call(+ "sendChatAction",+ chat_id=chat_id,+ action="typing",+ message_thread_id=thread_id,+ )+ except Exception:+ logger.debug("Telegram sendChatAction failed", exc_info=True)++ async def create_thread(+ self, channel_id: str, message_id: str, name: str+ ) -> Optional[str]:+ # Group conversations stay in the chat (replying into the same forum+ # topic when there is one) — creating/subscribing threads in a+ # human-owned group would risk hijacking it. The handler falls back to+ # in-channel replies, and users continue by replying to the bot.+ return None++ # -- Proactive output --++ async def list_text_channels(+ self, server_ids: tuple[str, ...]+ ) -> list[ChannelInfo]:+ # The Bot API can't enumerate a bot's chats; proactive posts must+ # target a raw chat id.+ return []++ async def get_channel_server_id(self, channel_id: str) -> Optional[str]:+ chat_id, _ = _decode_target(channel_id)+ try:+ chat = await self._client.call("getChat", chat_id=chat_id)+ except Exception:+ return None+ if chat.get("type") in ("group", "supergroup"):+ return str(chat.get("id"))+ return None++ async def post_channel_message(+ self, channel_id: str, text: str+ ) -> Optional[PostedRef]:+ chat_id, thread_id = _decode_target(channel_id)+ first_id: Optional[str] = None+ for chunk in iter_chunks(self.localize_markup(text), config.CHUNK_FLUSH_AT):+ result = await self._client.call(+ "sendMessage",+ chat_id=chat_id,+ text=chunk,+ parse_mode="HTML",+ message_thread_id=thread_id,+ )+ if first_id is None:+ first_id = str(result.get("message_id", ""))+ if first_id is None:+ return None+ return PostedRef(id=first_id, url=None)++ async def create_channel_thread(+ self, channel_id: str, name: str, text: str+ ) -> Optional[PostedRef]:+ # No named threads to create — post with the name as a bold header;+ # the returned ref keeps subsequent sends in the same chat/topic.+ posted = await self.post_channel_message(channel_id, f"**{name}**\n\n{text}")+ if posted is None:+ return None+ return PostedRef(id=channel_id, url=posted.url)++ # -- Helpers --++ async def _bot_identity(self) -> tuple[str, str]:+ """The bot's own (id, username) from getMe, cached truthy-only so a+ transient failure doesn't permanently break mention detection."""+ if self._bot_id and self._bot_username:+ return self._bot_id, self._bot_username+ try:+ me = await self._client.call("getMe")+ except Exception:+ logger.warning("Failed to fetch Telegram identity (getMe)", exc_info=True)+ return self._bot_id, self._bot_username or config.get_bot_username()+ self._bot_id = str(me.get("id", "")) or self._bot_id+ self._bot_username = me.get("username", "") or self._bot_username+ return self._bot_id, self._bot_username+++def _verify_secret(request: Request, _body: bytes) -> bool:+ expected = config.get_webhook_secret()+ provided = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")+ return bool(expected) and hmac.compare_digest(provided, expected)+++def _collect_mentionable_users(message: dict[str, Any]) -> tuple[tuple[str, str], ...]:+ # text_mention entities carry full user objects (users without a public+ # @username); those are the only inbound mentions with a numeric id we+ # can ping safely on the way back out.+ pairs: list[tuple[str, str]] = []+ for entity in message.get("entities") or []:+ user = entity.get("user")+ if entity.get("type") == "text_mention" and user and not user.get("is_bot"):+ pair = (user.get("first_name") or "user", str(user.get("id")))+ if pair not in pairs:+ pairs.append(pair)+ return tuple(pairs)diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.pynew file mode 100644index 0000000000..66c04021e7--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py@@ -0,0 +1,354 @@+"""Tests for the Telegram adapter."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.bot.adapters.base import FileAttachment++from .adapter import (+ TelegramAdapter,+ _collect_mentionable_users,+ _decode_target,+ _encode_target,+ _verify_secret,+)++_ADAPTER = "backend.copilot.bot.adapters.telegram.adapter"+++def _adapter() -> TelegramAdapter:+ with patch(f"{_ADAPTER}.config.get_bot_token", return_value="123:abc"):+ a = TelegramAdapter(MagicMock())+ a._bot_id = "999"+ a._bot_username = "OurBot"+ a._client = MagicMock()+ a._client.call = AsyncMock(return_value={"message_id": 77})+ return a+++def _dm(text: str, **extra) -> dict:+ return {+ "message": {+ "message_id": 10,+ "text": text,+ "chat": {"id": 42, "type": "private"},+ "from": {"id": 42, "username": "bently"},+ **extra,+ }+ }+++def _group(text: str, **extra) -> dict:+ return {+ "message": {+ "message_id": 11,+ "text": text,+ "chat": {"id": -100555, "type": "supergroup", "title": "Builders"},+ "from": {"id": 42, "username": "bently"},+ **extra,+ }+ }+++class TestVerifySecret:+ def test_matching_header_passes(self):+ request = MagicMock()+ request.headers = {"X-Telegram-Bot-Api-Secret-Token": "s3cret"}+ with patch(f"{_ADAPTER}.config.get_webhook_secret", return_value="s3cret"):+ assert _verify_secret(request, b"") is True++ def test_wrong_or_missing_header_fails(self):+ request = MagicMock()+ request.headers = {"X-Telegram-Bot-Api-Secret-Token": "nope"}+ with patch(f"{_ADAPTER}.config.get_webhook_secret", return_value="s3cret"):+ assert _verify_secret(request, b"") is False+ request.headers = {}+ with patch(f"{_ADAPTER}.config.get_webhook_secret", return_value="s3cret"):+ assert _verify_secret(request, b"") is False++ def test_unconfigured_secret_rejects_everything(self):+ request = MagicMock()+ request.headers = {"X-Telegram-Bot-Api-Secret-Token": ""}+ with patch(f"{_ADAPTER}.config.get_webhook_secret", return_value=""):+ assert _verify_secret(request, b"") is False+++class TestDispatch:+ @pytest.mark.asyncio+ async def test_dm_dispatches_as_dm_context(self):+ a = _adapter()+ seen = []+ a.on_message(lambda ctx, adapter: seen.append(ctx) or _noop())+ await a._dispatch_update(_dm("hello there"))+ assert len(seen) == 1+ ctx = seen[0]+ assert ctx.channel_type == "dm"+ assert ctx.server_id is None+ assert ctx.channel_id == "42"+ assert ctx.text == "hello there"++ @pytest.mark.asyncio+ async def test_group_message_without_mention_is_ignored(self):+ a = _adapter()+ seen = []+ a.on_message(lambda ctx, adapter: seen.append(ctx) or _noop())+ await a._dispatch_update(_group("just chatting"))+ assert seen == []++ @pytest.mark.asyncio+ async def test_group_mention_dispatches_and_strips_the_mention(self):+ a = _adapter()+ seen = []+ a.on_message(lambda ctx, adapter: seen.append(ctx) or _noop())+ await a._dispatch_update(_group("@OurBot summarise this"))+ assert len(seen) == 1+ ctx = seen[0]+ assert ctx.channel_type == "channel"+ assert ctx.server_id == "-100555"+ assert ctx.text == "summarise this"+ assert ctx.bot_mentioned is True++ @pytest.mark.asyncio+ async def test_reply_to_bot_message_counts_as_engagement(self):+ a = _adapter()+ seen = []+ a.on_message(lambda ctx, adapter: seen.append(ctx) or _noop())+ await a._dispatch_update(+ _group("and now?", reply_to_message={"from": {"id": 999, "is_bot": True}})+ )+ assert len(seen) == 1++ @pytest.mark.asyncio+ async def test_bot_messages_are_skipped(self):+ a = _adapter()+ seen = []+ a.on_message(lambda ctx, adapter: seen.append(ctx) or _noop())+ update = _dm("@OurBot hi")+ update["message"]["from"]["is_bot"] = True+ await a._dispatch_update(update)+ assert seen == []++ @pytest.mark.asyncio+ async def test_forum_topic_id_rides_in_the_target(self):+ a = _adapter()+ seen = []+ a.on_message(lambda ctx, adapter: seen.append(ctx) or _noop())+ await a._dispatch_update(_group("@OurBot hi", message_thread_id=7))+ assert seen[0].channel_id == "-100555|7"++ @pytest.mark.asyncio+ async def test_command_routes_to_command_handler_not_chat(self):+ a = _adapter()+ seen = []+ a.on_message(lambda ctx, adapter: seen.append(ctx) or _noop())+ update = _group("/setup")+ update["message"]["entities"] = [+ {"type": "bot_command", "offset": 0, "length": 6}+ ]+ with patch(f"{_ADAPTER}.commands.handle", new=AsyncMock()) as handle:+ await a._dispatch_update(update)+ handle.assert_awaited_once()+ assert seen == []++ @pytest.mark.asyncio+ async def test_command_handler_error_is_contained(self):+ # _dispatch_update runs as a fire-and-forget task — a raising command+ # handler must be caught and logged, not left to asyncio's deferred+ # "exception never retrieved".+ a = _adapter()+ update = _group("/setup")+ update["message"]["entities"] = [+ {"type": "bot_command", "offset": 0, "length": 6}+ ]+ with patch(+ f"{_ADAPTER}.commands.handle",+ new=AsyncMock(side_effect=RuntimeError("boom")),+ ):+ await a._dispatch_update(update)+++class TestFeatures:+ @pytest.mark.asyncio+ async def test_engaging_message_gets_a_reaction_ack(self):+ a = _adapter()+ a.on_message(lambda ctx, adapter: _noop())+ await a._dispatch_update(_dm("hello"))+ methods = [c.args[0] for c in a._client.call.call_args_list]+ assert "setMessageReaction" in methods++ @pytest.mark.asyncio+ async def test_ignored_group_message_gets_no_reaction(self):+ a = _adapter()+ a.on_message(lambda ctx, adapter: _noop())+ await a._dispatch_update(_group("no mention here"))+ assert a._client.call.call_args_list == []++ @pytest.mark.asyncio+ async def test_command_menu_registered_on_startup(self):+ a = _adapter()+ await a._register_command_menu()+ assert a._client.call.call_args.args == ("setMyCommands",)+ menu = a._client.call.call_args.kwargs["commands"]+ assert {c["command"] for c in menu} >= {"setup", "new", "help", "unlink"}++ @pytest.mark.asyncio+ async def test_image_files_send_as_photos_documents_otherwise(self):+ a = _adapter()+ a._client.send_photo = AsyncMock()+ a._client.send_document = AsyncMock()+ await a.send_file(+ "42",+ "",+ FileAttachment(filename="x.png", mime_type="image/png", content=b"i"),+ )+ a._client.send_photo.assert_awaited_once()+ await a.send_file(+ "42",+ "",+ FileAttachment(filename="x.pdf", mime_type="application/pdf", content=b"d"),+ )+ a._client.send_document.assert_awaited_once()+++class TestAnalytics:+ @pytest.mark.asyncio+ async def test_group_join_records_guild(self):+ a = _adapter()+ await a._dispatch_update(+ {+ "my_chat_member": {+ "chat": {"id": -100777, "type": "supergroup", "title": "Builders"},+ "new_chat_member": {"status": "member"},+ }+ }+ )+ a._api.track_guild_joined.assert_called_once_with(+ "telegram", "-100777", "Builders"+ )++ @pytest.mark.asyncio+ async def test_group_kick_records_guild_left(self):+ a = _adapter()+ await a._dispatch_update(+ {+ "my_chat_member": {+ "chat": {"id": -100777, "type": "supergroup"},+ "new_chat_member": {"status": "kicked"},+ }+ }+ )+ a._api.track_guild_left.assert_called_once_with("telegram", "-100777")++ @pytest.mark.asyncio+ async def test_private_membership_changes_are_ignored(self):+ a = _adapter()+ await a._dispatch_update(+ {+ "my_chat_member": {+ "chat": {"id": 42, "type": "private"},+ "new_chat_member": {"status": "member"},+ }+ }+ )+ a._api.track_guild_joined.assert_not_called()+++class TestOutbound:+ @pytest.mark.asyncio+ async def test_send_message_renders_html_and_threads(self):+ a = _adapter()+ await a.send_message("-100555|7", "**bold** & plain")+ kwargs = a._client.call.call_args.kwargs+ assert a._client.call.call_args.args == ("sendMessage",)+ assert kwargs["chat_id"] == "-100555"+ assert kwargs["message_thread_id"] == 7+ assert kwargs["parse_mode"] == "HTML"+ assert kwargs["text"] == "<b>bold</b> & plain"++ @pytest.mark.asyncio+ async def test_send_link_prefers_login_url_for_https(self):+ # Telegram attaches a signed identity when the user taps a login_url+ # button — the /link page verifies it for seamless linking.+ a = _adapter()+ await a.send_link("42", "Link it", "Open AutoGPT", "https://x/l")+ button = a._client.call.call_args.kwargs["reply_markup"]["inline_keyboard"][0][+ 0+ ]+ assert button == {"text": "Open AutoGPT", "login_url": {"url": "https://x/l"}}++ @pytest.mark.asyncio+ async def test_send_link_falls_back_to_plain_url_when_login_rejected(self):+ # Unregistered domain (no BotFather /setdomain) → login_url send fails;+ # the link must still arrive as a plain URL button.+ a = _adapter()+ a._client.call = AsyncMock(+ side_effect=[RuntimeError("BUTTON_TYPE_INVALID"), {}]+ )+ await a.send_link("42", "Link it", "Open AutoGPT", "https://x/l")+ retry = a._client.call.call_args.kwargs["reply_markup"]["inline_keyboard"][0][0]+ assert retry == {"text": "Open AutoGPT", "url": "https://x/l"}++ @pytest.mark.asyncio+ async def test_send_link_degrades_to_text_when_button_rejected(self):+ # Telegram refuses localhost button URLs (local dev) — the link must+ # still arrive, appended as plain text.+ a = _adapter()+ a._client.call = AsyncMock(side_effect=[RuntimeError("Wrong HTTP URL"), {}])+ await a.send_link("42", "Link it", "Open", "http://localhost:3000/l?a=1&b=2")+ final = a._client.call.call_args.kwargs+ assert "reply_markup" not in final+ # parse_mode stays HTML, so the appended link must be entity-escaped.+ assert "Open: http://localhost:3000/l?a=1&b=2" in final["text"]++ @pytest.mark.asyncio+ async def test_send_link_plain_url_for_non_https(self):+ a = _adapter()+ await a.send_link("42", "Link it", "Open", "http://localhost:3000/l")+ button = a._client.call.call_args.kwargs["reply_markup"]["inline_keyboard"][0][+ 0+ ]+ assert button == {"text": "Open", "url": "http://localhost:3000/l"}++ @pytest.mark.asyncio+ async def test_create_thread_declines_so_replies_stay_in_chat(self):+ a = _adapter()+ assert await a.create_thread("-100555", "11", "AutoGPT: hi") is None+++def test_short_chat_ids_count_as_channel_refs():+ a = _adapter()+ assert a.looks_like_channel_id("12345") is True+ assert a.looks_like_channel_id("-100987654321") is True+ assert a.looks_like_channel_id("general") is False+++async def test_attachments_without_declared_size_are_skipped():+ # The size cap is checked against the declared size pre-fetch; an+ # undeclared size can't be admitted.+ a = _adapter()+ attachments, _skipped = await a._extract_attachments(+ {"document": {"file_id": "f1", "file_name": "x.pdf"}}+ )+ assert attachments == ()+++def test_target_codec_roundtrip():+ assert _decode_target(_encode_target("42")) == ("42", None)+ assert _decode_target(_encode_target("-100555", 7)) == ("-100555", 7)+++def test_collect_mentionable_users_only_text_mentions_with_ids():+ message = {+ "entities": [+ {"type": "mention"}, # @username form — no numeric id, unusable+ {"type": "text_mention", "user": {"id": 5, "first_name": "Sam"}},+ {"type": "text_mention", "user": {"id": 9, "is_bot": True}},+ ]+ }+ assert _collect_mentionable_users(message) == (("Sam", "5"),)+++async def _noop() -> None:+ return Nonediff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/api_client.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/api_client.pynew file mode 100644index 0000000000..6c34825cfe--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/api_client.py@@ -0,0 +1,114 @@+"""Thin async client for the Telegram Bot API.++Plain HTTPS JSON calls via httpx — the Bot API surface we need is small+enough that a dedicated SDK dependency isn't warranted.+"""++import logging+from typing import Any, Optional++import httpx++logger = logging.getLogger(__name__)++_API_BASE = "https://api.telegram.org"+_REQUEST_TIMEOUT_SECONDS = 30.0+++class TelegramAPIError(Exception):+ """A Bot API call returned ok=false."""+++class TelegramClient:+ def __init__(self, token: str):+ self._token = token+ # One pooled client for the adapter's lifetime (mirrors how Slack's+ # AsyncWebClient holds its session) — avoids a TCP+TLS handshake per+ # Bot API call.+ self._http = httpx.AsyncClient(timeout=_REQUEST_TIMEOUT_SECONDS)++ async def call(self, method: str, **params: Any) -> Any:+ """POST a Bot API method; return its ``result`` or raise."""+ url = f"{_API_BASE}/bot{self._token}/{method}"+ resp = await self._http.post(url, json=_drop_none(params))+ payload = resp.json()+ if not payload.get("ok"):+ raise TelegramAPIError(+ f"{method} failed: {payload.get('description', 'unknown error')}"+ )+ return payload.get("result")++ async def send_document(+ self,+ chat_id: str,+ content: bytes,+ filename: str,+ caption: Optional[str] = None,+ message_thread_id: Optional[int] = None,+ ) -> Any:+ return await self._send_multipart(+ "sendDocument",+ "document",+ chat_id,+ content,+ filename,+ caption=caption,+ message_thread_id=message_thread_id,+ )++ async def send_photo(+ self,+ chat_id: str,+ content: bytes,+ filename: str,+ caption: Optional[str] = None,+ message_thread_id: Optional[int] = None,+ ) -> Any:+ return await self._send_multipart(+ "sendPhoto",+ "photo",+ chat_id,+ content,+ filename,+ caption=caption,+ message_thread_id=message_thread_id,+ )++ async def _send_multipart(+ self,+ method: str,+ field: str,+ chat_id: str,+ content: bytes,+ filename: str,+ caption: Optional[str] = None,+ message_thread_id: Optional[int] = None,+ ) -> Any:+ """File-carrying methods need multipart, unlike the JSON methods."""+ url = f"{_API_BASE}/bot{self._token}/{method}"+ data: dict[str, Any] = {"chat_id": chat_id}+ if caption:+ data["caption"] = caption+ data["parse_mode"] = "HTML"+ if message_thread_id is not None:+ data["message_thread_id"] = str(message_thread_id)+ resp = await self._http.post(url, data=data, files={field: (filename, content)})+ payload = resp.json()+ if not payload.get("ok"):+ raise TelegramAPIError(+ f"{method} failed: {payload.get('description', 'unknown error')}"+ )+ return payload.get("result")++ async def download_file(self, file_id: str) -> bytes:+ """Resolve a file_id via getFile and download its content."""+ info = await self.call("getFile", file_id=file_id)+ file_path = info.get("file_path") or ""+ url = f"{_API_BASE}/file/bot{self._token}/{file_path}"+ resp = await self._http.get(url)+ resp.raise_for_status()+ return resp.content+++def _drop_none(params: dict[str, Any]) -> dict[str, Any]:+ return {k: v for k, v in params.items() if v is not None}diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands.pynew file mode 100644index 0000000000..dc0eaed13a--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands.py@@ -0,0 +1,170 @@+"""Telegram bot-command handlers — /setup, /help, /unlink.++Policy comes from the shared ``command_core``; this module owns only+Telegram's transport: commands arrive as ordinary messages with a+``bot_command`` entity, and replies render as HTML messages with an inline+URL button.+"""++import html+import logging+from typing import Any, Optional++from backend.copilot.bot import sessions+from backend.copilot.bot.bot_backend import BotBackend+from backend.copilot.bot.command_core import CommandReply, setup_reply, unlink_reply++from .api_client import TelegramClient+from .targets import encode_target+from .text import to_html++logger = logging.getLogger(__name__)++# Published to Telegram's command menu via setMyCommands on startup.+COMMAND_MENU = [+ {"command": "setup", "description": "Link this group to an AutoGPT account"},+ {"command": "new", "description": "Start a fresh AutoGPT conversation"},+ {"command": "help", "description": "Show AutoGPT bot usage info"},+ {"command": "unlink", "description": "Manage linked chats from your settings"},+]++_HELP_TEXT = (+ "**AutoGPT for Telegram**\n"+ "• Add me to a group and run /setup to link it to an AutoGPT account.\n"+ "• Mention me (or reply to my messages) in a group to chat.\n"+ "• Message me directly to chat with your personal AutoGPT account.\n"+ "• Run /new to start a fresh conversation.\n"+ "• Run /unlink to manage your linked groups and DM."+)+++def parse_command(message: dict[str, Any], bot_username: str) -> Optional[str]:+ """Return the command name ("setup") when ``message`` is a bot command+ addressed to us (bare ``/setup`` or the disambiguated ``/setup@OurBot``+ form Telegram uses in groups), else None."""+ text = message.get("text") or ""+ entities = message.get("entities") or []+ is_command = any(+ e.get("type") == "bot_command" and e.get("offset") == 0 for e in entities+ )+ if not is_command or not text.startswith("/"):+ return None+ command = text.split()[0][1:]+ if "@" in command:+ command, _, target = command.partition("@")+ if bot_username and target.casefold() != bot_username.casefold():+ return None+ return command.casefold()+++async def handle(+ api: BotBackend, client: TelegramClient, message: dict[str, Any], command: str+) -> None:+ chat = message.get("chat") or {}+ sender = message.get("from") or {}+ chat_id = str(chat.get("id", ""))+ is_private = chat.get("type") == "private"+ api.track_event(+ platform="telegram",+ event_type="command_used",+ server_id=None if is_private else chat_id,+ command_name=command,+ )++ if command == "help":+ await _send(client, chat_id, CommandReply(text=_HELP_TEXT), message)+ return+ if command == "unlink":+ await _send(client, chat_id, unlink_reply(), message)+ return+ if command == "new":+ target = encode_target(chat_id, message.get("message_thread_id"))+ try:+ await sessions.clear_session("telegram", target)+ except Exception:+ logger.exception("Failed to clear telegram session for /new")+ await _send(+ client,+ chat_id,+ CommandReply(+ text=(+ "Couldn't reset the conversation right now. Please try "+ "again in a moment."+ )+ ),+ message,+ )+ return+ await _send(+ client,+ chat_id,+ CommandReply(+ text="Started a fresh conversation — send a message to begin."+ ),+ message,+ )+ return+ if command in ("setup", "start"):+ if is_private:+ await _send(+ client,+ chat_id,+ CommandReply(+ text=(+ "/setup links a group. To link your own DMs, just send "+ "me a message and I'll walk you through it."+ )+ ),+ message,+ )+ return+ reply = await setup_reply(+ api,+ platform="telegram",+ server_noun="group",+ platform_server_id=chat_id,+ platform_user_id=str(sender.get("id", "")),+ platform_username=sender.get("username")+ or sender.get("first_name")+ or "unknown",+ server_name=chat.get("title") or "",+ channel_id=chat_id,+ )+ await _send(client, chat_id, reply, message)+ return+ logger.debug("Ignoring unknown Telegram command /%s", command)+++async def _send(+ client: TelegramClient,+ chat_id: str,+ reply: CommandReply,+ message: dict[str, Any],+) -> None:+ text = to_html(reply.text)+ params: dict[str, Any] = {+ "chat_id": chat_id,+ "text": text,+ "parse_mode": "HTML",+ "message_thread_id": message.get("message_thread_id"),+ }+ if reply.button_label and reply.button_url:+ params["reply_markup"] = {+ "inline_keyboard": [[{"text": reply.button_label, "url": reply.button_url}]]+ }+ try:+ await client.call("sendMessage", **params)+ except Exception:+ if "reply_markup" not in params:+ logger.exception("Failed to send Telegram command reply")+ return+ # Telegram rejects some button URLs (e.g. localhost in local dev);+ # degrade to the URL as plain text so the command still answers.+ params.pop("reply_markup")+ # Escaped because parse_mode stays HTML — a bare & in the URL would+ # read as a malformed entity and kill the fallback too.+ params["text"] += html.escape(f"\n\n{reply.button_label}: {reply.button_url}")+ try:+ await client.call("sendMessage", **params)+ except Exception:+ logger.exception("Failed to send Telegram command reply")diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands_test.pynew file mode 100644index 0000000000..a3bbd3cbed--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands_test.py@@ -0,0 +1,116 @@+"""Tests for Telegram bot-command parsing + handling."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.bot.command_core import CommandReply++from . import commands++_CMD = "backend.copilot.bot.adapters.telegram.commands"+++def _message(text: str, chat_type: str = "supergroup") -> dict:+ return {+ "message_id": 5,+ "text": text,+ "entities": [+ {"type": "bot_command", "offset": 0, "length": len(text.split()[0])}+ ],+ "chat": {"id": -100123456, "type": chat_type, "title": "Builders"},+ "from": {"id": 42, "username": "bently"},+ }+++def test_parse_command_bare_and_addressed_forms():+ assert commands.parse_command(_message("/setup"), "OurBot") == "setup"+ assert commands.parse_command(_message("/setup@OurBot"), "OurBot") == "setup"+ assert commands.parse_command(_message("/SETUP@ourbot"), "OurBot") == "setup"+++def test_parse_command_ignores_other_bots_and_non_commands():+ assert commands.parse_command(_message("/setup@OtherBot"), "OurBot") is None+ plain = _message("hello /setup")+ plain["entities"] = []+ assert commands.parse_command(plain, "OurBot") is None+++async def test_setup_in_group_mints_link_and_sends_button():+ client = MagicMock()+ client.call = AsyncMock()+ reply = CommandReply(+ text="**Set up AutoGPT for Builders**",+ button_label="Link Group",+ button_url="https://x/l",+ )+ with patch(f"{_CMD}.setup_reply", new=AsyncMock(return_value=reply)) as sr:+ await commands.handle(MagicMock(), client, _message("/setup"), "setup")+ kwargs = sr.call_args.kwargs+ assert kwargs["platform"] == "telegram"+ assert kwargs["server_noun"] == "group"+ assert kwargs["platform_server_id"] == "-100123456"+ assert kwargs["server_name"] == "Builders"+ sent = client.call.call_args.kwargs+ assert sent["reply_markup"]["inline_keyboard"][0][0]["url"] == "https://x/l"+ assert "<b>Set up AutoGPT for Builders</b>" in sent["text"]+++async def test_setup_in_private_chat_redirects_to_dm_linking():+ client = MagicMock()+ client.call = AsyncMock()+ with patch(f"{_CMD}.setup_reply", new=AsyncMock()) as sr:+ await commands.handle(+ MagicMock(), client, _message("/setup", chat_type="private"), "setup"+ )+ sr.assert_not_called()+ assert "send me a message" in client.call.call_args.kwargs["text"]+++async def test_help_sends_usage_text():+ client = MagicMock()+ client.call = AsyncMock()+ await commands.handle(MagicMock(), client, _message("/help"), "help")+ text = client.call.call_args.kwargs["text"]+ # Rendered as real HTML — an escaped-entity regression would show the+ # user literal <b> junk.+ assert "<b>AutoGPT for Telegram</b>" in text+ assert "<" not in text+++async def test_new_clears_the_target_session():+ client = MagicMock()+ client.call = AsyncMock()+ msg = _message("/new")+ msg["message_thread_id"] = 7+ with patch(f"{_CMD}.sessions.clear_session", new=AsyncMock()) as clear:+ await commands.handle(MagicMock(), client, msg, "new")+ clear.assert_awaited_once_with("telegram", "-100123456|7")+ assert "fresh conversation" in client.call.call_args.kwargs["text"]+++async def test_commands_track_command_used_with_group_scope():+ client = MagicMock()+ client.call = AsyncMock()+ api = MagicMock()+ await commands.handle(api, client, _message("/help"), "help")+ api.track_event.assert_called_once_with(+ platform="telegram",+ event_type="command_used",+ server_id="-100123456",+ command_name="help",+ )+++async def test_dm_commands_track_without_server_id():+ client = MagicMock()+ client.call = AsyncMock()+ api = MagicMock()+ await commands.handle(api, client, _message("/help", chat_type="private"), "help")+ assert api.track_event.call_args.kwargs["server_id"] is Nonediff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/config.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/config.pynew file mode 100644index 0000000000..263f8b89aa--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/config.py@@ -0,0 +1,52 @@+"""Telegram-specific configuration.++One bot (from @BotFather) serves every chat — Telegram has no per-workspace+install, so a single token + webhook secret is the whole credential story.++Bot setup checklist (once per bot, via @BotFather):+- ``/setprivacy`` -> Disable — group privacy mode ON (the default) means the+ bot never receives plain group messages, so @mentions and reply-to-bot go+ unseen. After changing it, remove + re-add the bot to existing groups.+- The command menu registers itself on startup (setMyCommands).++The webhook itself is registered once, out of band, with the secret Telegram+will echo back in the ``X-Telegram-Bot-Api-Secret-Token`` header:++ curl "https://api.telegram.org/bot<TOKEN>/setWebhook" \+ -d "url=<PLATFORM_BASE_URL>/api/copilot-webhooks/telegram/updates" \+ -d "secret_token=<WEBHOOK_SECRET>" -d "allowed_updates=[\"message\",\"my_chat_member\"]"+"""++from backend.util.settings import Settings+++def get_bot_token() -> str:+ return Settings().secrets.autopilot_bot_telegram_token+++def get_webhook_secret() -> str:+ return Settings().secrets.autopilot_bot_telegram_webhook_secret+++def get_bot_username() -> str:+ """The bot's public @username (without the @) — used for the t.me+ add-to-group link; mention detection resolves the authoritative username+ from getMe at runtime."""+ return Settings().secrets.autopilot_bot_telegram_username+++# Telegram's hard cap is 4096 chars per message.+MAX_MESSAGE_LENGTH = 4096++# Flush at 3800 — leaves headroom under the cap for the boundary splitter to+# reach a natural break point.+CHUNK_FLUSH_AT = 3800++# Bots can only download files up to 20MB via getFile.+MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024++# Forum topic names cap at 128 chars; also a sane cap for our title strings.+MAX_THREAD_NAME_LENGTH = 128++# sendChatAction's "typing" indicator lasts ~5s — refresh just under that.+TYPING_REFRESH_SECONDS = 4.0diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/login.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/login.pynew file mode 100644index 0000000000..3101106a09--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/login.py@@ -0,0 +1,44 @@+"""Verification of Telegram login payloads (login_url buttons / Login Widget).++When a user taps a ``login_url`` button in the bot chat, Telegram appends a+signed identity (id, name, username, auth_date, hash) to the opened URL. The+hash is HMAC-SHA256 over the sorted key=value lines, keyed with+SHA256(bot_token) — verifying it proves Telegram itself vouched for the+user. Docs: https://core.telegram.org/widgets/login#checking-authorization+"""++import hashlib+import hmac+import time+from typing import Mapping, Optional++# Telegram-signed payloads expire — a day matches Telegram's own guidance.+MAX_AUTH_AGE_SECONDS = 24 * 60 * 60++# Every key Telegram may include in the signed payload; anything else in the+# query string (e.g. our own params) must not enter the data-check string.+_SIGNED_KEYS = ("auth_date", "first_name", "id", "last_name", "photo_url", "username")+++def verify_login(params: Mapping[str, str], bot_token: str) -> Optional[str]:+ """Return the verified Telegram user id, or None if the payload doesn't+ check out (bad hash, stale auth_date, missing fields)."""+ received_hash = params.get("hash", "")+ auth_date = params.get("auth_date", "")+ user_id = params.get("id", "")+ if not received_hash or not auth_date.isdigit() or not user_id or not bot_token:+ return None+ if time.time() - int(auth_date) > MAX_AUTH_AGE_SECONDS:+ return None+ # Telegram signs the key=value lines in alphabetical order — sort here so+ # verification can't silently break if _SIGNED_KEYS is ever reordered.+ data_check_string = "\n".join(+ f"{key}={params[key]}" for key in sorted(_SIGNED_KEYS) if key in params+ )+ secret_key = hashlib.sha256(bot_token.encode()).digest()+ expected = hmac.new(+ secret_key, data_check_string.encode(), hashlib.sha256+ ).hexdigest()+ if not hmac.compare_digest(expected, received_hash):+ return None+ return user_iddiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/login_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/login_test.pynew file mode 100644index 0000000000..14553639ec--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/login_test.py@@ -0,0 +1,68 @@+"""Tests for Telegram login payload verification."""++import hashlib+import hmac+import time+from unittest.mock import patch++from .login import verify_login++_TOKEN = "123:test-bot-token"+++def _signed(params: dict[str, str], token: str = _TOKEN) -> dict[str, str]:+ check = "\n".join(f"{k}={v}" for k, v in sorted(params.items()))+ secret = hashlib.sha256(token.encode()).digest()+ params["hash"] = hmac.new(secret, check.encode(), hashlib.sha256).hexdigest()+ return params+++def _fresh_payload(**overrides) -> dict[str, str]:+ params = {+ "id": "424242",+ "first_name": "Bently",+ "username": "bently",+ "auth_date": str(int(time.time())),+ }+ params.update(overrides)+ return _signed(params)+++def test_valid_payload_returns_the_telegram_user_id():+ assert verify_login(_fresh_payload(), _TOKEN) == "424242"+++def test_tampered_payload_is_rejected():+ payload = _fresh_payload()+ payload["id"] = "999999" # swap identity after signing+ assert verify_login(payload, _TOKEN) is None+++def test_wrong_bot_token_is_rejected():+ assert verify_login(_fresh_payload(), "456:other-token") is None+++def test_stale_auth_date_is_rejected():+ old = str(int(time.time()) - 2 * 24 * 60 * 60)+ assert verify_login(_fresh_payload(auth_date=old), _TOKEN) is None+++def test_extra_unsigned_params_do_not_break_verification():+ payload = _fresh_payload()+ payload["utm_source"] = "telegram" # our own query params ride along+ assert verify_login(payload, _TOKEN) == "424242"+++def test_missing_hash_or_token_rejected():+ payload = _fresh_payload()+ payload.pop("hash")+ assert verify_login(payload, _TOKEN) is None+ assert verify_login(_fresh_payload(), "") is None+++def test_verification_survives_signed_keys_reordering():+ # Telegram signs key=value lines alphabetically; verification must sort+ # rather than depend on _SIGNED_KEYS happening to be declared in order.+ scrambled = ("username", "id", "photo_url", "last_name", "first_name", "auth_date")+ with patch("backend.copilot.bot.adapters.telegram.login._SIGNED_KEYS", scrambled):+ assert verify_login(_fresh_payload(), _TOKEN) == "424242"diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/targets.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/targets.pynew file mode 100644index 0000000000..d8e6f8986a--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/targets.py@@ -0,0 +1,19 @@+"""Encoding of the opaque target id the handler passes back to sends.++A target is a chat, optionally pinned to a forum topic: ``chat_id`` or+``chat_id|thread_id``. Shared by the adapter (context building, sends) and+the command handlers (session-scoped commands like /new).+"""++from typing import Optional+++def encode_target(chat_id: str, thread_id: Optional[int] = None) -> str:+ return f"{chat_id}|{thread_id}" if thread_id is not None else chat_id+++def decode_target(target_id: str) -> tuple[str, Optional[int]]:+ chat_id, sep, thread = target_id.partition("|")+ if sep and thread.isdigit():+ return chat_id, int(thread)+ return chat_id, Nonediff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/text.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/text.pynew file mode 100644index 0000000000..31e621b8a0--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/text.py@@ -0,0 +1,44 @@+"""Convert the bot's canonical CommonMark output into Telegram HTML.++Telegram's HTML parse mode is the robust dialect — MarkdownV2 requires+escaping half of ASCII. HTML-escape everything first, then re-introduce the+handful of tags Telegram supports for the CommonMark constructs we emit.+Code spans are stashed behind placeholders while bold/link run so markdown+inside code (``**kwargs``, URLs in comments) is never rewritten.+"""++import html+import re++_CODE_BLOCK_RE = re.compile(r"```(?:\w+\n)?(.*?)```", re.DOTALL)+_INLINE_CODE_RE = re.compile(r"`([^`\n]+)`")+_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")+_LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")++# Placeholder frame for stashed code spans. NUL can't survive html.escape'd+# model/user output because we strip it from the input first.+_STASH = "\x00{}\x00"+++def to_html(text: str) -> str:+ """Render CommonMark code blocks, inline code, bold, and links as+ Telegram HTML. Everything else is escaped so user/model output can't+ inject tags."""+ escaped = html.escape(text.replace("\x00", ""), quote=True)+ stashed: list[str] = []++ def _stash(rendered: str) -> str:+ stashed.append(rendered)+ return _STASH.format(len(stashed) - 1)++ escaped = _CODE_BLOCK_RE.sub(+ lambda m: _stash(f"<pre>{m.group(1).strip()}</pre>"), escaped+ )+ escaped = _INLINE_CODE_RE.sub(+ lambda m: _stash(f"<code>{m.group(1)}</code>"), escaped+ )+ escaped = _BOLD_RE.sub(r"<b>\1</b>", escaped)+ escaped = _LINK_RE.sub(r'<a href="\2">\1</a>', escaped)+ for i, rendered in enumerate(stashed):+ escaped = escaped.replace(_STASH.format(i), rendered)+ return escapeddiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/text_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/text_test.pynew file mode 100644index 0000000000..820d3e90dc--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/text_test.py@@ -0,0 +1,35 @@+"""Tests for CommonMark → Telegram HTML conversion."""++from .text import to_html+++def test_bold_and_links_become_html_tags():+ assert to_html("**hi** [docs](https://x.io)") == (+ '<b>hi</b> <a href="https://x.io">docs</a>'+ )+++def test_inline_code_and_code_blocks():+ assert to_html("run `ls` now") == "run <code>ls</code> now"+ assert to_html("```py\nprint(1)\n```") == "<pre>print(1)</pre>"+++def test_html_in_input_is_escaped_not_rendered():+ # Model/user output must not be able to inject live tags.+ assert to_html("<script>alert(1)</script>") == (+ "<script>alert(1)</script>"+ )+++def test_plain_text_survives_unchanged():+ assert to_html("just words, no markup") == "just words, no markup"+++def test_markdown_inside_code_spans_stays_literal():+ block = "```" + "\n**kwargs** and [x](y)\n" + "```"+ assert to_html(block) == "<pre>**kwargs** and [x](y)</pre>"+ assert to_html("`**bold**`") == "<code>**bold**</code>"+++def test_double_quotes_escape_so_hrefs_stay_valid():+ assert to_html('a "quoted" word') == "a "quoted" word"diff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.pyindex 24ec7a2c99..8ef1fa1e85 100644--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py@@ -14,6 +14,8 @@ from fastapi import FastAPIfrom .adapters.base import WebhookAdapterfrom .adapters.slack import config as slack_configfrom .adapters.slack.adapter import SlackAdapter+from .adapters.telegram import config as telegram_config+from .adapters.telegram.adapter import TelegramAdapterfrom .bot_backend import BotBackendfrom .handler import MessageHandler@@ -51,4 +53,9 @@ def _build_webhook_adapters(api: BotBackend) -> list[WebhookAdapter]:if slack_config.get_signing_secret() and has_credentials:adapters.append(SlackAdapter(api))logger.info("Slack adapter enabled")+ # Telegram: one BotFather token for every chat; the webhook secret is what+ # authenticates inbound updates, so both are required.+ if telegram_config.get_bot_token() and telegram_config.get_webhook_secret():+ adapters.append(TelegramAdapter(api))+ logger.info("Telegram adapter enabled")return adaptersdiff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.pyindex 9c35bf587f..6e396791d6 100644--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py@@ -8,18 +8,21 @@ from .adapters.base import WebhookAdapterfrom .webhook_routes import _build_webhook_adapters, register_webhook_adapters_SLACK_CFG = "backend.copilot.bot.webhook_routes.slack_config"+_TELEGRAM_CFG = "backend.copilot.bot.webhook_routes.telegram_config"-def test_build_webhook_adapters_empty_without_slack_creds():+def test_build_webhook_adapters_empty_without_creds():with (patch(f"{_SLACK_CFG}.get_bot_token", return_value=""),patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),+ patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value=""),):assert _build_webhook_adapters(MagicMock()) == []def test_build_webhook_adapters_includes_slack_when_configured():with (+ patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value=""),patch(f"{_SLACK_CFG}.get_bot_token", return_value="xoxb-x"),patch(f"{_SLACK_CFG}.get_signing_secret", return_value="secret"),patch("backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"),@@ -29,6 +32,28 @@ def test_build_webhook_adapters_includes_slack_when_configured():assert adapters[0].platform_name == "slack"+def test_build_webhook_adapters_includes_telegram_when_configured():+ with (+ patch(f"{_SLACK_CFG}.get_bot_token", return_value=""),+ patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),+ patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value="123:abc"),+ patch(f"{_TELEGRAM_CFG}.get_webhook_secret", return_value="s3cret"),+ ):+ adapters = _build_webhook_adapters(MagicMock())+ assert len(adapters) == 1+ assert adapters[0].platform_name == "telegram"+++def test_telegram_needs_both_token_and_webhook_secret():+ with (+ patch(f"{_SLACK_CFG}.get_bot_token", return_value=""),+ patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),+ patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value="123:abc"),+ patch(f"{_TELEGRAM_CFG}.get_webhook_secret", return_value=""),+ ):+ assert _build_webhook_adapters(MagicMock()) == []++def test_register_webhook_adapters_wires_each_adapter():app = FastAPI()adapter = MagicMock(spec=WebhookAdapter)diff --git a/autogpt_platform/backend/backend/data/db_accessors.py b/autogpt_platform/backend/backend/data/db_accessors.pyindex f5508f4b9a..6026cf4bf2 100644--- a/autogpt_platform/backend/backend/data/db_accessors.py+++ b/autogpt_platform/backend/backend/data/db_accessors.py@@ -170,6 +170,19 @@ def platform_cost_db():return platform_cost_db+def orgs_db():+ if db.is_connected():+ from backend.api.features.orgs import db as _orgs_db++ orgs_db = _orgs_db+ else:+ from backend.util.clients import get_database_manager_async_client++ orgs_db = get_database_manager_async_client()++ return orgs_db++def platform_linking_db():if db.is_connected():from backend.platform_linking import db as _platform_linking_dbdiff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex b43dd63c02..f5d9839c64 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -30,6 +30,7 @@ from backend.api.features.library.triggers import (setup_triggered_preset,update_triggered_preset,)+from backend.api.features.orgs.db import get_user_default_teamfrom backend.api.features.search.embeddings import (cleanup_orphaned_embeddings,get_embedding_stats,@@ -432,6 +433,9 @@ class DatabaseManager(AppService):reconcile_stripe_tier_for_user = _(reconcile_stripe_tier_for_user)# ============ Platform Linking ============ #+ # ============ Orgs ============ #+ get_user_default_team = _(get_user_default_team)+find_server_link_owner = _(platform_linking_db.find_server_link_owner)find_user_link_owner = _(platform_linking_db.find_user_link_owner)resolve_server_link = _(platform_linking_db.resolve_server_link)@@ -705,6 +709,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):# ============ Platform Linking ============ #find_server_link_owner = d.find_server_link_owner+ get_user_default_team = d.get_user_default_teamfind_user_link_owner = d.find_user_link_ownerresolve_server_link = d.resolve_server_linkresolve_user_link = d.resolve_user_linkdiff --git a/autogpt_platform/backend/backend/platform_linking/chat.py b/autogpt_platform/backend/backend/platform_linking/chat.pyindex 19cd826233..b518840244 100644--- a/autogpt_platform/backend/backend/platform_linking/chat.py+++ b/autogpt_platform/backend/backend/platform_linking/chat.py@@ -3,7 +3,6 @@import loggingfrom uuid import uuid4-from backend.api.features.orgs.db import get_user_default_teamfrom backend.api.features.store.exceptions import VirusDetectedError, VirusScanErrorfrom backend.copilot import stream_registryfrom backend.copilot.config import ChatConfig@@ -23,7 +22,7 @@ from backend.copilot.rate_limit import (get_global_rate_limits,is_user_paywalled,)-from backend.data.db_accessors import platform_linking_db, workspace_db+from backend.data.db_accessors import orgs_db, platform_linking_db, workspace_dbfrom backend.util.exceptions import DuplicateChatMessageError, NotFoundErrorfrom backend.util.settings import Settingsfrom backend.util.workspace import WorkspaceManager@@ -242,7 +241,7 @@ async def _resolve_or_create_session(if session_id:session = await get_chat_session(session_id, owner_user_id)if session is None:- org_id, team_id = await get_user_default_team(owner_user_id)+ org_id, team_id = await orgs_db().get_user_default_team(owner_user_id)session = await create_chat_session(owner_user_id,dry_run=False,@@ -351,7 +350,7 @@ async def start_chat_turn(request: BotChatRequest) -> ChatTurnHandle:turn_id=turn_id,)- org_id, team_id = await get_user_default_team(owner_user_id)+ org_id, team_id = await orgs_db().get_user_default_team(owner_user_id)await enqueue_copilot_turn(session_id=session_id,user_id=owner_user_id,diff --git a/autogpt_platform/backend/backend/platform_linking/chat_test.py b/autogpt_platform/backend/backend/platform_linking/chat_test.pyindex 658ae50663..bc02a802ae 100644--- a/autogpt_platform/backend/backend/platform_linking/chat_test.py+++ b/autogpt_platform/backend/backend/platform_linking/chat_test.py@@ -35,10 +35,9 @@ class TestStartChatTurn:# Bot-originated chats resolve the owner's default org/team so the# ChatSession is created with tenancy context. Tests don't seed# OrgMember rows, so stub the lookup to return None tuples.- with patch(- "backend.platform_linking.chat.get_user_default_team",- new=AsyncMock(return_value=(None, None)),- ):+ orgs = MagicMock()+ orgs.get_user_default_team = AsyncMock(return_value=(None, None))+ with patch("backend.platform_linking.chat.orgs_db", return_value=orgs):yield@pytest.fixture(autouse=True)@@ -444,8 +443,10 @@ class TestEnsureChatSession:with (patch("backend.platform_linking.chat.platform_linking_db", return_value=db),patch(- "backend.platform_linking.chat.get_user_default_team",- new=AsyncMock(return_value=("org-1", "team-1")),+ "backend.platform_linking.chat.orgs_db",+ return_value=MagicMock(+ get_user_default_team=AsyncMock(return_value=("org-1", "team-1"))+ ),),patch("backend.platform_linking.chat.create_chat_session",diff --git a/autogpt_platform/backend/backend/platform_linking/db.py b/autogpt_platform/backend/backend/platform_linking/db.pyindex c755d1354a..9fb58f3373 100644--- a/autogpt_platform/backend/backend/platform_linking/db.py+++ b/autogpt_platform/backend/backend/platform_linking/db.py@@ -244,7 +244,23 @@ async def get_link_token_info(token: str) -> LinkTokenInfoResponse:# ── Confirmation (user-facing, JWT-authed) ────────────────────────────-async def confirm_server_link(token: str, user_id: str) -> ConfirmLinkResponse:+def _enforce_verified_identity(+ token_platform_user_id: str, verified_platform_user_id: str | None+) -> None:+ """When the caller carries a platform-verified identity (Telegram+ login_url payload), the token must have been minted for that same+ platform user — a forwarded/leaked link URL then fails instead of+ binding to whoever opened it."""+ if (+ verified_platform_user_id is not None+ and token_platform_user_id != verified_platform_user_id+ ):+ raise NotAuthorizedError("This link was created for a different platform user.")+++async def confirm_server_link(+ token: str, user_id: str, verified_platform_user_id: str | None = None+) -> ConfirmLinkResponse:link_token = await PlatformLinkToken.prisma().find_unique(where={"token": token})if not link_token:@@ -257,6 +273,7 @@ async def confirm_server_link(token: str, user_id: str) -> ConfirmLinkResponse:raise LinkTokenExpiredError("This link has expired.")if not link_token.platformServerId:raise LinkFlowMismatchError("Server token missing server ID.")+ _enforce_verified_identity(link_token.platformUserId, verified_platform_user_id)owner = await find_server_link_owner(link_token.platform, link_token.platformServerId@@ -308,7 +325,9 @@ async def confirm_server_link(token: str, user_id: str) -> ConfirmLinkResponse:)-async def confirm_user_link(token: str, user_id: str) -> ConfirmUserLinkResponse:+async def confirm_user_link(+ token: str, user_id: str, verified_platform_user_id: str | None = None+) -> ConfirmUserLinkResponse:link_token = await PlatformLinkToken.prisma().find_unique(where={"token": token})if not link_token:@@ -319,6 +338,7 @@ async def confirm_user_link(token: str, user_id: str) -> ConfirmUserLinkResponseraise LinkTokenExpiredError("This link has already been used.")if link_token.expiresAt.replace(tzinfo=timezone.utc) < datetime.now(timezone.utc):raise LinkTokenExpiredError("This link has expired.")+ _enforce_verified_identity(link_token.platformUserId, verified_platform_user_id)owner = await find_user_link_owner(link_token.platform, link_token.platformUserId)if owner:diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 364d44eb10..a48158c00b 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -790,6 +790,22 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):description="Slack app OAuth client secret — exchanged with the auth ""code on the install callback for a per-workspace bot token.",)+ autopilot_bot_telegram_token: str = Field(+ default="",+ description="Telegram bot token (from @BotFather). Set together with "+ "the webhook secret to mount the Telegram adapter on the main API.",+ )+ autopilot_bot_telegram_webhook_secret: str = Field(+ default="",+ description="Secret registered with Telegram's setWebhook; Telegram "+ "echoes it in the X-Telegram-Bot-Api-Secret-Token header and inbound "+ "updates are rejected unless it matches.",+ )+ autopilot_bot_telegram_username: str = Field(+ default="",+ description="The bot's public @username (without the @) — used to "+ "build the t.me add-to-group link on the Bots settings page.",+ )smtp_server: str = Field(default="", description="SMTP server IP")smtp_port: str = Field(default="", description="SMTP server port")diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsxindex eff3e51422..d9fb00e2c0 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx@@ -179,6 +179,51 @@ describe("PlatformLinkPage", () => {).toBeDefined();});+ test("forwards telegram login params to the confirm endpoint", async () => {+ mockUseSearchParams.mockReturnValue(+ new URLSearchParams({+ id: "424242",+ first_name: "Bently",+ auth_date: "1750000000",+ hash: "abc123",+ }),+ );+ let capturedBody: unknown = null;+ server.use(+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({+ platform: "TELEGRAM",+ link_type: LinkType.USER,+ server_name: null,+ }),+ getPostPlatformLinkingConfirmAUserLinkTokenUserMustBeAuthenticatedMockHandler200(+ async (info) => {+ capturedBody = await info.request.json();+ return {+ success: true,+ link_type: LinkType.USER,+ platform: "TELEGRAM",+ platform_user_id: "424242",+ };+ },+ ),+ );++ render(<PlatformLinkPage />);+ fireEvent.click(+ await screen.findByRole("button", { name: /connect my telegram dms/i }),+ );+ await screen.findByRole("heading", { name: /autogpt is ready/i });++ expect(capturedBody).toEqual({+ telegram_auth: {+ id: "424242",+ first_name: "Bently",+ auth_date: "1750000000",+ hash: "abc123",+ },+ });+ });+test("loads user link details and confirms the user link endpoint", async () => {let serverConfirmCalls = 0;let userConfirmCalls = 0;diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/helpers.tsindex 02d5c9c5a8..c948635ce6 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/helpers.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/helpers.ts@@ -27,3 +27,25 @@ export function getLoginRedirect(token: string | null): string {export function isUserLink(linkType: LinkType | undefined): boolean {return linkType === LinkType.USER;}++const TELEGRAM_AUTH_KEYS = [+ "id",+ "first_name",+ "last_name",+ "username",+ "photo_url",+ "auth_date",+ "hash",+] as const;++export function getTelegramAuth(+ searchParams: URLSearchParams,+): Record<string, string> | null {+ if (!searchParams.get("id") || !searchParams.get("hash")) return null;+ const auth: Record<string, string> = {};+ for (const key of TELEGRAM_AUTH_KEYS) {+ const value = searchParams.get(key);+ if (value !== null) auth[key] = value;+ }+ return auth;+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.tsindex af78efc99a..36770f5351 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts@@ -11,6 +11,7 @@ import { useParams, useSearchParams } from "next/navigation";import {getLoginRedirect,getPlatformDisplayName,+ getTelegramAuth,isUserLink,TOKEN_PATTERN,} from "./helpers";@@ -74,7 +75,12 @@ export function usePlatformLinkingPage() {function handleLink() {if (!token || !info) return;- mutation.mutate({ token });+ // A login_url button tap appends a Telegram-signed identity to this+ // page's URL; forwarding it lets the backend verify WHO opened the link.+ mutation.mutate({+ token,+ data: { telegram_auth: getTelegramAuth(searchParams) },+ });}async function handleSwitchAccount() {diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/bots/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/bots/__tests__/main.test.tsxindex 7e9c4de854..c6f4462238 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/bots/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/bots/__tests__/main.test.tsx@@ -105,7 +105,7 @@ describe("BotsContent", () => {server.use(getGetV2TopServersByActivityMockHandler200([{- platform: "TELEGRAM",+ platform: "MATRIX",server_id: "tg1",name: "Mystery",messages: 1,@@ -116,6 +116,6 @@ describe("BotsContent", () => {render(<BotsContent />);// No label entry exists for TELEGRAM, so the badge shows the raw key.- expect(await screen.findByText("TELEGRAM")).toBeDefined();+ expect(await screen.findByText("MATRIX")).toBeDefined();});});diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/bots/components/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/bots/components/helpers.tsindex 7a62b70dbc..b95ac062fc 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/bots/components/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/admin/bots/components/helpers.ts@@ -10,6 +10,7 @@ export const PLATFORM_OPTIONS = [{ value: "all", label: "All platforms" },{ value: "DISCORD", label: "Discord" },{ value: "SLACK", label: "Slack" },+ { value: "TELEGRAM", label: "Telegram" },];export function formatNumber(value: number | null | undefined): string {diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotsList/BotsList.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotsList/BotsList.tsxindex 8250acb4b3..d77982abc4 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotsList/BotsList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotsList/BotsList.tsx@@ -47,7 +47,7 @@ export function BotsList() {}return (- <div className="flex w-full flex-col gap-4 px-4 pb-4">+ <div className="grid w-full grid-cols-1 items-start gap-4 px-4 pb-4 lg:grid-cols-2">{platforms.map((platform) => (<BotCard key={platform.platform} platform={platform} />))}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex cb523b96e7..376232253f 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -10048,6 +10048,19 @@}}],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "anyOf": [+ { "$ref": "#/components/schemas/ConfirmLinkRequest" },+ { "type": "null" }+ ],+ "title": "Body"+ }+ }+ }+ },"responses": {"200": {"description": "Successful Response",@@ -10198,6 +10211,19 @@}}],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "anyOf": [+ { "$ref": "#/components/schemas/ConfirmLinkRequest" },+ { "type": "null" }+ ],+ "title": "Body"+ }+ }+ }+ },"responses": {"200": {"description": "Successful Response",@@ -14781,6 +14807,23 @@"required": ["uuid"],"title": "CommunitySummary"},+ "ConfirmLinkRequest": {+ "properties": {+ "telegram_auth": {+ "anyOf": [+ {+ "additionalProperties": { "type": "string" },+ "type": "object"+ },+ { "type": "null" }+ ],+ "title": "Telegram Auth"+ }+ },+ "type": "object",+ "title": "ConfirmLinkRequest",+ "description": "Optional confirm payload. ``telegram_auth`` carries the signed identity\nTelegram appends when the user reached this page via a login_url button —\nwhen present it must verify, and the link token must belong to that same\nTelegram user."+ },"ConfirmLinkResponse": {"properties": {"success": { "type": "boolean", "title": "Success" },