You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一个事件循环中启动FastAPI与aiogram机器人?

在同一事件循环中启动FastAPI与Telegram Bot

要让FastAPI和Telegram Bot共用同一个事件循环,核心是避开两者默认的阻塞启动方式,改用异步方法将它们纳入同一个循环。以下是具体实现方案:

完整代码示例

import asyncio
from fastapi import FastAPI
from aiogram import Bot, Dispatcher
import uvicorn
import config_data  # 你的配置模块

# 初始化核心实例
app = FastAPI()
bot = Bot(token=config_data.BOT_TOKEN)
dp = Dispatcher(bot)

# 示例FastAPI路由
@app.get("/")
async def root():
    return {"message": "FastAPI与Telegram Bot已同时运行"}

# 异步启动逻辑
async def main():
    # 配置并启动FastAPI异步服务
    uvicorn_config = uvicorn.Config(app, host="0.0.0.0", port=8000)
    uvicorn_server = uvicorn.Server(uvicorn_config)
    fastapi_task = asyncio.create_task(uvicorn_server.serve())

    # 启动Telegram Bot异步轮询
    bot_task = asyncio.create_task(dp.start_polling())

    # 等待两个任务持续运行(直到被外部中断)
    await asyncio.gather(fastapi_task, bot_task)

if __name__ == "__main__":
    asyncio.run(main())

关键细节说明

  • 替换阻塞的uvicorn.run(app):改用uvicorn.Server的异步serve()方法,将其包装为任务加入事件循环,避免独占线程。
  • 替换阻塞的executor.start_polling(dp):使用dp.start_polling()的异步版本,同样以任务形式加入循环,实现与FastAPI并行运行。
  • 通过asyncio.gather()管理两个异步任务,确保它们共用同一个事件循环,无需分开启动服务。

内容的提问来源于stack exchange,提问作者Andrless

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 10:24:44