【问题标题】:How can I start FastApi and aiogram bot in one event loop?如何在一个事件循环中启动 FastApi 和 aiogram bot?
【发布时间】:2023-01-04 16:29:30
【问题描述】:
我有这样的代码:
app = FastAPI()
bot = Bot(token=config_data.BOT_TOKEN)
dp = Dispatcher(bot)
我通常以这种方式启动机器人:
executor.start_polling(dp)
并启动 FastApi 应用程序:
uvicorn.run(app)
如何在一个事件循环中启动它?
【问题讨论】:
标签:
python
python-asyncio
fastapi
aiogram
【解决方案1】:
使用webhook同时使用fastapi和aiogram
机器人.py文件
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}")
主.py文件
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()