Agent Zero AI framework
feat/fix(telegram): Frontend Input Persistence Fix & Webhook Backend Refactor
keyboardstafffc787ea2c488
diff --git a/plugins/_telegram_integration/api/webhook.py b/plugins/_telegram_integration/api/webhook.pynew file mode 100644index 000000000..be9c11f7c--- /dev/null+++ b/plugins/_telegram_integration/api/webhook.py@@ -0,0 +1,47 @@+from helpers.api import ApiHandler, Request, Response+from helpers.print_style import PrintStyle+++class TelegramWebhook(ApiHandler):+ """Receives Telegram webhook updates. No auth/CSRF — Telegram cannot send session cookies."""++ @classmethod+ def requires_auth(cls) -> bool:+ return False++ @classmethod+ def requires_csrf(cls) -> bool:+ return False++ @classmethod+ def get_methods(cls) -> list[str]:+ return ["POST"]++ async def process(self, input: dict, request: Request) -> dict | Response:+ from aiogram.types import Update++ from plugins._telegram_integration.helpers.bot_manager import get_bot, get_all_bots++ # Identify which bot this update is for+ bot_name = request.args.get("bot", "")+ if not bot_name:+ return Response("Missing ?bot= parameter", 400)++ instance = get_bot(bot_name)+ if not instance:+ return Response(f"Bot not found: {bot_name}", 404)++ # Verify webhook secret if configured+ secret_header = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")+ if instance.webhook_secret and secret_header != instance.webhook_secret:+ return Response("Invalid secret token", 403)++ # Parse and feed the update to aiogram+ try:+ update = Update.model_validate(input, context={"bot": instance.bot})+ await instance.dispatcher.feed_update(instance.bot, update)+ except Exception as e:+ PrintStyle.error(f"Telegram webhook ({bot_name}): {e}")+ return Response("Internal error", 500)++ return {"ok": True}diff --git a/plugins/_telegram_integration/default_config.yaml b/plugins/_telegram_integration/default_config.yamlindex 92458836a..c7915f20d 100644--- a/plugins/_telegram_integration/default_config.yaml+++ b/plugins/_telegram_integration/default_config.yaml@@ -4,7 +4,7 @@ bots: []# enabled: true# token: ""# mode: polling # polling or webhook-# webhook_url: "" # required if mode=webhook, e.g. https://yourdomain.com/telegram/my_bot+# webhook_url: "" # required if mode=webhook, your A0 base URL e.g. https://yourdomain.com (webhook path appended automatically)# 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)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.pyindex 3ff44c80c..a7eddb7a9 100644--- a/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py+++ b/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py@@ -52,8 +52,11 @@ class TelegramBotManager(Extension):continueif name in running:inst = running[name]- if inst.task and not inst.task.done():- continue # already running+ # Already running: polling (task alive) or webhook (active)+ if (inst.task and not inst.task.done()) or inst.webhook_active:+ continue+ # Instance exists but is dead — stop and recreate+ await stop_bot(name)try:# Create handler closures that capture bot_name and config@@ -97,21 +100,30 @@ class TelegramBotManager(Extension):# Wrapper functions for aiogram handlers+def _get_current_bot_cfg(bot_name: str) -> dict:+ """Fetch the latest bot config by name, so handlers always use fresh settings."""+ config = plugins.get_plugin_config(PLUGIN_NAME) or {}+ for b in config.get("bots", []):+ if b.get("name") == bot_name:+ return b+ return {}++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)+ await handle_start(message, bot_name, _get_current_bot_cfg(bot_name) or 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)+ await handle_clear(message, bot_name, _get_current_bot_cfg(bot_name) or 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)+ await handle_message(message, bot_name, _get_current_bot_cfg(bot_name) or 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)+ await handle_callback_query(query, bot_name, _get_current_bot_cfg(bot_name) or bot_cfg)diff --git a/plugins/_telegram_integration/helpers/bot_manager.py b/plugins/_telegram_integration/helpers/bot_manager.pyindex 4776510f9..580032c0b 100644--- a/plugins/_telegram_integration/helpers/bot_manager.py+++ b/plugins/_telegram_integration/helpers/bot_manager.py@@ -7,7 +7,6 @@ from aiogram.client.default import DefaultBotPropertiesfrom aiogram.enums import ParseMode, ChatTypefrom aiogram.filters import Command, CommandStartfrom aiogram.types import Message, CallbackQuery-from aiogram.webhook.aiohttp_server import SimpleRequestHandlerfrom helpers.errors import format_errorfrom helpers.print_style import PrintStyle@@ -21,7 +20,8 @@ class BotInstance:dispatcher: Dispatcherrouter: Routertask: asyncio.Task | None = None # polling task- webhook_app: object | None = None # aiohttp app for webhook mode+ webhook_active: bool = False # True when webhook mode is registered+ webhook_secret: str = "" # secret for webhook verificationbot_info: object | None = None # cached result of bot.get_me()# Bot registry (singleton, persists across module reloads)@@ -130,6 +130,12 @@ def _make_group_mention_filter(handler: Callable, bot: Bot):# Pollingasync def start_polling(instance: BotInstance) -> asyncio.Task:+ # Ensure any leftover webhook is removed before polling+ try:+ await instance.bot.delete_webhook()+ except Exception:+ pass+async def _poll():try:PrintStyle.info(f"Telegram ({instance.name}): starting polling")@@ -159,25 +165,18 @@ async def stop_polling(instance: BotInstance):# 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+async def setup_webhook(instance: BotInstance, webhook_url: str, secret: str = ""):+ """Register webhook with Telegram. Updates are received via the API handler."""+ full_url = f"{webhook_url.rstrip('/')}/api/plugins/_telegram_integration/webhook?bot={instance.name}"await instance.bot.set_webhook(- url=url,+ url=full_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+ instance.webhook_active = True+ instance.webhook_secret = secret+ PrintStyle.info(f"Telegram ({instance.name}): webhook active via {webhook_url.rstrip('/')}")async def remove_webhook(instance: BotInstance):@@ -185,6 +184,8 @@ async def remove_webhook(instance: BotInstance):await instance.bot.delete_webhook()except Exception as e:PrintStyle.error(f"Telegram ({instance.name}): remove webhook error: {format_error(e)}")+ instance.webhook_active = False+ instance.webhook_secret = ""# Cleanupdiff --git a/plugins/_telegram_integration/webui/config.html b/plugins/_telegram_integration/webui/config.htmlindex 24c0d17df..c9584bd87 100644--- a/plugins/_telegram_integration/webui/config.html+++ b/plugins/_telegram_integration/webui/config.html@@ -83,10 +83,10 @@<div class="field" x-show="bot.mode === 'webhook'"><div class="field-label"><div class="field-title">Webhook URL</div>- <div class="field-description">Public HTTPS URL for Telegram to send updates to</div>+ <div class="field-description">Your Agent Zero base URL (e.g. https://yourdomain.com). The webhook path is appended automatically</div></div><div class="field-control">- <input type="text" x-model="bot.webhook_url" placeholder="https://yourdomain.com/telegram/my_bot" />+ <input type="text" x-model="bot.webhook_url" placeholder="https://yourdomain.com" /></div></div>@@ -107,8 +107,8 @@</div><div class="field-control"><input type="text"- :value="$store.telegramConfig.whitelistText(bot)"- @input="$store.telegramConfig.setWhitelist(bot, $event.target.value)"+ x-effect="if (document.activeElement !== $el) $el.value = $store.telegramConfig.whitelistText(bot)"+ @change="$store.telegramConfig.setWhitelist(bot, $event.target.value)"placeholder="123456789, @username" /></div></div>@@ -134,8 +134,8 @@</div><div class="field-control"><input type="text"- :value="$store.telegramConfig.userProjectsText(bot)"- @input="$store.telegramConfig.setUserProjects(bot, $event.target.value)"+ x-effect="if (document.activeElement !== $el) $el.value = $store.telegramConfig.userProjectsText(bot)"+ @change="$store.telegramConfig.setUserProjects(bot, $event.target.value)"placeholder="123456=my_project, 789012=other_project" /></div></div>@@ -146,7 +146,8 @@<div class="field-description">Fallback project if user not in the mapping above</div></div><div class="field-control">- <select x-model="bot.default_project">+ <select x-effect="void $store.telegramConfig.projects; $nextTick(() => $el.value = bot.default_project)"+ @change="bot.default_project = $event.target.value"><option value="">No project</option><template x-for="proj in $store.telegramConfig.projects" :key="proj.name"><option :value="proj.name" x-text="proj.title || proj.name"></option>diff --git a/plugins/_telegram_integration/webui/telegram-config-store.js b/plugins/_telegram_integration/webui/telegram-config-store.jsindex b07ae0c17..5dd6c2c62 100644--- a/plugins/_telegram_integration/webui/telegram-config-store.js+++ b/plugins/_telegram_integration/webui/telegram-config-store.js@@ -81,8 +81,9 @@ export const store = createStore("telegramConfig", {.map((s) => s.trim()).filter((s) => s).forEach((item) => {- const [k, v] = item.split("=").map((p) => p.trim());- if (k && v) obj[k] = v;+ const parts = item.split("=").map((p) => p.trim());+ const k = parts[0];+ if (k) obj[k] = parts[1] || "";});bot.user_projects = obj;},