1

I have code like this:

app = FastAPI()
bot = Bot(token=config_data.BOT_TOKEN)
dp = Dispatcher(bot)

I usually start bot in this way: executor.start_polling(dp)

and start FastApi app: uvicorn.run(app)

How can I start it in one event loop?

Andrless
  • 11
  • 2

1 Answers1

0

use webhook to use fastapi and aiogram together

bot.py file

from aiogram import Dispatcher, Bot, types
TOKEN = "1945118170:AAH4ZVOXOgEC8F3wDCB-rZ81817fynT7INk"
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(commands="start")
async def start(message: types.Message):
    await message.answer(f"Salom, {message.from_user.full_name}")

main.py file

from fastapi import FastAPI
from aiogram import types, Dispatcher, Bot
from bot import dp, bot, TOKEN


app = FastAPI()
WEBHOOK_PATH = f"/bot/{TOKEN}"
WEBHOOK_URL = "https://7608e5642d7f.ngrok.io" + WEBHOOK_PATH


@app.on_event("startup")
async def on_startup():
    webhook_info = await bot.get_webhook_info()
    if webhook_info.url != WEBHOOK_URL:
        await bot.set_webhook(
            url=WEBHOOK_URL
        )


@app.post(WEBHOOK_PATH)
async def bot_webhook(update: dict):
    telegram_update = types.Update(**update)
    Dispatcher.set_current(dp)
    Bot.set_current(bot)
    await dp.process_update(telegram_update)


@app.on_event("shutdown")
async def on_shutdown():
    await bot.session.close()
Malikov
  • 1
  • 1
  • 2