Skip to content

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(blocks): Add Telegram blocks (#12141)

Krzysztof Czerwinskia1cb3d2a9191
diff --git a/autogpt_platform/backend/backend/blocks/telegram/_api.py b/autogpt_platform/backend/backend/blocks/telegram/_api.py
new file mode 100644
index 0000000000..9cf9740ecd
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/telegram/_api.py
@@ -0,0 +1,182 @@
+"""
+Telegram Bot API helper functions.
+
+Provides utilities for making authenticated requests to the Telegram Bot API.
+"""
+
+import logging
+from io import BytesIO
+from typing import Any, Optional
+
+from pydantic import BaseModel
+
+from backend.data.model import APIKeyCredentials
+from backend.util.request import Requests
+
+logger = logging.getLogger(__name__)
+
+TELEGRAM_API_BASE = "https://api.telegram.org"
+
+
+class TelegramMessageResult(BaseModel, extra="allow"):
+ """Result from Telegram send/edit message API calls."""
+
+ message_id: int = 0
+ chat: dict[str, Any] = {}
+ date: int = 0
+ text: str = ""
+
+
+class TelegramFileResult(BaseModel, extra="allow"):
+ """Result from Telegram getFile API call."""
+
+ file_id: str = ""
+ file_unique_id: str = ""
+ file_size: int = 0
+ file_path: str = ""
+
+
+class TelegramAPIException(ValueError):
+ """Exception raised for Telegram API errors."""
+
+ def __init__(self, message: str, error_code: int = 0):
+ super().__init__(message)
+ self.error_code = error_code
+
+
+def get_bot_api_url(bot_token: str, method: str) -> str:
+ """Construct Telegram Bot API URL for a method."""
+ return f"{TELEGRAM_API_BASE}/bot{bot_token}/{method}"
+
+
+def get_file_url(bot_token: str, file_path: str) -> str:
+ """Construct Telegram file download URL."""
+ return f"{TELEGRAM_API_BASE}/file/bot{bot_token}/{file_path}"
+
+
+async def call_telegram_api(
+ credentials: APIKeyCredentials,
+ method: str,
+ data: Optional[dict[str, Any]] = None,
+) -> TelegramMessageResult:
+ """
+ Make a request to the Telegram Bot API.
+
+ Args:
+ credentials: Bot token credentials
+ method: API method name (e.g., "sendMessage", "getFile")
+ data: Request parameters
+
+ Returns:
+ API response result
+
+ Raises:
+ TelegramAPIException: If the API returns an error
+ """
+ token = credentials.api_key.get_secret_value()
+ url = get_bot_api_url(token, method)
+
+ response = await Requests().post(url, json=data or {})
+ result = response.json()
+
+ if not result.get("ok"):
+ error_code = result.get("error_code", 0)
+ description = result.get("description", "Unknown error")
+ raise TelegramAPIException(description, error_code)
+
+ return TelegramMessageResult(**result.get("result", {}))
+
+
+async def call_telegram_api_with_file(
+ credentials: APIKeyCredentials,
+ method: str,
+ file_field: str,
+ file_data: bytes,
+ filename: str,
+ content_type: str,
+ data: Optional[dict[str, Any]] = None,
+) -> TelegramMessageResult:
+ """
+ Make a multipart/form-data request to the Telegram Bot API with a file upload.
+
+ Args:
+ credentials: Bot token credentials
+ method: API method name (e.g., "sendPhoto", "sendVoice")
+ file_field: Form field name for the file (e.g., "photo", "voice")
+ file_data: Raw file bytes
+ filename: Filename for the upload
+ content_type: MIME type of the file
+ data: Additional form parameters
+
+ Returns:
+ API response result
+
+ Raises:
+ TelegramAPIException: If the API returns an error
+ """
+ token = credentials.api_key.get_secret_value()
+ url = get_bot_api_url(token, method)
+
+ files = [(file_field, (filename, BytesIO(file_data), content_type))]
+
+ response = await Requests().post(url, files=files, data=data or {})
+ result = response.json()
+
+ if not result.get("ok"):
+ error_code = result.get("error_code", 0)
+ description = result.get("description", "Unknown error")
+ raise TelegramAPIException(description, error_code)
+
+ return TelegramMessageResult(**result.get("result", {}))
+
+
+async def get_file_info(
+ credentials: APIKeyCredentials, file_id: str
+) -> TelegramFileResult:
+ """
+ Get file information from Telegram.
+
+ Args:
+ credentials: Bot token credentials
+ file_id: Telegram file_id from message
+
+ Returns:
+ File info dict containing file_id, file_unique_id, file_size, file_path
+ """
+ result = await call_telegram_api(credentials, "getFile", {"file_id": file_id})
+ return TelegramFileResult(**result.model_dump())
+
+
+async def get_file_download_url(credentials: APIKeyCredentials, file_id: str) -> str:
+ """
+ Get the download URL for a Telegram file.
+
+ Args:
+ credentials: Bot token credentials
+ file_id: Telegram file_id from message
+
+ Returns:
+ Full download URL
+ """
+ token = credentials.api_key.get_secret_value()
+ result = await get_file_info(credentials, file_id)
+ file_path = result.file_path
+ if not file_path:
+ raise TelegramAPIException("No file_path returned from getFile")
+ return get_file_url(token, file_path)
+
+
+async def download_telegram_file(credentials: APIKeyCredentials, file_id: str) -> bytes:
+ """
+ Download a file from Telegram servers.
+
+ Args:
+ credentials: Bot token credentials
+ file_id: Telegram file_id
+
+ Returns:
+ File content as bytes
+ """
+ url = await get_file_download_url(credentials, file_id)
+ response = await Requests().get(url)
+ return response.content
diff --git a/autogpt_platform/backend/backend/blocks/telegram/_auth.py b/autogpt_platform/backend/backend/blocks/telegram/_auth.py
new file mode 100644
index 0000000000..bc7561d4c2
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/telegram/_auth.py
@@ -0,0 +1,43 @@
+"""
+Telegram Bot credentials handling.
+
+Telegram bots use an API key (bot token) obtained from @BotFather.
+"""
+
+from typing import Literal
+
+from pydantic import SecretStr
+
+from backend.data.model import APIKeyCredentials, CredentialsField, CredentialsMetaInput
+from backend.integrations.providers import ProviderName
+
+# Bot token credentials (API key style)
+TelegramCredentials = APIKeyCredentials
+TelegramCredentialsInput = CredentialsMetaInput[
+ Literal[ProviderName.TELEGRAM], Literal["api_key"]
+]
+
+
+def TelegramCredentialsField() -> TelegramCredentialsInput:
+ """Creates a Telegram bot token credentials field."""
+ return CredentialsField(
+ description="Telegram Bot API token from @BotFather. "
+ "Create a bot at https://t.me/BotFather to get your token."
+ )
+
+
+# Test credentials for unit tests
+TEST_CREDENTIALS = APIKeyCredentials(
+ id="01234567-89ab-cdef-0123-456789abcdef",
+ provider="telegram",
+ api_key=SecretStr("test_telegram_bot_token"),
+ title="Mock Telegram Bot Token",
+ expires_at=None,
+)
+
+TEST_CREDENTIALS_INPUT = {
+ "provider": TEST_CREDENTIALS.provider,
+ "id": TEST_CREDENTIALS.id,
+ "type": TEST_CREDENTIALS.type,
+ "title": TEST_CREDENTIALS.title,
+}
diff --git a/autogpt_platform/backend/backend/blocks/telegram/blocks.py b/autogpt_platform/backend/backend/blocks/telegram/blocks.py
new file mode 100644
index 0000000000..08155ede46
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/telegram/blocks.py
@@ -0,0 +1,1254 @@
+"""
+Telegram action blocks for sending messages, media, and managing chat content.
+"""
+
+import base64
+import logging
+import mimetypes
+from enum import Enum
+from pathlib import Path
+from typing import Any, Optional
+
+from backend.blocks._base import (
+ Block,
+ BlockCategory,
+ BlockOutput,
+ BlockSchemaInput,
+ BlockSchemaOutput,
+)
+from backend.data.execution import ExecutionContext
+from backend.data.model import APIKeyCredentials, SchemaField
+from backend.util.file import get_exec_file_path, store_media_file
+from backend.util.type import MediaFileType
+
+from ._api import (
+ TelegramMessageResult,
+ call_telegram_api,
+ call_telegram_api_with_file,
+ download_telegram_file,
+)
+from ._auth import (
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ TelegramCredentialsField,
+ TelegramCredentialsInput,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class ParseMode(str, Enum):
+ """Telegram message parse modes."""
+
+ NONE = "none"
+ MARKDOWN = "Markdown"
+ MARKDOWNV2 = "MarkdownV2"
+ HTML = "HTML"
+
+
+class SendTelegramMessageBlock(Block):
+ """Send a text message to a Telegram chat."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(
+ description="The chat ID to send the message to. "
+ "Get this from the trigger block's chat_id output."
+ )
+ text: str = SchemaField(
+ description="The text message to send (max 4096 characters)"
+ )
+ parse_mode: ParseMode = SchemaField(
+ description="Message formatting mode (Markdown, HTML, or none)",
+ default=ParseMode.NONE,
+ advanced=True,
+ )
+ reply_to_message_id: Optional[int] = SchemaField(
+ description="Message ID to reply to",
+ default=None,
+ advanced=True,
+ )
+ disable_notification: bool = SchemaField(
+ description="Send message silently (no notification sound)",
+ default=False,
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ message_id: int = SchemaField(description="The ID of the sent message")
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="787678ad-1f47-4efc-89df-643f9908621a",
+ description="Send a text message to a Telegram chat.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=SendTelegramMessageBlock.Input,
+ output_schema=SendTelegramMessageBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "text": "Hello from AutoGPT!",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("message_id", 123),
+ ("status", "Message sent"),
+ ],
+ test_mock={
+ "_send_message": lambda *args, **kwargs: TelegramMessageResult(
+ message_id=123,
+ )
+ },
+ )
+
+ async def run(
+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs
+ ) -> BlockOutput:
+ try:
+ result = await self._send_message(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ text=input_data.text,
+ parse_mode=input_data.parse_mode.value,
+ reply_to_message_id=input_data.reply_to_message_id,
+ disable_notification=input_data.disable_notification,
+ )
+ yield "message_id", result.message_id
+ yield "status", "Message sent"
+ except Exception as e:
+ raise ValueError(f"Failed to send message: {e}") from e
+
+ async def _send_message(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ text: str,
+ parse_mode: str,
+ reply_to_message_id: Optional[int],
+ disable_notification: bool,
+ ) -> TelegramMessageResult:
+ data: dict[str, Any] = {
+ "chat_id": chat_id,
+ "text": text,
+ }
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+ if reply_to_message_id:
+ data["reply_to_message_id"] = reply_to_message_id
+ if disable_notification:
+ data["disable_notification"] = True
+
+ return await call_telegram_api(credentials, "sendMessage", data)
+
+
+class SendTelegramPhotoBlock(Block):
+ """Send a photo to a Telegram chat."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(description="The chat ID to send the photo to")
+ photo: MediaFileType = SchemaField(
+ description="Photo to send (URL, data URI, or workspace:// reference). "
+ "URLs are preferred as Telegram will fetch them directly."
+ )
+ caption: str = SchemaField(
+ description="Caption for the photo (max 1024 characters)",
+ default="",
+ advanced=True,
+ )
+ parse_mode: ParseMode = SchemaField(
+ description="Caption formatting mode",
+ default=ParseMode.NONE,
+ advanced=True,
+ )
+ reply_to_message_id: Optional[int] = SchemaField(
+ description="Message ID to reply to",
+ default=None,
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ message_id: int = SchemaField(description="The ID of the sent message")
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="ceb9fd95-fd95-49ff-b57b-278957255716",
+ description="Send a photo to a Telegram chat.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=SendTelegramPhotoBlock.Input,
+ output_schema=SendTelegramPhotoBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "photo": "https://example.com/image.jpg",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("message_id", 123),
+ ("status", "Photo sent"),
+ ],
+ test_mock={
+ "_send_photo_url": lambda *args, **kwargs: TelegramMessageResult(
+ message_id=123
+ )
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: APIKeyCredentials,
+ execution_context: ExecutionContext,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ photo_input = input_data.photo
+
+ # If it's a URL, pass it directly to Telegram (it will fetch it)
+ if photo_input.startswith(("http://", "https://")):
+ result = await self._send_photo_url(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ photo_url=photo_input,
+ caption=input_data.caption,
+ parse_mode=input_data.parse_mode.value,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+ else:
+ # For data URIs or workspace:// references, resolve to local
+ # file and upload via multipart/form-data
+ relative_path = await store_media_file(
+ file=input_data.photo,
+ execution_context=execution_context,
+ return_format="for_local_processing",
+ )
+ if not execution_context.graph_exec_id:
+ raise ValueError("graph_exec_id is required")
+ abs_path = get_exec_file_path(
+ execution_context.graph_exec_id, relative_path
+ )
+ result = await self._send_photo_file(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ file_path=abs_path,
+ caption=input_data.caption,
+ parse_mode=input_data.parse_mode.value,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+
+ yield "message_id", result.message_id
+ yield "status", "Photo sent"
+ except Exception as e:
+ raise ValueError(f"Failed to send photo: {e}") from e
+
+ async def _send_photo_url(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ photo_url: str,
+ caption: str,
+ parse_mode: str,
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ data: dict[str, Any] = {
+ "chat_id": chat_id,
+ "photo": photo_url,
+ }
+ if caption:
+ data["caption"] = caption
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+ if reply_to_message_id:
+ data["reply_to_message_id"] = reply_to_message_id
+
+ return await call_telegram_api(credentials, "sendPhoto", data)
+
+ async def _send_photo_file(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ file_path: str,
+ caption: str,
+ parse_mode: str,
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ path = Path(file_path)
+ file_bytes = path.read_bytes()
+ data: dict[str, Any] = {"chat_id": str(chat_id)}
+ if caption:
+ data["caption"] = caption
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+ if reply_to_message_id:
+ data["reply_to_message_id"] = str(reply_to_message_id)
+
+ mime_type = mimetypes.guess_type(path.name)[0] or "image/jpeg"
+ return await call_telegram_api_with_file(
+ credentials,
+ "sendPhoto",
+ file_field="photo",
+ file_data=file_bytes,
+ filename=path.name,
+ content_type=mime_type,
+ data=data,
+ )
+
+
+class SendTelegramVoiceBlock(Block):
+ """Send a voice message to a Telegram chat."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(
+ description="The chat ID to send the voice message to"
+ )
+ voice: MediaFileType = SchemaField(
+ description="Voice message to send (OGG format with OPUS codec). "
+ "Can be URL, data URI, or workspace:// reference."
+ )
+ caption: str = SchemaField(
+ description="Caption for the voice message",
+ default="",
+ advanced=True,
+ )
+ duration: Optional[int] = SchemaField(
+ description="Duration in seconds",
+ default=None,
+ advanced=True,
+ )
+ reply_to_message_id: Optional[int] = SchemaField(
+ description="Message ID to reply to",
+ default=None,
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ message_id: int = SchemaField(description="The ID of the sent message")
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="7a0ef660-1a5b-4951-8642-c13a0c8d6d93",
+ description="Send a voice message to a Telegram chat. "
+ "Voice must be OGG format with OPUS codec.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=SendTelegramVoiceBlock.Input,
+ output_schema=SendTelegramVoiceBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "voice": "https://example.com/voice.ogg",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("message_id", 123),
+ ("status", "Voice sent"),
+ ],
+ test_mock={
+ "_send_voice_url": lambda *args, **kwargs: TelegramMessageResult(
+ message_id=123
+ )
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: APIKeyCredentials,
+ execution_context: ExecutionContext,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ voice_input = input_data.voice
+
+ # If it's a URL, pass it directly to Telegram
+ if voice_input.startswith(("http://", "https://")):
+ result = await self._send_voice_url(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ voice_url=voice_input,
+ caption=input_data.caption,
+ duration=input_data.duration,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+ else:
+ # For data URIs or workspace:// references, resolve to local
+ # file and upload via multipart/form-data
+ relative_path = await store_media_file(
+ file=input_data.voice,
+ execution_context=execution_context,
+ return_format="for_local_processing",
+ )
+ if not execution_context.graph_exec_id:
+ raise ValueError("graph_exec_id is required")
+ abs_path = get_exec_file_path(
+ execution_context.graph_exec_id, relative_path
+ )
+ result = await self._send_voice_file(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ file_path=abs_path,
+ caption=input_data.caption,
+ duration=input_data.duration,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+
+ yield "message_id", result.message_id
+ yield "status", "Voice sent"
+ except Exception as e:
+ raise ValueError(f"Failed to send voice: {e}") from e
+
+ async def _send_voice_url(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ voice_url: str,
+ caption: str,
+ duration: Optional[int],
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ data: dict[str, Any] = {
+ "chat_id": chat_id,
+ "voice": voice_url,
+ }
+ if caption:
+ data["caption"] = caption
+ if duration:
+ data["duration"] = duration
+ if reply_to_message_id:
+ data["reply_to_message_id"] = reply_to_message_id
+
+ return await call_telegram_api(credentials, "sendVoice", data)
+
+ async def _send_voice_file(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ file_path: str,
+ caption: str,
+ duration: Optional[int],
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ path = Path(file_path)
+ file_bytes = path.read_bytes()
+ data: dict[str, Any] = {"chat_id": str(chat_id)}
+ if caption:
+ data["caption"] = caption
+ if duration:
+ data["duration"] = str(duration)
+ if reply_to_message_id:
+ data["reply_to_message_id"] = str(reply_to_message_id)
+
+ mime_type = mimetypes.guess_type(path.name)[0] or "audio/ogg"
+ return await call_telegram_api_with_file(
+ credentials,
+ "sendVoice",
+ file_field="voice",
+ file_data=file_bytes,
+ filename=path.name,
+ content_type=mime_type,
+ data=data,
+ )
+
+
+class ReplyToTelegramMessageBlock(Block):
+ """Reply to a specific Telegram message."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(description="The chat ID where the message is")
+ reply_to_message_id: int = SchemaField(description="The message ID to reply to")
+ text: str = SchemaField(description="The reply text")
+ parse_mode: ParseMode = SchemaField(
+ description="Message formatting mode",
+ default=ParseMode.NONE,
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ message_id: int = SchemaField(description="The ID of the reply message")
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="c2b1c976-844f-4b6c-ab21-4973d2ceab15",
+ description="Reply to a specific message in a Telegram chat.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=ReplyToTelegramMessageBlock.Input,
+ output_schema=ReplyToTelegramMessageBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "reply_to_message_id": 42,
+ "text": "This is a reply!",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("message_id", 123),
+ ("status", "Reply sent"),
+ ],
+ test_mock={
+ "_send_reply": lambda *args, **kwargs: TelegramMessageResult(
+ message_id=123
+ )
+ },
+ )
+
+ async def run(
+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs
+ ) -> BlockOutput:
+ try:
+ result = await self._send_reply(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ reply_to_message_id=input_data.reply_to_message_id,
+ text=input_data.text,
+ parse_mode=input_data.parse_mode.value,
+ )
+ yield "message_id", result.message_id
+ yield "status", "Reply sent"
+ except Exception as e:
+ raise ValueError(f"Failed to send reply: {e}") from e
+
+ async def _send_reply(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ reply_to_message_id: int,
+ text: str,
+ parse_mode: str,
+ ) -> TelegramMessageResult:
+ data: dict[str, Any] = {
+ "chat_id": chat_id,
+ "text": text,
+ "reply_to_message_id": reply_to_message_id,
+ }
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+
+ return await call_telegram_api(credentials, "sendMessage", data)
+
+
+class GetTelegramFileBlock(Block):
+ """Download a file from Telegram by file_id."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ file_id: str = SchemaField(
+ description="The Telegram file_id to download. "
+ "Get this from trigger outputs (photo_file_id, voice_file_id, etc.)"
+ )
+
+ class Output(BlockSchemaOutput):
+ file: MediaFileType = SchemaField(
+ description="The downloaded file (workspace:// reference or data URI)"
+ )
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="b600aaf2-6272-40c6-b973-c3984747c5bd",
+ description="Download a file from Telegram using its file_id. "
+ "Use this to process photos, voice messages, or documents received.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=GetTelegramFileBlock.Input,
+ output_schema=GetTelegramFileBlock.Output,
+ test_input={
+ "file_id": "AgACAgIAAxkBAAI...",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("file", "data:application/octet-stream;base64,dGVzdA=="),
+ ("status", "File downloaded"),
+ ],
+ test_mock={"_download_file": lambda *args, **kwargs: b"test"},
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: APIKeyCredentials,
+ execution_context: ExecutionContext,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ # Download the file from Telegram
+ file_content = await self._download_file(
+ credentials=credentials,
+ file_id=input_data.file_id,
+ )
+
+ # Convert to data URI and wrap as MediaFileType
+ mime_type = "application/octet-stream"
+ data_uri = MediaFileType(
+ f"data:{mime_type};base64," f"{base64.b64encode(file_content).decode()}"
+ )
+
+ # Store and get appropriate output format
+ file_result = await store_media_file(
+ file=data_uri,
+ execution_context=execution_context,
+ return_format="for_block_output",
+ )
+
+ yield "file", file_result
+ yield "status", "File downloaded"
+ except Exception as e:
+ raise ValueError(f"Failed to download file: {e}") from e
+
+ async def _download_file(
+ self,
+ credentials: APIKeyCredentials,
+ file_id: str,
+ ) -> bytes:
+ return await download_telegram_file(credentials, file_id)
+
+
+class DeleteTelegramMessageBlock(Block):
+ """Delete a message from a Telegram chat."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(description="The chat ID containing the message")
+ message_id: int = SchemaField(description="The ID of the message to delete")
+
+ class Output(BlockSchemaOutput):
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="bb4fd91a-883e-4d29-9879-b06c4bb79d30",
+ description="Delete a message from a Telegram chat. "
+ "Bots can delete their own messages and incoming messages "
+ "in private chats at any time.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=DeleteTelegramMessageBlock.Input,
+ output_schema=DeleteTelegramMessageBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "message_id": 42,
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("status", "Message deleted"),
+ ],
+ test_mock={"_delete_message": lambda *args, **kwargs: True},
+ )
+
+ async def run(
+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs
+ ) -> BlockOutput:
+ try:
+ await self._delete_message(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ message_id=input_data.message_id,
+ )
+ yield "status", "Message deleted"
+ except Exception as e:
+ raise ValueError(f"Failed to delete message: {e}") from e
+
+ async def _delete_message(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ message_id: int,
+ ) -> bool:
+ await call_telegram_api(
+ credentials,
+ "deleteMessage",
+ {"chat_id": chat_id, "message_id": message_id},
+ )
+ return True
+
+
+class EditTelegramMessageBlock(Block):
+ """Edit the text of an existing message."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(description="The chat ID containing the message")
+ message_id: int = SchemaField(description="The ID of the message to edit")
+ text: str = SchemaField(
+ description="New text for the message (max 4096 characters)"
+ )
+ parse_mode: ParseMode = SchemaField(
+ description="Message formatting mode",
+ default=ParseMode.NONE,
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ message_id: int = SchemaField(description="The ID of the edited message")
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="c55816a2-37af-4901-ba19-36edcf2acfc1",
+ description="Edit the text of an existing message sent by the bot.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=EditTelegramMessageBlock.Input,
+ output_schema=EditTelegramMessageBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "message_id": 42,
+ "text": "Updated text!",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("message_id", 42),
+ ("status", "Message edited"),
+ ],
+ test_mock={
+ "_edit_message": lambda *args, **kwargs: TelegramMessageResult(
+ message_id=42
+ )
+ },
+ )
+
+ async def run(
+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs
+ ) -> BlockOutput:
+ try:
+ result = await self._edit_message(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ message_id=input_data.message_id,
+ text=input_data.text,
+ parse_mode=input_data.parse_mode.value,
+ )
+ yield "message_id", result.message_id
+ yield "status", "Message edited"
+ except Exception as e:
+ raise ValueError(f"Failed to edit message: {e}") from e
+
+ async def _edit_message(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ message_id: int,
+ text: str,
+ parse_mode: str,
+ ) -> TelegramMessageResult:
+ data: dict[str, Any] = {
+ "chat_id": chat_id,
+ "message_id": message_id,
+ "text": text,
+ }
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+
+ return await call_telegram_api(credentials, "editMessageText", data)
+
+
+class SendTelegramAudioBlock(Block):
+ """Send an audio file to a Telegram chat, displayed in the music player."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(description="The chat ID to send the audio to")
+ audio: MediaFileType = SchemaField(
+ description="Audio file to send (MP3 or M4A format). "
+ "Can be URL, data URI, or workspace:// reference."
+ )
+ caption: str = SchemaField(
+ description="Caption for the audio file",
+ default="",
+ advanced=True,
+ )
+ title: str = SchemaField(
+ description="Track title",
+ default="",
+ advanced=True,
+ )
+ performer: str = SchemaField(
+ description="Track performer/artist",
+ default="",
+ advanced=True,
+ )
+ duration: Optional[int] = SchemaField(
+ description="Duration in seconds",
+ default=None,
+ advanced=True,
+ )
+ reply_to_message_id: Optional[int] = SchemaField(
+ description="Message ID to reply to",
+ default=None,
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ message_id: int = SchemaField(description="The ID of the sent message")
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="9044829a-7915-4ab4-a50f-89922ba3679f",
+ description="Send an audio file to a Telegram chat. "
+ "The file is displayed in the music player. "
+ "For voice messages, use the Send Voice block instead.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=SendTelegramAudioBlock.Input,
+ output_schema=SendTelegramAudioBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "audio": "https://example.com/track.mp3",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("message_id", 123),
+ ("status", "Audio sent"),
+ ],
+ test_mock={
+ "_send_audio_url": lambda *args, **kwargs: TelegramMessageResult(
+ message_id=123
+ )
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: APIKeyCredentials,
+ execution_context: ExecutionContext,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ audio_input = input_data.audio
+
+ if audio_input.startswith(("http://", "https://")):
+ result = await self._send_audio_url(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ audio_url=audio_input,
+ caption=input_data.caption,
+ title=input_data.title,
+ performer=input_data.performer,
+ duration=input_data.duration,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+ else:
+ relative_path = await store_media_file(
+ file=input_data.audio,
+ execution_context=execution_context,
+ return_format="for_local_processing",
+ )
+ if not execution_context.graph_exec_id:
+ raise ValueError("graph_exec_id is required")
+ abs_path = get_exec_file_path(
+ execution_context.graph_exec_id, relative_path
+ )
+ result = await self._send_audio_file(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ file_path=abs_path,
+ caption=input_data.caption,
+ title=input_data.title,
+ performer=input_data.performer,
+ duration=input_data.duration,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+
+ yield "message_id", result.message_id
+ yield "status", "Audio sent"
+ except Exception as e:
+ raise ValueError(f"Failed to send audio: {e}") from e
+
+ async def _send_audio_url(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ audio_url: str,
+ caption: str,
+ title: str,
+ performer: str,
+ duration: Optional[int],
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ data: dict[str, Any] = {
+ "chat_id": chat_id,
+ "audio": audio_url,
+ }
+ if caption:
+ data["caption"] = caption
+ if title:
+ data["title"] = title
+ if performer:
+ data["performer"] = performer
+ if duration:
+ data["duration"] = duration
+ if reply_to_message_id:
+ data["reply_to_message_id"] = reply_to_message_id
+
+ return await call_telegram_api(credentials, "sendAudio", data)
+
+ async def _send_audio_file(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ file_path: str,
+ caption: str,
+ title: str,
+ performer: str,
+ duration: Optional[int],
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ path = Path(file_path)
+ file_bytes = path.read_bytes()
+ data: dict[str, Any] = {"chat_id": str(chat_id)}
+ if caption:
+ data["caption"] = caption
+ if title:
+ data["title"] = title
+ if performer:
+ data["performer"] = performer
+ if duration:
+ data["duration"] = str(duration)
+ if reply_to_message_id:
+ data["reply_to_message_id"] = str(reply_to_message_id)
+
+ mime_type = mimetypes.guess_type(path.name)[0] or "audio/mpeg"
+ return await call_telegram_api_with_file(
+ credentials,
+ "sendAudio",
+ file_field="audio",
+ file_data=file_bytes,
+ filename=path.name,
+ content_type=mime_type,
+ data=data,
+ )
+
+
+class SendTelegramDocumentBlock(Block):
+ """Send a document to a Telegram chat."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(description="The chat ID to send the document to")
+ document: MediaFileType = SchemaField(
+ description="Document to send (any file type). "
+ "Can be URL, data URI, or workspace:// reference."
+ )
+ filename: str = SchemaField(
+ description="Filename shown to the recipient. "
+ "If empty, the original filename is used (may be a random ID "
+ "for uploaded files).",
+ default="",
+ )
+ caption: str = SchemaField(
+ description="Caption for the document",
+ default="",
+ advanced=True,
+ )
+ parse_mode: ParseMode = SchemaField(
+ description="Caption formatting mode",
+ default=ParseMode.NONE,
+ advanced=True,
+ )
+ reply_to_message_id: Optional[int] = SchemaField(
+ description="Message ID to reply to",
+ default=None,
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ message_id: int = SchemaField(description="The ID of the sent message")
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="554f4bad-4c99-48ba-9d1c-75840b71c5ad",
+ description="Send a document (any file type) to a Telegram chat.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=SendTelegramDocumentBlock.Input,
+ output_schema=SendTelegramDocumentBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "document": "https://example.com/file.pdf",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("message_id", 123),
+ ("status", "Document sent"),
+ ],
+ test_mock={
+ "_send_document_url": lambda *args, **kwargs: TelegramMessageResult(
+ message_id=123
+ )
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: APIKeyCredentials,
+ execution_context: ExecutionContext,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ doc_input = input_data.document
+
+ if doc_input.startswith(("http://", "https://")):
+ result = await self._send_document_url(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ document_url=doc_input,
+ caption=input_data.caption,
+ parse_mode=input_data.parse_mode.value,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+ else:
+ relative_path = await store_media_file(
+ file=input_data.document,
+ execution_context=execution_context,
+ return_format="for_local_processing",
+ )
+ if not execution_context.graph_exec_id:
+ raise ValueError("graph_exec_id is required")
+ abs_path = get_exec_file_path(
+ execution_context.graph_exec_id, relative_path
+ )
+ result = await self._send_document_file(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ file_path=abs_path,
+ display_filename=input_data.filename,
+ caption=input_data.caption,
+ parse_mode=input_data.parse_mode.value,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+
+ yield "message_id", result.message_id
+ yield "status", "Document sent"
+ except Exception as e:
+ raise ValueError(f"Failed to send document: {e}") from e
+
+ async def _send_document_url(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ document_url: str,
+ caption: str,
+ parse_mode: str,
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ data: dict[str, Any] = {
+ "chat_id": chat_id,
+ "document": document_url,
+ }
+ if caption:
+ data["caption"] = caption
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+ if reply_to_message_id:
+ data["reply_to_message_id"] = reply_to_message_id
+
+ return await call_telegram_api(credentials, "sendDocument", data)
+
+ async def _send_document_file(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ file_path: str,
+ display_filename: str,
+ caption: str,
+ parse_mode: str,
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ path = Path(file_path)
+ file_bytes = path.read_bytes()
+ data: dict[str, Any] = {"chat_id": str(chat_id)}
+ if caption:
+ data["caption"] = caption
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+ if reply_to_message_id:
+ data["reply_to_message_id"] = str(reply_to_message_id)
+
+ mime_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
+ return await call_telegram_api_with_file(
+ credentials,
+ "sendDocument",
+ file_field="document",
+ file_data=file_bytes,
+ filename=display_filename or path.name,
+ content_type=mime_type,
+ data=data,
+ )
+
+
+class SendTelegramVideoBlock(Block):
+ """Send a video to a Telegram chat."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ chat_id: int = SchemaField(description="The chat ID to send the video to")
+ video: MediaFileType = SchemaField(
+ description="Video to send (MP4 format). "
+ "Can be URL, data URI, or workspace:// reference."
+ )
+ caption: str = SchemaField(
+ description="Caption for the video",
+ default="",
+ advanced=True,
+ )
+ parse_mode: ParseMode = SchemaField(
+ description="Caption formatting mode",
+ default=ParseMode.NONE,
+ advanced=True,
+ )
+ duration: Optional[int] = SchemaField(
+ description="Duration in seconds",
+ default=None,
+ advanced=True,
+ )
+ reply_to_message_id: Optional[int] = SchemaField(
+ description="Message ID to reply to",
+ default=None,
+ advanced=True,
+ )
+
+ class Output(BlockSchemaOutput):
+ message_id: int = SchemaField(description="The ID of the sent message")
+ status: str = SchemaField(description="Status of the operation")
+
+ def __init__(self):
+ super().__init__(
+ id="cda075af-3f31-47b0-baa9-0050b3bd78bd",
+ description="Send a video to a Telegram chat.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=SendTelegramVideoBlock.Input,
+ output_schema=SendTelegramVideoBlock.Output,
+ test_input={
+ "chat_id": 12345678,
+ "video": "https://example.com/video.mp4",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("message_id", 123),
+ ("status", "Video sent"),
+ ],
+ test_mock={
+ "_send_video_url": lambda *args, **kwargs: TelegramMessageResult(
+ message_id=123
+ )
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: APIKeyCredentials,
+ execution_context: ExecutionContext,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ video_input = input_data.video
+
+ if video_input.startswith(("http://", "https://")):
+ result = await self._send_video_url(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ video_url=video_input,
+ caption=input_data.caption,
+ parse_mode=input_data.parse_mode.value,
+ duration=input_data.duration,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+ else:
+ relative_path = await store_media_file(
+ file=input_data.video,
+ execution_context=execution_context,
+ return_format="for_local_processing",
+ )
+ if not execution_context.graph_exec_id:
+ raise ValueError("graph_exec_id is required")
+ abs_path = get_exec_file_path(
+ execution_context.graph_exec_id, relative_path
+ )
+ result = await self._send_video_file(
+ credentials=credentials,
+ chat_id=input_data.chat_id,
+ file_path=abs_path,
+ caption=input_data.caption,
+ parse_mode=input_data.parse_mode.value,
+ duration=input_data.duration,
+ reply_to_message_id=input_data.reply_to_message_id,
+ )
+
+ yield "message_id", result.message_id
+ yield "status", "Video sent"
+ except Exception as e:
+ raise ValueError(f"Failed to send video: {e}") from e
+
+ async def _send_video_url(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ video_url: str,
+ caption: str,
+ parse_mode: str,
+ duration: Optional[int],
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ data: dict[str, Any] = {
+ "chat_id": chat_id,
+ "video": video_url,
+ }
+ if caption:
+ data["caption"] = caption
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+ if duration:
+ data["duration"] = duration
+ if reply_to_message_id:
+ data["reply_to_message_id"] = reply_to_message_id
+
+ return await call_telegram_api(credentials, "sendVideo", data)
+
+ async def _send_video_file(
+ self,
+ credentials: APIKeyCredentials,
+ chat_id: int,
+ file_path: str,
+ caption: str,
+ parse_mode: str,
+ duration: Optional[int],
+ reply_to_message_id: Optional[int],
+ ) -> TelegramMessageResult:
+ path = Path(file_path)
+ file_bytes = path.read_bytes()
+ data: dict[str, Any] = {"chat_id": str(chat_id)}
+ if caption:
+ data["caption"] = caption
+ if parse_mode and parse_mode != "none":
+ data["parse_mode"] = parse_mode
+ if duration:
+ data["duration"] = str(duration)
+ if reply_to_message_id:
+ data["reply_to_message_id"] = str(reply_to_message_id)
+
+ mime_type = mimetypes.guess_type(path.name)[0] or "video/mp4"
+ return await call_telegram_api_with_file(
+ credentials,
+ "sendVideo",
+ file_field="video",
+ file_data=file_bytes,
+ filename=path.name,
+ content_type=mime_type,
+ data=data,
+ )
diff --git a/autogpt_platform/backend/backend/blocks/telegram/triggers.py b/autogpt_platform/backend/backend/blocks/telegram/triggers.py
new file mode 100644
index 0000000000..398fd2f6bf
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/telegram/triggers.py
@@ -0,0 +1,377 @@
+"""
+Telegram trigger blocks for receiving messages via webhooks.
+"""
+
+import logging
+
+from pydantic import BaseModel
+
+from backend.blocks._base import (
+ Block,
+ BlockCategory,
+ BlockOutput,
+ BlockSchemaInput,
+ BlockSchemaOutput,
+ BlockWebhookConfig,
+)
+from backend.data.model import SchemaField
+from backend.integrations.providers import ProviderName
+from backend.integrations.webhooks.telegram import TelegramWebhookType
+
+from ._auth import (
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ TelegramCredentialsField,
+ TelegramCredentialsInput,
+)
+
+logger = logging.getLogger(__name__)
+
+
+# Example payload for testing
+EXAMPLE_MESSAGE_PAYLOAD = {
+ "update_id": 123456789,
+ "message": {
+ "message_id": 1,
+ "from": {
+ "id": 12345678,
+ "is_bot": False,
+ "first_name": "John",
+ "last_name": "Doe",
+ "username": "johndoe",
+ "language_code": "en",
+ },
+ "chat": {
+ "id": 12345678,
+ "first_name": "John",
+ "last_name": "Doe",
+ "username": "johndoe",
+ "type": "private",
+ },
+ "date": 1234567890,
+ "text": "Hello, bot!",
+ },
+}
+
+
+class TelegramTriggerBase:
+ """Base class for Telegram trigger blocks."""
+
+ class Input(BlockSchemaInput):
+ credentials: TelegramCredentialsInput = TelegramCredentialsField()
+ payload: dict = SchemaField(hidden=True, default_factory=dict)
+
+
+class TelegramMessageTriggerBlock(TelegramTriggerBase, Block):
+ """
+ Triggers when a message is received or edited in your Telegram bot.
+
+ Supports text, photos, voice messages, audio files, documents, and videos.
+ Connect the outputs to other blocks to process messages and send responses.
+ """
+
+ class Input(TelegramTriggerBase.Input):
+ class EventsFilter(BaseModel):
+ """Filter for message types to receive."""
+
+ text: bool = True
+ photo: bool = False
+ voice: bool = False
+ audio: bool = False
+ document: bool = False
+ video: bool = False
+ edited_message: bool = False
+
+ events: EventsFilter = SchemaField(
+ title="Message Types", description="Types of messages to receive"
+ )
+
+ class Output(BlockSchemaOutput):
+ payload: dict = SchemaField(
+ description="The complete webhook payload from Telegram"
+ )
+ chat_id: int = SchemaField(
+ description="The chat ID where the message was received. "
+ "Use this to send replies."
+ )
+ message_id: int = SchemaField(description="The unique message ID")
+ user_id: int = SchemaField(description="The user ID who sent the message")
+ username: str = SchemaField(description="Username of the sender (may be empty)")
+ first_name: str = SchemaField(description="First name of the sender")
+ event: str = SchemaField(
+ description="The message type (text, photo, voice, audio, etc.)"
+ )
+ text: str = SchemaField(
+ description="Text content of the message (for text messages)"
+ )
+ photo_file_id: str = SchemaField(
+ description="File ID of the photo (for photo messages). "
+ "Use GetTelegramFileBlock to download."
+ )
+ voice_file_id: str = SchemaField(
+ description="File ID of the voice message (for voice messages). "
+ "Use GetTelegramFileBlock to download."
+ )
+ audio_file_id: str = SchemaField(
+ description="File ID of the audio file (for audio messages). "
+ "Use GetTelegramFileBlock to download."
+ )
+ file_id: str = SchemaField(
+ description="File ID for document/video messages. "
+ "Use GetTelegramFileBlock to download."
+ )
+ file_name: str = SchemaField(
+ description="Original filename (for document/audio messages)"
+ )
+ caption: str = SchemaField(description="Caption for media messages")
+ is_edited: bool = SchemaField(
+ description="Whether this is an edit of a previously sent message"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="4435e4e0-df6e-4301-8f35-ad70b12fc9ec",
+ description="Triggers when a message is received or edited in your Telegram bot. "
+ "Supports text, photos, voice messages, audio files, documents, and videos.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=TelegramMessageTriggerBlock.Input,
+ output_schema=TelegramMessageTriggerBlock.Output,
+ webhook_config=BlockWebhookConfig(
+ provider=ProviderName.TELEGRAM,
+ webhook_type=TelegramWebhookType.BOT,
+ resource_format="bot",
+ event_filter_input="events",
+ event_format="message.{event}",
+ ),
+ test_input={
+ "events": {"text": True, "photo": True},
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "payload": EXAMPLE_MESSAGE_PAYLOAD,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("payload", EXAMPLE_MESSAGE_PAYLOAD),
+ ("chat_id", 12345678),
+ ("message_id", 1),
+ ("user_id", 12345678),
+ ("username", "johndoe"),
+ ("first_name", "John"),
+ ("is_edited", False),
+ ("event", "text"),
+ ("text", "Hello, bot!"),
+ ("photo_file_id", ""),
+ ("voice_file_id", ""),
+ ("audio_file_id", ""),
+ ("file_id", ""),
+ ("file_name", ""),
+ ("caption", ""),
+ ],
+ )
+
+ async def run(self, input_data: Input, **kwargs) -> BlockOutput:
+ payload = input_data.payload
+ is_edited = "edited_message" in payload
+ message = payload.get("message") or payload.get("edited_message", {})
+
+ # Extract common fields
+ chat = message.get("chat", {})
+ sender = message.get("from", {})
+
+ yield "payload", payload
+ yield "chat_id", chat.get("id", 0)
+ yield "message_id", message.get("message_id", 0)
+ yield "user_id", sender.get("id", 0)
+ yield "username", sender.get("username", "")
+ yield "first_name", sender.get("first_name", "")
+ yield "is_edited", is_edited
+
+ # For edited messages, yield event as "edited_message" and extract
+ # all content fields from the edited message body
+ if is_edited:
+ yield "event", "edited_message"
+ yield "text", message.get("text", "")
+ photos = message.get("photo", [])
+ yield "photo_file_id", photos[-1].get("file_id", "") if photos else ""
+ voice = message.get("voice", {})
+ yield "voice_file_id", voice.get("file_id", "")
+ audio = message.get("audio", {})
+ yield "audio_file_id", audio.get("file_id", "")
+ document = message.get("document", {})
+ video = message.get("video", {})
+ yield "file_id", (document.get("file_id", "") or video.get("file_id", ""))
+ yield "file_name", (
+ document.get("file_name", "") or audio.get("file_name", "")
+ )
+ yield "caption", message.get("caption", "")
+ # Determine message type and extract content
+ elif "text" in message:
+ yield "event", "text"
+ yield "text", message.get("text", "")
+ yield "photo_file_id", ""
+ yield "voice_file_id", ""
+ yield "audio_file_id", ""
+ yield "file_id", ""
+ yield "file_name", ""
+ yield "caption", ""
+ elif "photo" in message:
+ # Get the largest photo (last in array)
+ photos = message.get("photo", [])
+ photo_fid = photos[-1].get("file_id", "") if photos else ""
+ yield "event", "photo"
+ yield "text", ""
+ yield "photo_file_id", photo_fid
+ yield "voice_file_id", ""
+ yield "audio_file_id", ""
+ yield "file_id", ""
+ yield "file_name", ""
+ yield "caption", message.get("caption", "")
+ elif "voice" in message:
+ voice = message.get("voice", {})
+ yield "event", "voice"
+ yield "text", ""
+ yield "photo_file_id", ""
+ yield "voice_file_id", voice.get("file_id", "")
+ yield "audio_file_id", ""
+ yield "file_id", ""
+ yield "file_name", ""
+ yield "caption", message.get("caption", "")
+ elif "audio" in message:
+ audio = message.get("audio", {})
+ yield "event", "audio"
+ yield "text", ""
+ yield "photo_file_id", ""
+ yield "voice_file_id", ""
+ yield "audio_file_id", audio.get("file_id", "")
+ yield "file_id", ""
+ yield "file_name", audio.get("file_name", "")
+ yield "caption", message.get("caption", "")
+ elif "document" in message:
+ document = message.get("document", {})
+ yield "event", "document"
+ yield "text", ""
+ yield "photo_file_id", ""
+ yield "voice_file_id", ""
+ yield "audio_file_id", ""
+ yield "file_id", document.get("file_id", "")
+ yield "file_name", document.get("file_name", "")
+ yield "caption", message.get("caption", "")
+ elif "video" in message:
+ video = message.get("video", {})
+ yield "event", "video"
+ yield "text", ""
+ yield "photo_file_id", ""
+ yield "voice_file_id", ""
+ yield "audio_file_id", ""
+ yield "file_id", video.get("file_id", "")
+ yield "file_name", video.get("file_name", "")
+ yield "caption", message.get("caption", "")
+ else:
+ yield "event", "other"
+ yield "text", ""
+ yield "photo_file_id", ""
+ yield "voice_file_id", ""
+ yield "audio_file_id", ""
+ yield "file_id", ""
+ yield "file_name", ""
+ yield "caption", ""
+
+
+# Example payload for reaction trigger testing
+EXAMPLE_REACTION_PAYLOAD = {
+ "update_id": 123456790,
+ "message_reaction": {
+ "chat": {
+ "id": 12345678,
+ "first_name": "John",
+ "last_name": "Doe",
+ "username": "johndoe",
+ "type": "private",
+ },
+ "message_id": 42,
+ "user": {
+ "id": 12345678,
+ "is_bot": False,
+ "first_name": "John",
+ "username": "johndoe",
+ },
+ "date": 1234567890,
+ "new_reaction": [{"type": "emoji", "emoji": "πŸ‘"}],
+ "old_reaction": [],
+ },
+}
+
+
+class TelegramMessageReactionTriggerBlock(TelegramTriggerBase, Block):
+ """
+ Triggers when a reaction to a message is changed.
+
+ Works automatically in private chats. In group chats, the bot must be
+ an administrator to receive reaction updates.
+ """
+
+ class Input(TelegramTriggerBase.Input):
+ pass
+
+ class Output(BlockSchemaOutput):
+ payload: dict = SchemaField(
+ description="The complete webhook payload from Telegram"
+ )
+ chat_id: int = SchemaField(
+ description="The chat ID where the reaction occurred"
+ )
+ message_id: int = SchemaField(description="The message ID that was reacted to")
+ user_id: int = SchemaField(description="The user ID who changed the reaction")
+ username: str = SchemaField(description="Username of the user (may be empty)")
+ new_reactions: list = SchemaField(
+ description="List of new reactions on the message"
+ )
+ old_reactions: list = SchemaField(
+ description="List of previous reactions on the message"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="82525328-9368-4966-8f0c-cd78e80181fd",
+ description="Triggers when a reaction to a message is changed. "
+ "Works in private chats automatically. "
+ "In groups, the bot must be an administrator.",
+ categories={BlockCategory.SOCIAL},
+ input_schema=TelegramMessageReactionTriggerBlock.Input,
+ output_schema=TelegramMessageReactionTriggerBlock.Output,
+ webhook_config=BlockWebhookConfig(
+ provider=ProviderName.TELEGRAM,
+ webhook_type=TelegramWebhookType.BOT,
+ resource_format="bot",
+ event_filter_input="",
+ event_format="message_reaction",
+ ),
+ test_input={
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "payload": EXAMPLE_REACTION_PAYLOAD,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("payload", EXAMPLE_REACTION_PAYLOAD),
+ ("chat_id", 12345678),
+ ("message_id", 42),
+ ("user_id", 12345678),
+ ("username", "johndoe"),
+ ("new_reactions", [{"type": "emoji", "emoji": "πŸ‘"}]),
+ ("old_reactions", []),
+ ],
+ )
+
+ async def run(self, input_data: Input, **kwargs) -> BlockOutput:
+ payload = input_data.payload
+ reaction = payload.get("message_reaction", {})
+
+ chat = reaction.get("chat", {})
+ user = reaction.get("user", {})
+
+ yield "payload", payload
+ yield "chat_id", chat.get("id", 0)
+ yield "message_id", reaction.get("message_id", 0)
+ yield "user_id", user.get("id", 0)
+ yield "username", user.get("username", "")
+ yield "new_reactions", reaction.get("new_reaction", [])
+ yield "old_reactions", reaction.get("old_reaction", [])
diff --git a/autogpt_platform/backend/backend/data/integrations.py b/autogpt_platform/backend/backend/data/integrations.py
index a6f007ce99..1abdc650bf 100644
--- a/autogpt_platform/backend/backend/data/integrations.py
+++ b/autogpt_platform/backend/backend/data/integrations.py
@@ -184,7 +184,7 @@ async def find_webhook_by_credentials_and_props(
credentials_id: str,
webhook_type: str,
resource: str,
- events: list[str],
+ events: Optional[list[str]],
) -> Webhook | None:
webhook = await IntegrationWebhook.prisma().find_first(
where={
@@ -192,7 +192,7 @@ async def find_webhook_by_credentials_and_props(
"credentialsId": credentials_id,
"webhookType": webhook_type,
"resource": resource,
- "events": {"has_every": events},
+ **({"events": {"has_every": events}} if events else {}),
},
)
return Webhook.from_db(webhook) if webhook else None
diff --git a/autogpt_platform/backend/backend/integrations/providers.py b/autogpt_platform/backend/backend/integrations/providers.py
index a462cd787f..377e001cec 100644
--- a/autogpt_platform/backend/backend/integrations/providers.py
+++ b/autogpt_platform/backend/backend/integrations/providers.py
@@ -47,6 +47,7 @@ class ProviderName(str, Enum):
SLANT3D = "slant3d"
SMARTLEAD = "smartlead"
SMTP = "smtp"
+ TELEGRAM = "telegram"
TWITTER = "twitter"
TODOIST = "todoist"
UNREAL_SPEECH = "unreal_speech"
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/__init__.py b/autogpt_platform/backend/backend/integrations/webhooks/__init__.py
index 3b87855e41..4deb79b064 100644
--- a/autogpt_platform/backend/backend/integrations/webhooks/__init__.py
+++ b/autogpt_platform/backend/backend/integrations/webhooks/__init__.py
@@ -15,6 +15,7 @@ def load_webhook_managers() -> dict["ProviderName", type["BaseWebhooksManager"]]
from .compass import CompassWebhookManager
from .github import GithubWebhooksManager
from .slant3d import Slant3DWebhooksManager
+ from .telegram import TelegramWebhooksManager
webhook_managers.update(
{
@@ -23,6 +24,7 @@ def load_webhook_managers() -> dict["ProviderName", type["BaseWebhooksManager"]]
CompassWebhookManager,
GithubWebhooksManager,
Slant3DWebhooksManager,
+ TelegramWebhooksManager,
]
}
)
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/telegram.py b/autogpt_platform/backend/backend/integrations/webhooks/telegram.py
new file mode 100644
index 0000000000..91b665013d
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/webhooks/telegram.py
@@ -0,0 +1,242 @@
+"""
+Telegram Bot API Webhooks Manager.
+
+Handles webhook registration and validation for Telegram bots.
+"""
+
+import hmac
+import logging
+
+from fastapi import HTTPException, Request
+from strenum import StrEnum
+
+from backend.data import integrations
+from backend.data.model import APIKeyCredentials, Credentials
+from backend.integrations.providers import ProviderName
+from backend.util.exceptions import MissingConfigError
+from backend.util.request import Requests
+from backend.util.settings import Config
+
+from ._base import BaseWebhooksManager
+from .utils import webhook_ingress_url
+
+logger = logging.getLogger(__name__)
+
+
+class TelegramWebhookType(StrEnum):
+ BOT = "bot"
+
+
+class TelegramWebhooksManager(BaseWebhooksManager):
+ """
+ Manages Telegram bot webhooks.
+
+ Telegram webhooks are registered via the setWebhook API method.
+ Incoming requests are validated using the secret_token header.
+ """
+
+ PROVIDER_NAME = ProviderName.TELEGRAM
+ WebhookType = TelegramWebhookType
+
+ TELEGRAM_API_BASE = "https://api.telegram.org"
+
+ async def get_suitable_auto_webhook(
+ self,
+ user_id: str,
+ credentials: Credentials,
+ webhook_type: TelegramWebhookType,
+ resource: str,
+ events: list[str],
+ ) -> integrations.Webhook:
+ """
+ Telegram only supports one webhook per bot. Instead of creating a new
+ webhook object when events change (which causes the old one to be pruned
+ and deregistered β€” removing the ONLY webhook for the bot), we find the
+ existing webhook and update its events in place.
+ """
+ app_config = Config()
+ if not app_config.platform_base_url:
+ raise MissingConfigError(
+ "PLATFORM_BASE_URL must be set to use Webhook functionality"
+ )
+
+ # Exact match β€” no re-registration needed
+ if webhook := await integrations.find_webhook_by_credentials_and_props(
+ user_id=user_id,
+ credentials_id=credentials.id,
+ webhook_type=webhook_type,
+ resource=resource,
+ events=events,
+ ):
+ return webhook
+
+ # Find any existing webhook for the same bot, regardless of events
+ if existing := await integrations.find_webhook_by_credentials_and_props(
+ user_id=user_id,
+ credentials_id=credentials.id,
+ webhook_type=webhook_type,
+ resource=resource,
+ events=None, # Ignore events for this lookup
+ ):
+ # Re-register with Telegram using the same URL but new allowed_updates
+ ingress_url = webhook_ingress_url(self.PROVIDER_NAME, existing.id)
+ _, config = await self._register_webhook(
+ credentials,
+ webhook_type,
+ resource,
+ events,
+ ingress_url,
+ existing.secret,
+ )
+ return await integrations.update_webhook(
+ existing.id, events=events, config=config
+ )
+
+ # No existing webhook at all β€” create a new one
+ return await self._create_webhook(
+ user_id=user_id,
+ webhook_type=webhook_type,
+ events=events,
+ resource=resource,
+ credentials=credentials,
+ )
+
+ @classmethod
+ async def validate_payload(
+ cls,
+ webhook: integrations.Webhook,
+ request: Request,
+ credentials: Credentials | None,
+ ) -> tuple[dict, str]:
+ """
+ Validates incoming Telegram webhook request.
+
+ Telegram sends X-Telegram-Bot-Api-Secret-Token header when secret_token
+ was set in setWebhook call.
+
+ Returns:
+ tuple: (payload dict, event_type string)
+ """
+ # Verify secret token header
+ secret_header = request.headers.get("X-Telegram-Bot-Api-Secret-Token")
+ if not secret_header or not hmac.compare_digest(secret_header, webhook.secret):
+ raise HTTPException(
+ status_code=403,
+ detail="Invalid or missing X-Telegram-Bot-Api-Secret-Token",
+ )
+
+ payload = await request.json()
+
+ # Determine event type based on update content
+ if "message" in payload:
+ message = payload["message"]
+ if "text" in message:
+ event_type = "message.text"
+ elif "photo" in message:
+ event_type = "message.photo"
+ elif "voice" in message:
+ event_type = "message.voice"
+ elif "audio" in message:
+ event_type = "message.audio"
+ elif "document" in message:
+ event_type = "message.document"
+ elif "video" in message:
+ event_type = "message.video"
+ else:
+ logger.warning(
+ "Unknown Telegram webhook payload type; "
+ f"message.keys() = {message.keys()}"
+ )
+ event_type = "message.other"
+ elif "edited_message" in payload:
+ event_type = "message.edited_message"
+ elif "message_reaction" in payload:
+ event_type = "message_reaction"
+ else:
+ event_type = "unknown"
+
+ return payload, event_type
+
+ async def _register_webhook(
+ self,
+ credentials: Credentials,
+ webhook_type: TelegramWebhookType,
+ resource: str,
+ events: list[str],
+ ingress_url: str,
+ secret: str,
+ ) -> tuple[str, dict]:
+ """
+ Register webhook with Telegram using setWebhook API.
+
+ Args:
+ credentials: Bot token credentials
+ webhook_type: Type of webhook (always BOT for Telegram)
+ resource: Resource identifier (unused for Telegram, bots are global)
+ events: Events to subscribe to
+ ingress_url: URL to receive webhook payloads
+ secret: Secret token for request validation
+
+ Returns:
+ tuple: (provider_webhook_id, config dict)
+ """
+ if not isinstance(credentials, APIKeyCredentials):
+ raise ValueError("API key (bot token) is required for Telegram webhooks")
+
+ token = credentials.api_key.get_secret_value()
+ url = f"{self.TELEGRAM_API_BASE}/bot{token}/setWebhook"
+
+ # Map event filter to Telegram allowed_updates
+ if events:
+ telegram_updates: set[str] = set()
+ for event in events:
+ telegram_updates.add(event.split(".")[0])
+ # "message.edited_message" requires the "edited_message" update type
+ if "edited_message" in event:
+ telegram_updates.add("edited_message")
+ sorted_updates = sorted(telegram_updates)
+ else:
+ sorted_updates = ["message", "message_reaction"]
+
+ webhook_data = {
+ "url": ingress_url,
+ "secret_token": secret,
+ "allowed_updates": sorted_updates,
+ }
+
+ response = await Requests().post(url, json=webhook_data)
+ result = response.json()
+
+ if not result.get("ok"):
+ error_desc = result.get("description", "Unknown error")
+ raise ValueError(f"Failed to set Telegram webhook: {error_desc}")
+
+ # Telegram doesn't return a webhook ID, use empty string
+ config = {
+ "url": ingress_url,
+ "allowed_updates": webhook_data["allowed_updates"],
+ }
+
+ return "", config
+
+ async def _deregister_webhook(
+ self, webhook: integrations.Webhook, credentials: Credentials
+ ) -> None:
+ """
+ Deregister webhook by calling setWebhook with empty URL.
+
+ This removes the webhook from Telegram's servers.
+ """
+ if not isinstance(credentials, APIKeyCredentials):
+ raise ValueError("API key (bot token) is required for Telegram webhooks")
+
+ token = credentials.api_key.get_secret_value()
+ url = f"{self.TELEGRAM_API_BASE}/bot{token}/setWebhook"
+
+ # Setting empty URL removes the webhook
+ response = await Requests().post(url, json={"url": ""})
+ result = response.json()
+
+ if not result.get("ok"):
+ error_desc = result.get("description", "Unknown error")
+ logger.warning(f"Failed to deregister Telegram webhook: {error_desc}")
diff --git a/autogpt_platform/frontend/public/integrations/telegram.png b/autogpt_platform/frontend/public/integrations/telegram.png
new file mode 100644
index 0000000000..e2402f9e52
Binary files /dev/null and b/autogpt_platform/frontend/public/integrations/telegram.png differ
diff --git a/docs/integrations/README.md b/docs/integrations/README.md
index 00d4b0c73a..338d21cc11 100644
--- a/docs/integrations/README.md
+++ b/docs/integrations/README.md
@@ -305,10 +305,12 @@ Below is a comprehensive list of all available blocks, categorized by their prim
| [Create Reddit Post](block-integrations/misc.md#create-reddit-post) | Create a new post on a subreddit |
| [Delete Reddit Comment](block-integrations/misc.md#delete-reddit-comment) | Delete a Reddit comment that you own |
| [Delete Reddit Post](block-integrations/misc.md#delete-reddit-post) | Delete a Reddit post that you own |
+| [Delete Telegram Message](block-integrations/telegram/blocks.md#delete-telegram-message) | Delete a message from a Telegram chat |
| [Discord Channel Info](block-integrations/discord/bot_blocks.md#discord-channel-info) | Resolves Discord channel names to IDs and vice versa |
| [Discord Get Current User](block-integrations/discord/oauth_blocks.md#discord-get-current-user) | Gets information about the currently authenticated Discord user using OAuth2 credentials |
| [Discord User Info](block-integrations/discord/bot_blocks.md#discord-user-info) | Gets information about a Discord user by their ID |
| [Edit Reddit Post](block-integrations/misc.md#edit-reddit-post) | Edit the body text of an existing Reddit post that you own |
+| [Edit Telegram Message](block-integrations/telegram/blocks.md#edit-telegram-message) | Edit the text of an existing message sent by the bot |
| [Get Linkedin Profile](block-integrations/enrichlayer/linkedin.md#get-linkedin-profile) | Fetch LinkedIn profile data using Enrichlayer |
| [Get Linkedin Profile Picture](block-integrations/enrichlayer/linkedin.md#get-linkedin-profile-picture) | Get LinkedIn profile pictures using Enrichlayer |
| [Get Reddit Comment](block-integrations/misc.md#get-reddit-comment) | Get details about a specific Reddit comment by its ID |
@@ -321,6 +323,7 @@ Below is a comprehensive list of all available blocks, categorized by their prim
| [Get Subreddit Flairs](block-integrations/misc.md#get-subreddit-flairs) | Get available link flair options for a subreddit |
| [Get Subreddit Info](block-integrations/misc.md#get-subreddit-info) | Get information about a subreddit including subscriber count, description, and rules |
| [Get Subreddit Rules](block-integrations/misc.md#get-subreddit-rules) | Get the rules for a subreddit to ensure compliance before posting |
+| [Get Telegram File](block-integrations/telegram/blocks.md#get-telegram-file) | Download a file from Telegram using its file_id |
| [Get User Posts](block-integrations/misc.md#get-user-posts) | Fetch posts by a specific Reddit user |
| [Linkedin Person Lookup](block-integrations/enrichlayer/linkedin.md#linkedin-person-lookup) | Look up LinkedIn profiles by person information using Enrichlayer |
| [Linkedin Role Lookup](block-integrations/enrichlayer/linkedin.md#linkedin-role-lookup) | Look up LinkedIn profiles by role in a company using Enrichlayer |
@@ -343,12 +346,21 @@ Below is a comprehensive list of all available blocks, categorized by their prim
| [Reddit Get My Posts](block-integrations/misc.md#reddit-get-my-posts) | Fetch posts created by the authenticated Reddit user (you) |
| [Reply To Discord Message](block-integrations/discord/bot_blocks.md#reply-to-discord-message) | Replies to a specific Discord message |
| [Reply To Reddit Comment](block-integrations/misc.md#reply-to-reddit-comment) | Reply to a specific Reddit comment |
+| [Reply To Telegram Message](block-integrations/telegram/blocks.md#reply-to-telegram-message) | Reply to a specific message in a Telegram chat |
| [Search Reddit](block-integrations/misc.md#search-reddit) | Search Reddit for posts matching a query |
| [Send Discord DM](block-integrations/discord/bot_blocks.md#send-discord-dm) | Sends a direct message to a Discord user using their user ID |
| [Send Discord Embed](block-integrations/discord/bot_blocks.md#send-discord-embed) | Sends a rich embed message to a Discord channel |
| [Send Discord File](block-integrations/discord/bot_blocks.md#send-discord-file) | Sends a file attachment to a Discord channel |
| [Send Discord Message](block-integrations/discord/bot_blocks.md#send-discord-message) | Sends a message to a Discord channel using a bot token |
| [Send Reddit Message](block-integrations/misc.md#send-reddit-message) | Send a private message (DM) to a Reddit user |
+| [Send Telegram Audio](block-integrations/telegram/blocks.md#send-telegram-audio) | Send an audio file to a Telegram chat |
+| [Send Telegram Document](block-integrations/telegram/blocks.md#send-telegram-document) | Send a document (any file type) to a Telegram chat |
+| [Send Telegram Message](block-integrations/telegram/blocks.md#send-telegram-message) | Send a text message to a Telegram chat |
+| [Send Telegram Photo](block-integrations/telegram/blocks.md#send-telegram-photo) | Send a photo to a Telegram chat |
+| [Send Telegram Video](block-integrations/telegram/blocks.md#send-telegram-video) | Send a video to a Telegram chat |
+| [Send Telegram Voice](block-integrations/telegram/blocks.md#send-telegram-voice) | Send a voice message to a Telegram chat |
+| [Telegram Message Reaction Trigger](block-integrations/telegram/triggers.md#telegram-message-reaction-trigger) | Triggers when a reaction to a message is changed |
+| [Telegram Message Trigger](block-integrations/telegram/triggers.md#telegram-message-trigger) | Triggers when a message is received or edited in your Telegram bot |
| [Transcribe Youtube Video](block-integrations/misc.md#transcribe-youtube-video) | Transcribes a YouTube video using a proxy |
| [Twitter Add List Member](block-integrations/twitter/list_members.md#twitter-add-list-member) | This block adds a specified user to a Twitter List owned by the authenticated user |
| [Twitter Bookmark Tweet](block-integrations/twitter/bookmark.md#twitter-bookmark-tweet) | This block bookmarks a tweet on Twitter |
diff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.md
index 3ad4bf2c6d..bd73deccb5 100644
--- a/docs/integrations/SUMMARY.md
+++ b/docs/integrations/SUMMARY.md
@@ -103,6 +103,8 @@
* [Stagehand Blocks](block-integrations/stagehand/blocks.md)
* [System Library Operations](block-integrations/system/library_operations.md)
* [System Store Operations](block-integrations/system/store_operations.md)
+* [Telegram Blocks](block-integrations/telegram/blocks.md)
+* [Telegram Triggers](block-integrations/telegram/triggers.md)
* [Text](block-integrations/text.md)
* [Todoist Comments](block-integrations/todoist/comments.md)
* [Todoist Labels](block-integrations/todoist/labels.md)
diff --git a/docs/integrations/block-integrations/telegram/blocks.md b/docs/integrations/block-integrations/telegram/blocks.md
new file mode 100644
index 0000000000..50e44e10e2
--- /dev/null
+++ b/docs/integrations/block-integrations/telegram/blocks.md
@@ -0,0 +1,348 @@
+# Telegram Blocks
+<!-- MANUAL: file_description -->
+These blocks let your agent interact with Telegram through the Bot API. They cover sending text, photos, video, audio, voice messages, and documents, as well as replying to, editing, and deleting messages. Media blocks accept URLs (passed directly to Telegram for server-side fetch), data URIs, and `workspace://` references (resolved locally and uploaded via multipart form-data). All blocks require a Telegram Bot API token obtained from [@BotFather](https://t.me/BotFather).
+<!-- END MANUAL -->
+
+## Delete Telegram Message
+
+### What it is
+Delete a message from a Telegram chat. Bots can delete their own messages and incoming messages in private chats at any time.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `deleteMessage` method with the provided `chat_id` and `message_id`. On success, outputs a status confirmation. Note that bots can only delete their own messages in any chat, or incoming messages in private chats. In groups, deleting other users' messages requires admin privileges.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID containing the message | int | Yes |
+| message_id | The ID of the message to delete | int | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Automatically clean up expired notifications or temporary status messages sent by your bot. For example, after a user confirms an action, delete the original prompt message to keep the chat tidy.
+<!-- END MANUAL -->
+
+---
+
+## Edit Telegram Message
+
+### What it is
+Edit the text of an existing message sent by the bot.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `editMessageText` method with the target `chat_id`, `message_id`, and the new `text`. An optional `parse_mode` can be set to format the replacement text as Markdown or HTML. Only messages sent by the bot itself can be edited.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID containing the message | int | Yes |
+| message_id | The ID of the message to edit | int | Yes |
+| text | New text for the message (max 4096 characters) | str | Yes |
+| parse_mode | Message formatting mode | "none" \| "Markdown" \| "MarkdownV2" \| "HTML" | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| message_id | The ID of the edited message | int |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Update a "Processing..." status message with the final result once a long-running task completes, so the user sees progress in-place rather than receiving a separate follow-up message.
+<!-- END MANUAL -->
+
+---
+
+## Get Telegram File
+
+### What it is
+Download a file from Telegram using its file_id. Use this to process photos, voice messages, or documents received.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+First calls the `getFile` API method to resolve the `file_id` into a server-side file path, then downloads the raw bytes from Telegram's file server. The downloaded content is converted to a data URI and stored via the workspace file system, outputting a `workspace://` reference (or data URI) that other blocks can consume.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| file_id | The Telegram file_id to download. Get this from trigger outputs (photo_file_id, voice_file_id, etc.) | str | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| file | The downloaded file (workspace:// reference or data URI) | str (file) |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Download a photo sent by a user and pass it to an image recognition or OCR block for processing, then reply with the extracted information.
+<!-- END MANUAL -->
+
+---
+
+## Reply To Telegram Message
+
+### What it is
+Reply to a specific message in a Telegram chat.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `sendMessage` method with a `reply_to_message_id` parameter, which creates a new message visually linked to the original. The reply appears with a quoted preview of the original message in the chat. An optional `parse_mode` enables Markdown or HTML formatting.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID where the message is | int | Yes |
+| reply_to_message_id | The message ID to reply to | int | Yes |
+| text | The reply text | str | Yes |
+| parse_mode | Message formatting mode | "none" \| "Markdown" \| "MarkdownV2" \| "HTML" | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| message_id | The ID of the reply message | int |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+In a group chat, reply directly to a user's question with an AI-generated answer so that the response is clearly threaded to the original question, keeping the conversation organized.
+<!-- END MANUAL -->
+
+---
+
+## Send Telegram Audio
+
+### What it is
+Send an audio file to a Telegram chat. The file is displayed in the music player. For voice messages, use the Send Voice block instead.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `sendAudio` method. If the input is an HTTP(S) URL, it is passed directly to Telegram which fetches the file server-side. For data URIs or `workspace://` references, the file is resolved locally and uploaded via multipart form-data. Optional metadata like `title`, `performer`, and `duration` is included when provided.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID to send the audio to | int | Yes |
+| audio | Audio file to send (MP3 or M4A format). Can be URL, data URI, or workspace:// reference. | str (file) | Yes |
+| caption | Caption for the audio file | str | No |
+| title | Track title | str | No |
+| performer | Track performer/artist | str | No |
+| duration | Duration in seconds | int | No |
+| reply_to_message_id | Message ID to reply to | int | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| message_id | The ID of the sent message | int |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Send a text-to-speech audio file generated by an AI model back to the user as a playable track, complete with a title and caption describing what was generated.
+<!-- END MANUAL -->
+
+---
+
+## Send Telegram Document
+
+### What it is
+Send a document (any file type) to a Telegram chat.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `sendDocument` method. URLs are passed directly for server-side fetch; data URIs and `workspace://` references are resolved locally and uploaded via multipart form-data. A custom `filename` can be specified to control the display name shown to the recipient. The caption supports optional Markdown or HTML formatting via `parse_mode`.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID to send the document to | int | Yes |
+| document | Document to send (any file type). Can be URL, data URI, or workspace:// reference. | str (file) | Yes |
+| filename | Filename shown to the recipient. If empty, the original filename is used (may be a random ID for uploaded files). | str | No |
+| caption | Caption for the document | str | No |
+| parse_mode | Caption formatting mode | "none" \| "Markdown" \| "MarkdownV2" \| "HTML" | No |
+| reply_to_message_id | Message ID to reply to | int | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| message_id | The ID of the sent message | int |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Generate a PDF report from collected data and send it to the user as a downloadable file with a descriptive filename like `weekly-report.pdf`.
+<!-- END MANUAL -->
+
+---
+
+## Send Telegram Message
+
+### What it is
+Send a text message to a Telegram chat.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `sendMessage` method with the provided `chat_id` and `text`. Optional parameters include `parse_mode` (to render Markdown or HTML formatting), `reply_to_message_id` (to thread the message as a reply), and `disable_notification` (to send silently without triggering a sound on the recipient's device).
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID to send the message to. Get this from the trigger block's chat_id output. | int | Yes |
+| text | The text message to send (max 4096 characters) | str | Yes |
+| parse_mode | Message formatting mode (Markdown, HTML, or none) | "none" \| "Markdown" \| "MarkdownV2" \| "HTML" | No |
+| reply_to_message_id | Message ID to reply to | int | No |
+| disable_notification | Send message silently (no notification sound) | bool | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| message_id | The ID of the sent message | int |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Build a conversational bot that receives a user's question via the Message Trigger, processes it through an AI block, and sends the answer back using this block. Use `parse_mode` to format responses with bold headings or code blocks.
+<!-- END MANUAL -->
+
+---
+
+## Send Telegram Photo
+
+### What it is
+Send a photo to a Telegram chat.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `sendPhoto` method. If the input is an HTTP(S) URL, it is passed directly to Telegram which fetches the image server-side (preferred for speed and efficiency). For data URIs or `workspace://` references, the file is resolved to a local path, read as bytes, and uploaded via multipart form-data with the appropriate MIME type.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID to send the photo to | int | Yes |
+| photo | Photo to send (URL, data URI, or workspace:// reference). URLs are preferred as Telegram will fetch them directly. | str (file) | Yes |
+| caption | Caption for the photo (max 1024 characters) | str | No |
+| parse_mode | Caption formatting mode | "none" \| "Markdown" \| "MarkdownV2" \| "HTML" | No |
+| reply_to_message_id | Message ID to reply to | int | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| message_id | The ID of the sent message | int |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Send an AI-generated image (e.g., from DALL-E or Stable Diffusion) back to the user who requested it, with a caption describing the prompt used.
+<!-- END MANUAL -->
+
+---
+
+## Send Telegram Video
+
+### What it is
+Send a video to a Telegram chat.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `sendVideo` method. URLs are passed directly for server-side fetch; data URIs and `workspace://` references are resolved locally and uploaded via multipart form-data with MIME type detection. Optional `duration` metadata and `parse_mode` for the caption can be provided.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID to send the video to | int | Yes |
+| video | Video to send (MP4 format). Can be URL, data URI, or workspace:// reference. | str (file) | Yes |
+| caption | Caption for the video | str | No |
+| parse_mode | Caption formatting mode | "none" \| "Markdown" \| "MarkdownV2" \| "HTML" | No |
+| duration | Duration in seconds | int | No |
+| reply_to_message_id | Message ID to reply to | int | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| message_id | The ID of the sent message | int |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Send a tutorial or demo video clip in response to a user's help request, or deliver a dynamically generated video summary of data trends.
+<!-- END MANUAL -->
+
+---
+
+## Send Telegram Voice
+
+### What it is
+Send a voice message to a Telegram chat. Voice must be OGG format with OPUS codec.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+Calls the Telegram Bot API `sendVoice` method. URLs are passed directly for server-side fetch; data URIs and `workspace://` references are resolved locally and uploaded via multipart form-data. The file must be in OGG format encoded with the OPUS codec for Telegram to display it as a voice message (with a waveform). Other formats will not render correctly as voice messages.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| chat_id | The chat ID to send the voice message to | int | Yes |
+| voice | Voice message to send (OGG format with OPUS codec). Can be URL, data URI, or workspace:// reference. | str (file) | Yes |
+| caption | Caption for the voice message | str | No |
+| duration | Duration in seconds | int | No |
+| reply_to_message_id | Message ID to reply to | int | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| message_id | The ID of the sent message | int |
+| status | Status of the operation | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+Convert an AI-generated text response to speech using a TTS block and send it as a voice message, creating a voice-based conversational assistant.
+<!-- END MANUAL -->
+
+---
diff --git a/docs/integrations/block-integrations/telegram/triggers.md b/docs/integrations/block-integrations/telegram/triggers.md
new file mode 100644
index 0000000000..753a6fd2a3
--- /dev/null
+++ b/docs/integrations/block-integrations/telegram/triggers.md
@@ -0,0 +1,86 @@
+# Telegram Triggers
+<!-- MANUAL: file_description -->
+These trigger blocks let your agent receive incoming messages and reactions from Telegram in real time via webhooks. When a user sends a message or reacts to one, the trigger fires and outputs structured data (chat ID, user info, message content, file IDs) that downstream blocks can process.
+<!-- END MANUAL -->
+
+## Telegram Message Reaction Trigger
+
+### What it is
+Triggers when a reaction to a message is changed. Works in private chats automatically. In groups, the bot must be an administrator.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+This block uses the Telegram Bot API webhook system, subscribing to `message_reaction` updates. When a user adds, changes, or removes a reaction on a message in a chat with your bot, Telegram sends an update to the registered webhook URL. The block extracts the chat ID, message ID, reacting user's info, and both the old and new reaction lists. In private chats this works automatically; in group chats the bot must be an administrator to receive reaction updates.
+<!-- END MANUAL -->
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| payload | The complete webhook payload from Telegram | Dict[str, Any] |
+| chat_id | The chat ID where the reaction occurred | int |
+| message_id | The message ID that was reacted to | int |
+| user_id | The user ID who changed the reaction | int |
+| username | Username of the user (may be empty) | str |
+| new_reactions | List of new reactions on the message | List[Any] |
+| old_reactions | List of previous reactions on the message | List[Any] |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+**Sentiment tracking** β€” Monitor reactions on bot-posted announcements to gauge audience sentiment in real time.
+
+**Approval workflows** β€” Use a thumbs-up reaction as a lightweight approval signal to trigger downstream actions like deployments or task assignments.
+
+**Engagement analytics** β€” Aggregate reaction data across messages to identify which content resonates most with your audience.
+<!-- END MANUAL -->
+
+---
+
+## Telegram Message Trigger
+
+### What it is
+Triggers when a message is received or edited in your Telegram bot. Supports text, photos, voice messages, audio files, documents, and videos.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+This block registers a webhook with the Telegram Bot API that subscribes to `message` and `edited_message` updates. Incoming messages are routed by content type β€” text, photo, voice, audio, document, or video β€” based on the event filter you configure. When a matching message arrives, the block extracts common fields (chat ID, sender info, message ID) along with type-specific data such as the text content, file IDs for media, or captions. File IDs can be passed to the Get Telegram File block to download the actual media. If the "edited_message" event is enabled, the block also fires when a user edits a previously sent message, with the `is_edited` output set to `true`.
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| events | Types of messages to receive | Message Types | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the operation failed | str |
+| payload | The complete webhook payload from Telegram | Dict[str, Any] |
+| chat_id | The chat ID where the message was received. Use this to send replies. | int |
+| message_id | The unique message ID | int |
+| user_id | The user ID who sent the message | int |
+| username | Username of the sender (may be empty) | str |
+| first_name | First name of the sender | str |
+| event | The message type (text, photo, voice, audio, etc.) | str |
+| text | Text content of the message (for text messages) | str |
+| photo_file_id | File ID of the photo (for photo messages). Use GetTelegramFileBlock to download. | str |
+| voice_file_id | File ID of the voice message (for voice messages). Use GetTelegramFileBlock to download. | str |
+| audio_file_id | File ID of the audio file (for audio messages). Use GetTelegramFileBlock to download. | str |
+| file_id | File ID for document/video messages. Use GetTelegramFileBlock to download. | str |
+| file_name | Original filename (for document/audio messages) | str |
+| caption | Caption for media messages | str |
+| is_edited | Whether this is an edit of a previously sent message | bool |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+**Conversational AI bot** β€” Receive text messages from users and feed them into an AI agent that generates and sends replies.
+
+**Photo processing pipeline** β€” Trigger on incoming photos, download them with Get Telegram File, run image analysis or OCR, and reply with the results.
+
+**Voice message transcription** β€” Capture voice messages, download the audio file, pass it to a speech-to-text service, and send the transcript back to the user.
+<!-- END MANUAL -->
+
+---