Skip to content

Agent Zero AI framework

feat: add Telegram integration plugin - core backend

keyboardstaff83ffa27d139c
diff --git a/plugins/_telegram_integration/api/test_connection.py b/plugins/_telegram_integration/api/test_connection.py
new file mode 100644
index 000000000..271c734f5
--- /dev/null
+++ b/plugins/_telegram_integration/api/test_connection.py
@@ -0,0 +1,35 @@
+from helpers.api import ApiHandler, Request
+from helpers.errors import format_error
+
+
+class TestConnection(ApiHandler):
+
+ async def process(self, input: dict, request: Request) -> dict:
+ bot_cfg = input.get("bot", {})
+ token = bot_cfg.get("token", "")
+ results: list[dict] = []
+
+ if not token:
+ results.append({
+ "test": "Token",
+ "ok": False,
+ "message": "No bot token provided",
+ })
+ return {"success": False, "results": results}
+
+ try:
+ from plugins._telegram_integration.helpers.bot_manager import test_token
+ ok, message = await test_token(token)
+ results.append({
+ "test": "Bot Token",
+ "ok": ok,
+ "message": message,
+ })
+ except Exception as e:
+ results.append({
+ "test": "Bot Token",
+ "ok": False,
+ "message": format_error(e),
+ })
+
+ return {"success": all(r["ok"] for r in results), "results": results}
diff --git a/plugins/_telegram_integration/default_config.yaml b/plugins/_telegram_integration/default_config.yaml
new file mode 100644
index 000000000..92458836a
--- /dev/null
+++ b/plugins/_telegram_integration/default_config.yaml
@@ -0,0 +1,15 @@
+bots: []
+# Example bot:
+# - name: my_bot
+# enabled: true
+# token: ""
+# mode: polling # polling or webhook
+# webhook_url: "" # required if mode=webhook, e.g. https://yourdomain.com/telegram/my_bot
+# webhook_secret: "" # optional shared secret for webhook verification
+# allowed_users: [] # Telegram user IDs or @usernames. Empty = allow all.
+# group_mode: mention # mention (respond when @mentioned or replied to) | all (respond to every message) | off (ignore groups)
+# user_projects: {} # Map Telegram user_id to project name, e.g. { "123456": "my_project" }
+# default_project: "" # Fallback project if user not in user_projects
+# attachment_max_age_hours: 0 # Hours to keep downloaded attachments. 0 = keep forever.
+# agent_instructions: "" # Extra instructions for the agent in Telegram chats
+
diff --git a/plugins/_telegram_integration/helpers/__init__.py b/plugins/_telegram_integration/helpers/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/plugins/_telegram_integration/helpers/bot_manager.py b/plugins/_telegram_integration/helpers/bot_manager.py
new file mode 100644
index 000000000..1f3d1277d
--- /dev/null
+++ b/plugins/_telegram_integration/helpers/bot_manager.py
@@ -0,0 +1,221 @@
+import asyncio
+from dataclasses import dataclass, field
+from typing import Callable, Awaitable
+
+from aiogram import Bot, Dispatcher, Router, F
+from aiogram.client.default import DefaultBotProperties
+from aiogram.enums import ParseMode, ChatType
+from aiogram.exceptions import TelegramBadRequest
+from aiogram.filters import Command, CommandStart
+from aiogram.types import Message, CallbackQuery, Update
+from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
+
+from helpers.errors import format_error
+from helpers.print_style import PrintStyle
+
+# Data models
+
+@dataclass
+class BotInstance:
+ name: str
+ bot: Bot
+ dispatcher: Dispatcher
+ router: Router
+ task: asyncio.Task | None = None # polling task
+ webhook_app: object | None = None # aiohttp app for webhook mode
+ bot_info: object | None = None # cached result of bot.get_me()
+
+# Bot registry (singleton, persists across module reloads)
+
+_bots: dict[str, BotInstance] = {}
+
+
+def get_bot(name: str) -> BotInstance | None:
+ return _bots.get(name)
+
+
+def get_all_bots() -> dict[str, BotInstance]:
+ return _bots
+
+# Bot creation
+
+def create_bot(
+ name: str,
+ token: str,
+ on_message: Callable[..., Awaitable],
+ on_command_start: Callable[..., Awaitable],
+ on_command_clear: Callable[..., Awaitable],
+ on_callback_query: Callable[..., Awaitable] | None = None,
+ group_mode: str = "mention",
+) -> BotInstance:
+ bot = Bot(token=token, default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN))
+ dp = Dispatcher()
+ router = Router()
+
+ # Register command handlers
+ router.message.register(on_command_start, CommandStart())
+ router.message.register(on_command_clear, Command("clear"))
+
+ if on_callback_query:
+ router.callback_query.register(on_callback_query)
+
+ # Register message handler with group filtering
+ if group_mode == "off":
+ # Private chats only
+ router.message.register(
+ on_message, F.chat.type == ChatType.PRIVATE,
+ )
+ elif group_mode == "mention":
+ # Private chats: all messages; Groups: only when mentioned/replied
+ router.message.register(
+ on_message, F.chat.type == ChatType.PRIVATE,
+ )
+ router.message.register(
+ _make_group_mention_filter(on_message, bot),
+ )
+ else:
+ # All messages in all chats
+ router.message.register(on_message)
+
+ dp.include_router(router)
+ instance = BotInstance(name=name, bot=bot, dispatcher=dp, router=router)
+ _bots[name] = instance
+ return instance
+
+
+async def cache_bot_info(instance: BotInstance):
+ """Fetch and cache bot info. Call after create_bot."""
+ if not instance.bot_info:
+ instance.bot_info = await instance.bot.get_me()
+ return instance.bot_info
+
+
+def _make_group_mention_filter(handler: Callable, bot: Bot):
+ """Create a group message handler that only responds to mentions and replies."""
+ async def _group_handler(message: Message):
+ if message.chat.type == ChatType.PRIVATE:
+ return
+ # Use cached bot_info from the instance
+ inst = get_bot(handler.__name__.split('_')[-1]) if hasattr(handler, '__name__') else None
+ bot_info = None
+ for b in _bots.values():
+ if b.bot is bot:
+ bot_info = b.bot_info
+ break
+ if not bot_info:
+ bot_info = await bot.get_me()
+ bot_username = bot_info.username or ""
+
+ # Check for reply to bot
+ if message.reply_to_message and message.reply_to_message.from_user:
+ if message.reply_to_message.from_user.id == bot_info.id:
+ await handler(message)
+ return
+
+ # Check for @mention in text
+ if message.text and f"@{bot_username}" in message.text:
+ await handler(message)
+ return
+
+ # Check entities for mention
+ if message.entities:
+ for entity in message.entities:
+ if entity.type == "mention":
+ mention_text = message.text[entity.offset:entity.offset + entity.length]
+ if mention_text.lower() == f"@{bot_username.lower()}":
+ await handler(message)
+ return
+
+ _group_handler.__name__ = f"_group_handler_{id(handler)}"
+ return _group_handler
+
+# Polling
+
+async def start_polling(instance: BotInstance) -> asyncio.Task:
+ async def _poll():
+ try:
+ PrintStyle.info(f"Telegram ({instance.name}): starting polling")
+ await instance.dispatcher.start_polling(
+ instance.bot,
+ handle_signals=False,
+ )
+ except asyncio.CancelledError:
+ PrintStyle.info(f"Telegram ({instance.name}): polling cancelled")
+ except Exception as e:
+ PrintStyle.error(f"Telegram ({instance.name}): polling error: {format_error(e)}")
+
+ task = asyncio.create_task(_poll())
+ instance.task = task
+ return task
+
+
+async def stop_polling(instance: BotInstance):
+ if instance.task and not instance.task.done():
+ await instance.dispatcher.stop_polling()
+ instance.task.cancel()
+ try:
+ await instance.task
+ except asyncio.CancelledError:
+ pass
+ instance.task = None
+
+# Webhook
+
+async def setup_webhook(instance: BotInstance, url: str, secret: str = ""):
+ """Set Telegram webhook and return aiohttp app for local serving."""
+ from aiohttp import web
+
+ await instance.bot.set_webhook(
+ url=url,
+ secret_token=secret or None,
+ )
+
+ app = web.Application()
+ handler = SimpleRequestHandler(
+ dispatcher=instance.dispatcher,
+ bot=instance.bot,
+ secret_token=secret or None,
+ )
+ handler.register(app, path=f"/telegram/{instance.name}")
+ instance.webhook_app = app
+ PrintStyle.info(f"Telegram ({instance.name}): webhook set to {url}")
+ return app
+
+
+async def remove_webhook(instance: BotInstance):
+ try:
+ await instance.bot.delete_webhook()
+ except Exception as e:
+ PrintStyle.error(f"Telegram ({instance.name}): remove webhook error: {format_error(e)}")
+
+# Cleanup
+
+async def stop_bot(name: str):
+ instance = _bots.pop(name, None)
+ if not instance:
+ return
+ if instance.task and not instance.task.done():
+ await stop_polling(instance)
+ else:
+ await remove_webhook(instance)
+ try:
+ await instance.bot.session.close()
+ except Exception:
+ pass
+ PrintStyle.info(f"Telegram ({name}): stopped")
+
+
+async def stop_all_bots():
+ for name in list(_bots.keys()):
+ await stop_bot(name)
+
+# Test connection
+
+async def test_token(token: str) -> tuple[bool, str]:
+ try:
+ bot = Bot(token=token)
+ info = await bot.get_me()
+ await bot.session.close()
+ return True, f"Connected as @{info.username} ({info.first_name})"
+ except Exception as e:
+ return False, format_error(e)
diff --git a/plugins/_telegram_integration/helpers/handler.py b/plugins/_telegram_integration/helpers/handler.py
new file mode 100644
index 000000000..917c5065d
--- /dev/null
+++ b/plugins/_telegram_integration/helpers/handler.py
@@ -0,0 +1,517 @@
+import json
+import os
+import threading
+import time
+import uuid
+
+from aiogram.types import Message as TgMessage, CallbackQuery
+
+from agent import Agent, AgentContext, AgentContextType, UserMessage
+from helpers import guids, plugins, files
+from helpers import message_queue as mq
+from helpers.notification import NotificationManager, NotificationType, NotificationPriority
+from helpers.persist_chat import save_tmp_chat
+from helpers.print_style import PrintStyle
+from helpers.errors import format_error
+from initialize import initialize_agent
+
+from plugins._telegram_integration.helpers import telegram_client as tc
+from plugins._telegram_integration.helpers.bot_manager import get_bot
+
+
+PLUGIN_NAME = "_telegram_integration"
+DOWNLOAD_FOLDER = "usr/telegram/attachments"
+STATE_FILE = "usr/telegram/state.json"
+
+# Context data keys
+CTX_TG_BOT = "telegram_bot"
+CTX_TG_CHAT_ID = "telegram_chat_id"
+CTX_TG_USER_ID = "telegram_user_id"
+CTX_TG_USERNAME = "telegram_username"
+CTX_TG_LAST_MSG_ID = "telegram_last_msg_id"
+
+# Transient
+CTX_TG_ATTACHMENTS = "_telegram_response_attachments"
+CTX_TG_KEYBOARD = "_telegram_response_keyboard"
+
+# Chat mapping: (bot_name, tg_user_id) → AgentContext ID
+
+_chat_map_lock = threading.Lock()
+
+
+def _load_state() -> dict:
+ path = files.get_abs_path(STATE_FILE)
+ if os.path.isfile(path):
+ try:
+ return json.loads(files.read_file(path))
+ except Exception:
+ return {}
+ return {}
+
+
+def _save_state(state: dict):
+ path = files.get_abs_path(STATE_FILE)
+ files.make_dirs(path)
+ files.write_file(path, json.dumps(state))
+
+
+def _map_key(bot_name: str, user_id: int) -> str:
+ return f"{bot_name}:{user_id}"
+
+
+def cleanup_old_attachments():
+ """Remove downloaded attachment files older than per-bot max age. 0 = keep forever."""
+ config = plugins.get_plugin_config(PLUGIN_NAME) or {}
+ bots_cfg = config.get("bots") or []
+ total_removed = 0
+ for bot_cfg in bots_cfg:
+ bot_name = bot_cfg.get("name", "")
+ if not bot_name:
+ continue
+ max_age_hours = bot_cfg.get("attachment_max_age_hours", 0)
+ if not max_age_hours or max_age_hours <= 0:
+ continue
+ folder = os.path.join(files.get_abs_path(DOWNLOAD_FOLDER), bot_name)
+ if not os.path.isdir(folder):
+ continue
+ cutoff = time.time() - max_age_hours * 3600
+ for name in os.listdir(folder):
+ path = os.path.join(folder, name)
+ try:
+ if os.path.isfile(path) and os.path.getmtime(path) < cutoff:
+ os.remove(path)
+ total_removed += 1
+ except OSError:
+ pass
+ if total_removed:
+ PrintStyle.info(f"Telegram: cleaned up {total_removed} old attachment(s)")
+
+# Access control
+
+def _is_allowed(bot_cfg: dict, user_id: int, username: str | None) -> bool:
+ allowed = bot_cfg.get("allowed_users") or []
+ if not allowed:
+ return True # empty = allow all
+ for entry in allowed:
+ entry_str = str(entry).strip()
+ if entry_str.startswith("@"):
+ if username and f"@{username}" == entry_str:
+ return True
+ else:
+ try:
+ if int(entry_str) == user_id:
+ return True
+ except ValueError:
+ if username and entry_str.lower() == username.lower():
+ return True
+ return False
+
+
+def _get_project(bot_cfg: dict, user_id: int) -> str:
+ user_projects = bot_cfg.get("user_projects") or {}
+ project = user_projects.get(str(user_id), "")
+ if not project:
+ project = bot_cfg.get("default_project", "")
+ return project
+
+# Message handlers (registered with aiogram by bot_manager)
+
+async def handle_start(message: TgMessage, bot_name: str, bot_cfg: dict):
+ """Handle /start command."""
+ user = message.from_user
+ if not user:
+ return
+
+ if not _is_allowed(bot_cfg, user.id, user.username):
+ await message.reply("⛔ You are not authorized to use this bot.")
+ return
+
+ instance = get_bot(bot_name)
+ if not instance:
+ return
+
+ await message.reply(
+ f"👋 Hello {user.first_name}! I'm connected to Agent Zero.\n\n"
+ "Send me a message and I'll process it.\n"
+ "Use /clear to reset the conversation."
+ )
+
+ # Ensure a chat context exists
+ await _get_or_create_context(bot_name, bot_cfg, message)
+
+
+async def handle_clear(message: TgMessage, bot_name: str, bot_cfg: dict):
+ """Handle /clear command — reset user's chat context."""
+ user = message.from_user
+ if not user:
+ return
+
+ if not _is_allowed(bot_cfg, user.id, user.username):
+ return
+
+ key = _map_key(bot_name, user.id)
+
+ with _chat_map_lock:
+ state = _load_state()
+ ctx_id = state.get("chats", {}).get(key)
+ if ctx_id:
+ ctx = AgentContext.get(ctx_id)
+ if ctx:
+ ctx.reset()
+ PrintStyle.info(f"Telegram ({bot_name}): cleared chat for user {user.id}")
+
+ instance = get_bot(bot_name)
+ if instance:
+ await tc.send_text(
+ instance.bot, message.chat.id,
+ "🗑 Chat cleared. Send a new message to start fresh.",
+ parse_mode=None,
+ )
+
+ # Send notification
+ username_str = f"@{user.username}" if user.username else str(user.id)
+ NotificationManager.send_notification(
+ type=NotificationType.INFO,
+ priority=NotificationPriority.NORMAL,
+ title="Telegram: chat cleared",
+ message=f"{username_str} cleared their chat via /clear",
+ display_time=5,
+ group="telegram",
+ )
+
+
+async def handle_message(message: TgMessage, bot_name: str, bot_cfg: dict):
+ """Handle incoming user message."""
+ user = message.from_user
+ if not user:
+ return
+
+ if not _is_allowed(bot_cfg, user.id, user.username):
+ return
+
+ instance = get_bot(bot_name)
+ if not instance:
+ return
+
+ # Send typing indicator
+ await tc.send_typing(instance.bot, message.chat.id)
+
+ # Get or create agent context
+ context = await _get_or_create_context(bot_name, bot_cfg, message)
+ if not context:
+ await tc.send_text(
+ instance.bot, message.chat.id,
+ "❌ Failed to create chat session.",
+ parse_mode=None,
+ )
+ return
+
+ # Build user message text
+ text = _extract_message_content(message)
+ attachments = await _download_attachments(instance.bot, message, bot_name=bot_name)
+
+ # Store last incoming message ID for reply threading
+ context.data[CTX_TG_LAST_MSG_ID] = message.message_id
+
+ # Build user message with prompt
+ agent = context.agent0
+ user_msg = agent.read_prompt(
+ "fw.telegram.user_message.md",
+ sender=_format_user(user),
+ body=text,
+ )
+
+ instructions = bot_cfg.get("agent_instructions", "")
+ if instructions:
+ user_msg += agent.read_prompt(
+ "fw.telegram.user_message_instructions.md",
+ instructions=instructions,
+ )
+
+ system_ctx = agent.read_prompt("fw.telegram.system_context.md")
+
+ mq.log_user_message(context, user_msg, attachments, source=" (telegram)")
+ context.communicate(UserMessage(
+ message=user_msg,
+ system_message=[system_ctx],
+ attachments=attachments,
+ ))
+
+ save_tmp_chat(context)
+
+ # Send notification
+ username_str = f"@{user.username}" if user.username else str(user.id)
+ preview = (text[:80] + "...") if len(text) > 80 else text
+ NotificationManager.send_notification(
+ type=NotificationType.INFO,
+ priority=NotificationPriority.HIGH,
+ title="Telegram: new message",
+ message=f"From {username_str}: {preview}",
+ display_time=10,
+ group="telegram",
+ )
+
+
+async def handle_callback_query(query: CallbackQuery, bot_name: str, bot_cfg: dict):
+ """Handle inline keyboard button press."""
+ user = query.from_user
+ if not user or not query.message:
+ return
+
+ if not _is_allowed(bot_cfg, user.id, user.username):
+ await query.answer("Not authorized.")
+ return
+
+ await query.answer()
+
+ # Treat callback data as a user message
+ text = query.data or ""
+ if not text:
+ return
+
+ context = await _get_or_create_context_from_user(
+ bot_name, bot_cfg, user.id, user.username, query.message.chat.id,
+ )
+ if not context:
+ return
+
+ agent = context.agent0
+ user_msg = agent.read_prompt(
+ "fw.telegram.user_message.md",
+ sender=_format_user(user),
+ body=f"[Button pressed: {text}]",
+ )
+
+ mq.log_user_message(context, user_msg, [], source=" (telegram)")
+ context.communicate(UserMessage(message=user_msg))
+ save_tmp_chat(context)
+
+# Context management
+
+async def _get_or_create_context(
+ bot_name: str,
+ bot_cfg: dict,
+ message: TgMessage,
+) -> AgentContext | None:
+ user = message.from_user
+ if not user:
+ return None
+ return await _get_or_create_context_from_user(
+ bot_name, bot_cfg, user.id, user.username, message.chat.id,
+ )
+
+
+async def _get_or_create_context_from_user(
+ bot_name: str,
+ bot_cfg: dict,
+ user_id: int,
+ username: str | None,
+ chat_id: int,
+) -> AgentContext | None:
+ key = _map_key(bot_name, user_id)
+
+ with _chat_map_lock:
+ state = _load_state()
+ chats = state.setdefault("chats", {})
+ ctx_id = chats.get(key)
+
+ # Check if existing context is still alive
+ if ctx_id:
+ ctx = AgentContext.get(ctx_id)
+ if ctx:
+ return ctx
+ # Context was garbage collected, remove stale mapping
+ chats.pop(key, None)
+
+ # Create new context
+ try:
+ config = initialize_agent()
+ display_name = f"@{username}" if username else str(user_id)
+ ctx = AgentContext(config, name=f"Telegram: {display_name}")
+
+ ctx.data[CTX_TG_BOT] = bot_name
+ ctx.data[CTX_TG_CHAT_ID] = chat_id
+ ctx.data[CTX_TG_USER_ID] = user_id
+ ctx.data[CTX_TG_USERNAME] = username or ""
+
+ project = _get_project(bot_cfg, user_id)
+ if project:
+ from helpers import projects
+ projects.activate_project(ctx.id, project)
+
+ chats[key] = ctx.id
+ _save_state(state)
+
+ PrintStyle.success(
+ f"Telegram ({bot_name}): new chat {ctx.id} for user {display_name}"
+ )
+ return ctx
+
+ except Exception as e:
+ PrintStyle.error(f"Telegram: failed to create context: {format_error(e)}")
+ return None
+
+# Message content extraction
+
+def _extract_message_content(message: TgMessage) -> str:
+ parts = []
+
+ if message.text:
+ parts.append(message.text)
+ elif message.caption:
+ parts.append(message.caption)
+
+ if message.location:
+ parts.append(f"[Location: {message.location.latitude}, {message.location.longitude}]")
+
+ if message.contact:
+ parts.append(
+ f"[Contact: {message.contact.first_name} "
+ f"{message.contact.last_name or ''} "
+ f"phone={message.contact.phone_number}]"
+ )
+
+ if message.sticker:
+ emoji = message.sticker.emoji or ""
+ parts.append(f"[Sticker: {emoji}]")
+
+ if message.voice:
+ parts.append("[Voice message — see attachment]")
+
+ if message.video_note:
+ parts.append("[Video note — see attachment]")
+
+ return "\n".join(parts) if parts else "[No text content]"
+
+
+async def _download_attachments(bot, message: TgMessage, bot_name: str = "") -> list[str]:
+ """Download photos, documents, audio, voice, video from message."""
+ paths: list[str] = []
+ sub = bot_name if bot_name else "_default"
+ download_base = os.path.join(files.get_abs_path(DOWNLOAD_FOLDER), sub)
+ os.makedirs(download_base, exist_ok=True)
+
+ async def _dl(file_id: str, filename: str) -> str | None:
+ dest = os.path.join(download_base, f"{uuid.uuid4().hex[:8]}_{filename}")
+ return await tc.download_file(bot, file_id, dest)
+
+ # Photo: get largest resolution
+ if message.photo:
+ photo = message.photo[-1]
+ path = await _dl(photo.file_id, f"photo_{photo.file_unique_id}.jpg")
+ if path:
+ paths.append(path)
+
+ # Document
+ if message.document:
+ fname = message.document.file_name or f"file_{message.document.file_unique_id}"
+ path = await _dl(message.document.file_id, fname)
+ if path:
+ paths.append(path)
+
+ # Audio
+ if message.audio:
+ fname = message.audio.file_name or f"audio_{message.audio.file_unique_id}.mp3"
+ path = await _dl(message.audio.file_id, fname)
+ if path:
+ paths.append(path)
+
+ # Voice
+ if message.voice:
+ path = await _dl(message.voice.file_id, f"voice_{message.voice.file_unique_id}.ogg")
+ if path:
+ paths.append(path)
+
+ # Video
+ if message.video:
+ fname = message.video.file_name or f"video_{message.video.file_unique_id}.mp4"
+ path = await _dl(message.video.file_id, fname)
+ if path:
+ paths.append(path)
+
+ # Video note
+ if message.video_note:
+ path = await _dl(
+ message.video_note.file_id,
+ f"videonote_{message.video_note.file_unique_id}.mp4",
+ )
+ if path:
+ paths.append(path)
+
+ return paths
+
+# Reply sending (called from process_chain_end extension)
+
+async def send_telegram_reply(
+ context: AgentContext,
+ response_text: str,
+ attachments: list[str] | None = None,
+ keyboard: list[list[dict]] | None = None,
+) -> str | None:
+ """Send reply to Telegram user. Returns error string or None on success."""
+ from aiogram import Bot
+ from aiogram.client.default import DefaultBotProperties
+ from aiogram.enums import ParseMode
+
+ bot_name = context.data.get(CTX_TG_BOT)
+ if not bot_name:
+ return "No Telegram bot configured on context"
+
+ instance = get_bot(bot_name)
+ if not instance:
+ return f"Bot '{bot_name}' not running"
+
+ chat_id = context.data.get(CTX_TG_CHAT_ID)
+ if not chat_id:
+ return "No chat_id on context"
+
+ # Create a temporary Bot bound to the current event loop to avoid
+ # cross-event-loop issues with the shared instance's aiohttp session.
+ reply_bot = Bot(
+ token=instance.bot.token,
+ default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN),
+ )
+ try:
+ # Send attachments first
+ if attachments:
+ for path in attachments:
+ if tc.is_image_file(path):
+ await tc.send_photo(reply_bot, chat_id, path)
+ else:
+ await tc.send_file(reply_bot, chat_id, path)
+
+ # Send text (with or without keyboard)
+ if response_text:
+ if keyboard:
+ await tc.send_text_with_keyboard(
+ reply_bot, chat_id, response_text, keyboard,
+ )
+ else:
+ await tc.send_text(reply_bot, chat_id, response_text)
+
+ return None
+
+ except Exception as e:
+ error = format_error(e)
+ PrintStyle.error(f"Telegram reply failed: {error}")
+ return error
+ finally:
+ await reply_bot.session.close()
+
+# Helpers
+
+def _format_user(user) -> str:
+ name = user.first_name or ""
+ if user.last_name:
+ name += f" {user.last_name}"
+ if user.username:
+ name += f" (@{user.username})"
+ return name.strip() or str(user.id)
+
+
+def find_context_for_bot_chat(bot_name: str, chat_id: int) -> AgentContext | None:
+ """Find active context matching a Telegram bot + chat_id."""
+ for ctx in AgentContext.all():
+ if ctx.data.get(CTX_TG_BOT) == bot_name and ctx.data.get(CTX_TG_CHAT_ID) == chat_id:
+ return ctx
+ return None
diff --git a/plugins/_telegram_integration/helpers/telegram_client.py b/plugins/_telegram_integration/helpers/telegram_client.py
new file mode 100644
index 000000000..35054f73a
--- /dev/null
+++ b/plugins/_telegram_integration/helpers/telegram_client.py
@@ -0,0 +1,226 @@
+import asyncio
+import os
+from typing import BinaryIO
+
+from aiogram import Bot
+from aiogram.exceptions import TelegramBadRequest
+from aiogram.types import (
+ BufferedInputFile,
+ FSInputFile,
+ InlineKeyboardButton,
+ InlineKeyboardMarkup,
+)
+
+from helpers.errors import format_error
+from helpers.print_style import PrintStyle
+
+# Text messages
+
+MAX_MESSAGE_LENGTH: int = 4096 # Telegram message length limit
+
+
+async def send_text(
+ bot: Bot,
+ chat_id: int,
+ text: str,
+ reply_to_message_id: int | None = None,
+ parse_mode: str | None = None,
+) -> int | None:
+ """Send text message, splitting if too long. Returns last message_id or None on error."""
+ try:
+ chunks = _split_text(text, MAX_MESSAGE_LENGTH)
+ last_msg_id = None
+ for chunk in chunks:
+ try:
+ msg = await bot.send_message(
+ chat_id=chat_id,
+ text=chunk,
+ reply_to_message_id=reply_to_message_id,
+ parse_mode=parse_mode,
+ )
+ last_msg_id = msg.message_id
+ except TelegramBadRequest:
+ # Retry without markdown if parse fails
+ msg = await bot.send_message(
+ chat_id=chat_id,
+ text=chunk,
+ reply_to_message_id=reply_to_message_id,
+ parse_mode=None,
+ )
+ last_msg_id = msg.message_id
+ return last_msg_id
+ except Exception as e:
+ PrintStyle.error(f"Telegram send_text failed: {format_error(e)}")
+ return None
+
+# Files and images
+
+async def send_file(
+ bot: Bot,
+ chat_id: int,
+ file_path: str,
+ caption: str = "",
+ reply_to_message_id: int | None = None,
+) -> int | None:
+ """Send a file from local path. Returns message_id or None on error."""
+ try:
+ if not os.path.isfile(file_path):
+ PrintStyle.error(f"Telegram: file not found: {file_path}")
+ return None
+ input_file = FSInputFile(file_path)
+ msg = await bot.send_document(
+ chat_id=chat_id,
+ document=input_file,
+ caption=caption[:1024] if caption else None,
+ reply_to_message_id=reply_to_message_id,
+ )
+ return msg.message_id
+ except Exception as e:
+ PrintStyle.error(f"Telegram send_file failed: {format_error(e)}")
+ return None
+
+
+async def send_photo(
+ bot: Bot,
+ chat_id: int,
+ photo_path: str,
+ caption: str = "",
+ reply_to_message_id: int | None = None,
+) -> int | None:
+ """Send a photo from local path. Returns message_id or None on error."""
+ try:
+ if not os.path.isfile(photo_path):
+ PrintStyle.error(f"Telegram: photo not found: {photo_path}")
+ return None
+ input_file = FSInputFile(photo_path)
+ msg = await bot.send_photo(
+ chat_id=chat_id,
+ photo=input_file,
+ caption=caption[:1024] if caption else None,
+ reply_to_message_id=reply_to_message_id,
+ )
+ return msg.message_id
+ except Exception as e:
+ PrintStyle.error(f"Telegram send_photo failed: {format_error(e)}")
+ return None
+
+
+async def send_file_bytes(
+ bot: Bot,
+ chat_id: int,
+ content: bytes,
+ filename: str,
+ caption: str = "",
+) -> int | None:
+ """Send file from bytes content."""
+ try:
+ input_file = BufferedInputFile(content, filename=filename)
+ msg = await bot.send_document(
+ chat_id=chat_id,
+ document=input_file,
+ caption=caption[:1024] if caption else None,
+ )
+ return msg.message_id
+ except Exception as e:
+ PrintStyle.error(f"Telegram send_file_bytes failed: {format_error(e)}")
+ return None
+
+# Inline keyboards
+
+def build_inline_keyboard(
+ buttons: list[list[dict]],
+) -> InlineKeyboardMarkup:
+ """Build inline keyboard from a list of rows.
+ Each row is a list of dicts with keys: text, callback_data or url.
+ """
+ rows = []
+ for row in buttons:
+ row_buttons = []
+ for btn in row:
+ if "url" in btn:
+ row_buttons.append(InlineKeyboardButton(
+ text=btn["text"], url=btn["url"],
+ ))
+ else:
+ row_buttons.append(InlineKeyboardButton(
+ text=btn["text"],
+ callback_data=btn.get("callback_data", btn["text"]),
+ ))
+ rows.append(row_buttons)
+ return InlineKeyboardMarkup(inline_keyboard=rows)
+
+
+async def send_text_with_keyboard(
+ bot: Bot,
+ chat_id: int,
+ text: str,
+ buttons: list[list[dict]],
+ reply_to_message_id: int | None = None,
+) -> int | None:
+ """Send text with inline keyboard buttons."""
+ try:
+ keyboard = build_inline_keyboard(buttons)
+ msg = await bot.send_message(
+ chat_id=chat_id,
+ text=text,
+ reply_markup=keyboard,
+ reply_to_message_id=reply_to_message_id,
+ )
+ return msg.message_id
+ except Exception as e:
+ PrintStyle.error(f"Telegram send_text_with_keyboard failed: {format_error(e)}")
+ return None
+
+# Typing indicator
+
+async def send_typing(bot: Bot, chat_id: int):
+ """Send 'typing...' action to chat."""
+ try:
+ await bot.send_chat_action(chat_id=chat_id, action="typing")
+ except Exception:
+ pass
+
+# File download
+
+async def download_file(
+ bot: Bot,
+ file_id: str,
+ destination: str,
+) -> str | None:
+ """Download a file by file_id to destination path. Returns path or None on error."""
+ try:
+ file = await bot.get_file(file_id)
+ if not file.file_path:
+ return None
+ os.makedirs(os.path.dirname(destination), exist_ok=True)
+ await bot.download_file(file.file_path, destination)
+ return destination
+ except Exception as e:
+ PrintStyle.error(f"Telegram download failed: {format_error(e)}")
+ return None
+
+# Helpers
+
+def _split_text(text: str, max_len: int) -> list[str]:
+ if len(text) <= max_len:
+ return [text]
+ chunks = []
+ while text:
+ if len(text) <= max_len:
+ chunks.append(text)
+ break
+ # Try to split at newline
+ split_at = text.rfind("\n", 0, max_len)
+ if split_at < max_len // 2:
+ split_at = max_len
+ chunks.append(text[:split_at])
+ text = text[split_at:].lstrip("\n")
+ return chunks
+
+
+_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
+
+
+def is_image_file(path: str) -> bool:
+ _, ext = os.path.splitext(path.lower())
+ return ext in _IMAGE_EXTENSIONS
diff --git a/plugins/_telegram_integration/plugin.yaml b/plugins/_telegram_integration/plugin.yaml
new file mode 100644
index 000000000..72bbf76a5
--- /dev/null
+++ b/plugins/_telegram_integration/plugin.yaml
@@ -0,0 +1,8 @@
+name: _telegram_integration
+title: Telegram Integration
+description: Communicate with Agent Zero via Telegram. Supports polling and webhook modes with per-user chat sessions.
+version: 1.0.0
+settings_sections:
+ - external
+per_project_config: false
+per_agent_config: false
diff --git a/plugins/_telegram_integration/prompts/fw.telegram.cleared.md b/plugins/_telegram_integration/prompts/fw.telegram.cleared.md
new file mode 100644
index 000000000..a0b41a3b3
--- /dev/null
+++ b/plugins/_telegram_integration/prompts/fw.telegram.cleared.md
@@ -0,0 +1,3 @@
+chat cleared by user via /clear command
+previous context has been reset
+greet user and wait for new input
\ No newline at end of file
diff --git a/plugins/_telegram_integration/prompts/fw.telegram.send_failed.md b/plugins/_telegram_integration/prompts/fw.telegram.send_failed.md
new file mode 100644
index 000000000..9a1809de3
--- /dev/null
+++ b/plugins/_telegram_integration/prompts/fw.telegram.send_failed.md
@@ -0,0 +1,4 @@
+telegram send failed (attempt {{attempt}}/{{max_retries}}): {{error}}
+previous response was NOT delivered to user
+retry without problematic content or inform user via alternative means
+if attachment caused the issue, retry without it
\ No newline at end of file
diff --git a/plugins/_telegram_integration/prompts/fw.telegram.system_context.md b/plugins/_telegram_integration/prompts/fw.telegram.system_context.md
new file mode 100644
index 000000000..f015b8ac7
--- /dev/null
+++ b/plugins/_telegram_integration/prompts/fw.telegram.system_context.md
@@ -0,0 +1,4 @@
+telegram session user communicates via Telegram
+response tool sends the message to the user dont use python code
+break_loop true > stop working and wait for user reply
+break_loop false > only for mid-task progress updates then keep working
\ No newline at end of file
diff --git a/plugins/_telegram_integration/prompts/fw.telegram.system_context_reply.md b/plugins/_telegram_integration/prompts/fw.telegram.system_context_reply.md
new file mode 100644
index 000000000..ac96eceb6
--- /dev/null
+++ b/plugins/_telegram_integration/prompts/fw.telegram.system_context_reply.md
@@ -0,0 +1,46 @@
+# Telegram session behavior
+user communicates via Telegram messenger
+response tool = send message to user on Telegram
+dont use code to send messages
+break_loop true > stop working and wait for user reply
+break_loop false > only for mid-task progress updates then keep working
+include file paths in attachments array to send files/images
+for multiple files zip first then attach single archive
+optionally set keyboard array for inline buttons
+
+usage:
+
+~~~json
+{
+ ...
+ "tool_name": "response",
+ "tool_args": {
+ "text": "working on it...",
+ "break_loop": false
+ }
+}
+~~~
+
+~~~json
+{
+ ...
+ "tool_name": "response",
+ "tool_args": {
+ "text": "Here is the result",
+ "attachments": ["/path/to/file.zip"],
+ "break_loop": true
+ }
+}
+~~~
+
+~~~json
+{
+ ...
+ "tool_name": "response",
+ "tool_args": {
+ "text": "Choose an option:",
+ "keyboard": [[{"text": "Option A", "callback_data": "a"}, {"text": "Option B", "callback_data": "b"}]],
+ "break_loop": true
+ }
+}
+~~~
\ No newline at end of file
diff --git a/plugins/_telegram_integration/prompts/fw.telegram.update_error.md b/plugins/_telegram_integration/prompts/fw.telegram.update_error.md
new file mode 100644
index 000000000..02b2554dc
--- /dev/null
+++ b/plugins/_telegram_integration/prompts/fw.telegram.update_error.md
@@ -0,0 +1 @@
+telegram update failed: {{error}}
\ No newline at end of file
diff --git a/plugins/_telegram_integration/prompts/fw.telegram.update_ok.md b/plugins/_telegram_integration/prompts/fw.telegram.update_ok.md
new file mode 100644
index 000000000..64c3e6b87
--- /dev/null
+++ b/plugins/_telegram_integration/prompts/fw.telegram.update_ok.md
@@ -0,0 +1 @@
+telegram update sent, continue working
\ No newline at end of file
diff --git a/plugins/_telegram_integration/prompts/fw.telegram.user_message.md b/plugins/_telegram_integration/prompts/fw.telegram.user_message.md
new file mode 100644
index 000000000..a05af6818
--- /dev/null
+++ b/plugins/_telegram_integration/prompts/fw.telegram.user_message.md
@@ -0,0 +1,3 @@
+[Telegram message from {{sender}}]
+
+{{body}}
\ No newline at end of file
diff --git a/plugins/_telegram_integration/prompts/fw.telegram.user_message_instructions.md b/plugins/_telegram_integration/prompts/fw.telegram.user_message_instructions.md
new file mode 100644
index 000000000..6b8835747
--- /dev/null
+++ b/plugins/_telegram_integration/prompts/fw.telegram.user_message_instructions.md
@@ -0,0 +1,2 @@
+
+[Handler instructions: {{instructions}}]
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index 189b6f4ba..10c0d78da 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -48,6 +48,7 @@ html2text>=2024.2.26
beautifulsoup4>=4.12.3
boto3>=1.35.0
exchangelib>=5.4.3
+aiogram>=3.15.0
pywinpty==3.0.2; sys_platform == "win32"
python-socketio>=5.14.2
uvicorn>=0.38.0