如何同时启动aiogram bot和aiohttp网络服务器?

问题描述 投票:0回答:1

我有 aiogram v3 机器人,在轮询模式下运行,我需要添加一个处理程序来处理来自外部应用程序的请求,我使用 aiohttp 服务器来侦听外部请求,处理它并向机器人用户发送通知:

import asyncio
from aiogram import Bot, Dispatcher
from aiohttp import web


app = web.Application()

async def bot_start():
    bot = Bot(TOKEN, parse_mode='HTML')
    dp = Dispatcher()
    await dp.start_polling(bot)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.create_task(bot_start())
    loop.run_until_complete(web.run_app(app, host="127.0.0.1", port=5555))

因此机器人开始轮询,但网络服务器未运行,请帮助在单个项目中启动两个进程。

PS。机器人必须以轮询模式运行,而不是 webhook。

python telegram-bot aiohttp aiogram
1个回答
0
投票

文档中对此进行了解释:https://docs.aiohttp.org/en/stable/web_advanced.html#complex-applications

使用cleanup_ctx:

async def run_other_task(_app):
    task = asyncio.create_task(other_long_task())

    yield

    task.cancel()
    with suppress(asyncio.CancelledError):
        await task  # Ensure any exceptions etc. are raised.

app.cleanup_ctx.append(run_other_task)

然后使用

web.run_app()
正常运行您的应用程序,不要扰乱循环。

请注意,代码中的一个致命缺陷是

web.run_app()
不是异步函数,它是异步应用程序的入口函数。即它取代了典型异步应用程序中的
asyncio.run()

© www.soinside.com 2019 - 2024. All rights reserved.