Skip to content

Agent Zero AI framework

feat: Telegram plugin extensions

keyboardstaff88b5d97335ca
diff --git a/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py b/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py
new file mode 100644
index 000000000..3ff44c80c
--- /dev/null
+++ b/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py
@@ -0,0 +1,117 @@
+import asyncio
+from functools import partial
+from typing import Any
+
+from helpers.extension import Extension
+from helpers.errors import format_error
+from helpers.print_style import PrintStyle
+from helpers import plugins
+
+
+PLUGIN_NAME: str = "_telegram_integration"
+
+
+class TelegramBotManager(Extension):
+
+ async def execute(self, **kwargs: Any) -> None:
+ from plugins._telegram_integration.helpers.bot_manager import (
+ get_all_bots,
+ create_bot,
+ cache_bot_info,
+ start_polling,
+ setup_webhook,
+ stop_bot,
+ )
+ from plugins._telegram_integration.helpers.handler import (
+ handle_start,
+ handle_clear,
+ handle_message,
+ handle_callback_query,
+ cleanup_old_attachments,
+ )
+
+ cleanup_old_attachments()
+
+ config = plugins.get_plugin_config(PLUGIN_NAME) or {}
+ bots_cfg = config.get("bots", [])
+ enabled_names = {
+ b["name"] for b in bots_cfg if b.get("enabled") and b.get("name") and b.get("token")
+ }
+
+ running = get_all_bots()
+
+ # Stop bots that are no longer enabled
+ for name in list(running.keys()):
+ if name not in enabled_names:
+ await stop_bot(name)
+
+ # Start new bots
+ for bot_cfg in bots_cfg:
+ name = bot_cfg.get("name", "")
+ if not name or not bot_cfg.get("enabled") or not bot_cfg.get("token"):
+ continue
+ if name in running:
+ inst = running[name]
+ if inst.task and not inst.task.done():
+ continue # already running
+
+ try:
+ # Create handler closures that capture bot_name and config
+ _on_start = partial(_wrap_start, bot_name=name, bot_cfg=bot_cfg)
+ _on_clear = partial(_wrap_clear, bot_name=name, bot_cfg=bot_cfg)
+ _on_message = partial(_wrap_message, bot_name=name, bot_cfg=bot_cfg)
+ _on_callback = partial(_wrap_callback, bot_name=name, bot_cfg=bot_cfg)
+
+ instance = create_bot(
+ name=name,
+ token=bot_cfg["token"],
+ on_message=_on_message,
+ on_command_start=_on_start,
+ on_command_clear=_on_clear,
+ on_callback_query=_on_callback,
+ group_mode=bot_cfg.get("group_mode", "mention"),
+ )
+
+ await cache_bot_info(instance)
+
+ mode = bot_cfg.get("mode", "polling")
+ if mode == "webhook":
+ webhook_url = bot_cfg.get("webhook_url", "")
+ webhook_secret = bot_cfg.get("webhook_secret", "")
+ if webhook_url:
+ await setup_webhook(instance, webhook_url, webhook_secret)
+ else:
+ PrintStyle.error(
+ f"Telegram ({name}): webhook mode requires webhook_url"
+ )
+ continue
+ else:
+ await start_polling(instance)
+
+ PrintStyle.success(f"Telegram ({name}): bot started in {mode} mode")
+
+ except Exception as e:
+ PrintStyle.error(
+ f"Telegram ({name}): failed to start: {format_error(e)}"
+ )
+
+# Wrapper functions for aiogram handlers
+
+async def _wrap_start(message, bot_name: str, bot_cfg: dict):
+ from plugins._telegram_integration.helpers.handler import handle_start
+ await handle_start(message, bot_name, bot_cfg)
+
+
+async def _wrap_clear(message, bot_name: str, bot_cfg: dict):
+ from plugins._telegram_integration.helpers.handler import handle_clear
+ await handle_clear(message, bot_name, bot_cfg)
+
+
+async def _wrap_message(message, bot_name: str, bot_cfg: dict):
+ from plugins._telegram_integration.helpers.handler import handle_message
+ await handle_message(message, bot_name, bot_cfg)
+
+
+async def _wrap_callback(query, bot_name: str, bot_cfg: dict):
+ from plugins._telegram_integration.helpers.handler import handle_callback_query
+ await handle_callback_query(query, bot_name, bot_cfg)
diff --git a/plugins/_telegram_integration/extensions/python/process_chain_end/_55_telegram_reply.py b/plugins/_telegram_integration/extensions/python/process_chain_end/_55_telegram_reply.py
new file mode 100644
index 000000000..c7b2ff005
--- /dev/null
+++ b/plugins/_telegram_integration/extensions/python/process_chain_end/_55_telegram_reply.py
@@ -0,0 +1,86 @@
+from helpers.extension import Extension
+from helpers.print_style import PrintStyle
+from helpers.errors import format_error
+from agent import AgentContext, LoopData, UserMessage
+from plugins._telegram_integration.helpers.handler import CTX_TG_BOT, CTX_TG_ATTACHMENTS, CTX_TG_KEYBOARD
+
+MAX_SEND_RETRIES: int = 2
+CTX_SEND_FAILURES: str = "_telegram_send_failures"
+
+
+class TelegramAutoReply(Extension):
+
+ async def execute(self, loop_data: LoopData = LoopData(), **kwargs):
+ if not self.agent or self.agent.number != 0:
+ return
+
+ context = self.agent.context
+ if not context.data.get(CTX_TG_BOT):
+ return
+
+ response_text = _extract_last_response(context)
+ if not response_text:
+ return
+
+ attachments = context.data.pop(CTX_TG_ATTACHMENTS, [])
+ keyboard = context.data.pop(CTX_TG_KEYBOARD, None)
+
+ try:
+ await self._send_reply(context, response_text, attachments, keyboard)
+ except Exception as e:
+ PrintStyle.error(f"Telegram auto-reply error: {format_error(e)}")
+
+ async def _send_reply(
+ self,
+ context: AgentContext,
+ response_text: str,
+ attachments: list[str],
+ keyboard: list[list[dict]] | None,
+ ):
+ from plugins._telegram_integration.helpers.handler import send_telegram_reply
+
+ error = await send_telegram_reply(
+ context, response_text, attachments or None, keyboard,
+ )
+ if not error:
+ context.data[CTX_SEND_FAILURES] = 0
+ return
+
+ failures = context.data.get(CTX_SEND_FAILURES, 0) + 1
+ context.data[CTX_SEND_FAILURES] = failures
+ if failures <= MAX_SEND_RETRIES:
+ _notify_agent_of_failure(context, error, failures)
+ else:
+ PrintStyle.error(
+ f"Telegram send failed {failures} times, giving up: {error}"
+ )
+ context.log.log(
+ type="error",
+ heading="Telegram send failed (max retries reached)",
+ content=error,
+ )
+
+# Helpers
+
+def _extract_last_response(context: AgentContext) -> str:
+ with context.log._lock:
+ logs = list(context.log.logs)
+ if not logs:
+ return ""
+ for item in reversed(logs):
+ if item.type == "response":
+ return item.content or ""
+ return ""
+
+
+def _notify_agent_of_failure(
+ context: AgentContext, error: str, attempt: int,
+):
+ msg = context.agent0.read_prompt(
+ "fw.telegram.send_failed.md",
+ error=error,
+ attempt=str(attempt),
+ max_retries=str(MAX_SEND_RETRIES),
+ )
+ context.log.log(type="error", heading="Telegram send failed", content=error)
+ context.communicate(UserMessage(message="", system_message=[msg]))
diff --git a/plugins/_telegram_integration/extensions/python/system_prompt/_20_telegram_context.py b/plugins/_telegram_integration/extensions/python/system_prompt/_20_telegram_context.py
new file mode 100644
index 000000000..7d34e7a9c
--- /dev/null
+++ b/plugins/_telegram_integration/extensions/python/system_prompt/_20_telegram_context.py
@@ -0,0 +1,20 @@
+from helpers.extension import Extension
+from agent import LoopData
+from plugins._telegram_integration.helpers.handler import CTX_TG_BOT
+
+
+class TelegramContextPrompt(Extension):
+
+ async def execute(
+ self,
+ system_prompt: list[str] = [],
+ loop_data: LoopData = LoopData(),
+ **kwargs,
+ ):
+ if not self.agent:
+ return
+
+ if self.agent.context.data.get(CTX_TG_BOT):
+ system_prompt.append(
+ self.agent.read_prompt("fw.telegram.system_context_reply.md")
+ )
diff --git a/plugins/_telegram_integration/extensions/python/tool_execute_after/_50_telegram_response.py b/plugins/_telegram_integration/extensions/python/tool_execute_after/_50_telegram_response.py
new file mode 100644
index 000000000..fd91213d7
--- /dev/null
+++ b/plugins/_telegram_integration/extensions/python/tool_execute_after/_50_telegram_response.py
@@ -0,0 +1,63 @@
+from helpers.extension import Extension
+from helpers.print_style import PrintStyle
+from helpers.tool import Response
+from plugins._telegram_integration.helpers.handler import (
+ CTX_TG_BOT,
+ CTX_TG_ATTACHMENTS,
+ CTX_TG_KEYBOARD,
+)
+
+
+class TelegramResponseIntercept(Extension):
+
+ async def execute(
+ self, tool_name: str = "", response: Response | None = None, **kwargs,
+ ):
+ if tool_name != "response":
+ return
+ if not self.agent:
+ return
+ context = self.agent.context
+ if not context.data.get(CTX_TG_BOT):
+ return
+
+ tool = self.agent.loop_data.current_tool
+ if not tool:
+ return
+
+ # Capture attachments for later (process_chain_end) or inline send
+ attachments = tool.args.get("attachments", [])
+ if attachments:
+ context.data[CTX_TG_ATTACHMENTS] = attachments
+
+ # Capture inline keyboard if provided
+ keyboard = tool.args.get("keyboard", None)
+ if keyboard:
+ context.data[CTX_TG_KEYBOARD] = keyboard
+
+ # Check break_loop arg from agent
+ agent_break = tool.args.get("break_loop", True)
+ if agent_break is False and response:
+ await self._send_inline(context, tool, response)
+
+ async def _send_inline(self, context, tool, response: Response):
+ from plugins._telegram_integration.helpers.handler import send_telegram_reply
+
+ agent = self.agent
+ assert agent is not None
+
+ text = tool.args.get("text", tool.args.get("message", ""))
+ attachments = context.data.pop(CTX_TG_ATTACHMENTS, [])
+ keyboard = context.data.pop(CTX_TG_KEYBOARD, None)
+
+ error = await send_telegram_reply(context, text, attachments or None, keyboard)
+
+ if error:
+ result = agent.read_prompt("fw.telegram.update_error.md", error=error)
+ else:
+ result = agent.read_prompt("fw.telegram.update_ok.md")
+
+ # Override response: don't break loop, add result to history
+ response.break_loop = False
+ response.message = result
+ agent.hist_add_tool_result("response", result)