First Webhook
This guide turns a normal aiogram bot into a webhook application.
1. Create the dispatcher
from aiogram import Dispatcher, Router
from aiogram.filters import CommandStart
from aiogram.types import Message
router = Router()
@router.message(CommandStart())
async def start(message: Message) -> None:
await message.answer("Webhook is alive")
dispatcher = Dispatcher()
dispatcher.include_router(router)
2. Choose a framework adapter
FastAPI
aiohttp
from contextlib import asynccontextmanager
from aiogram import Bot, Dispatcher
from fastapi import FastAPI
from aiogram_webhook import FastAPIAdapter, SingleBotEngine, WebhookConfig
from aiogram_webhook.route import Route
from aiogram_webhook.security import IPCheck, Security, StaticSecretToken
dispatcher = Dispatcher()
bot = Bot("BOT_TOKEN")
engine = SingleBotEngine(
dispatcher,
bot,
web=FastAPIAdapter(),
route=Route(base_url="https://example.com", path="/telegram/webhook"),
security=Security(IPCheck(), secret_token=StaticSecretToken("webhook-secret")),
webhook_config=WebhookConfig(drop_pending_updates=True),
)
@asynccontextmanager
async def lifespan(app: FastAPI):
await engine.set_webhook()
yield
app = FastAPI(lifespan=lifespan)
engine.register(app)
from aiohttp import web
from aiogram import Bot, Dispatcher
from aiogram_webhook import AiohttpAdapter, SingleBotEngine, WebhookConfig
from aiogram_webhook.route import Route
from aiogram_webhook.security import IPCheck, Security, StaticSecretToken
dispatcher = Dispatcher()
bot = Bot("BOT_TOKEN")
engine = SingleBotEngine(
dispatcher,
bot,
web=AiohttpAdapter(),
route=Route(base_url="https://example.com", path="/telegram/webhook"),
security=Security(IPCheck(), secret_token=StaticSecretToken("webhook-secret")),
webhook_config=WebhookConfig(drop_pending_updates=True),
)
async def set_webhook(app: web.Application) -> None:
await engine.set_webhook()
app = web.Application()
app.on_startup.append(set_webhook)
engine.register(app)
3. Expose a public HTTPS URL
Telegram must reach your app over HTTPS.
In development, use a tunnel or a public staging domain.
In production, put your app behind a reverse proxy or platform load balancer.
Warning
Keep base_url equal to the public URL Telegram can call.
Do not use localhost in Route(base_url=...) unless Telegram can really reach it.
4. Register the webhook
For one bot:
await engine.set_webhook()
For token-based multi-bot applications:
await engine.add_bot("123456:ABCDEF")
How do I know Telegram accepted it?
Telegram's setWebhook returns True through aiogram when the registration succeeds.
You can also inspect webhook state with await bot.get_webhook_info().
Previous
Next