简体   繁体   English

在同一代码中与另一个事件循环一起运行 aiohttp

[英]Run aiohttp alongside another event loop in the same code

I have a bot that runs Telethon and aiohttp.server in the same code, working at the same time我有一个机器人在同一代码中运行 Telethon 和 aiohttp.server,同时工作

This is a simplified example of how i ran it in aiohttp version 3.7.4.post0这是我如何在 aiohttp 版本 3.7.4.post0 中运行它的简化示例

from aiohttp import web
from telethon import TelegramClient

api_id="1234567"
api_hash="1234567890adcbefgh"
bot_token="1234567:abcdefgh0987654321"

bot=TelegramClient("my",api_id,api_hash).start(bot_token=bot_token)

# Simple TG handler
async def tg_handler(event):
    print(event.raw_text)
    await event.reply("HEY")

# Simple GET handler at /
async def http_handler_main(request):
    return web.Response(body="Hi",content_type="text/plain",charset="utf-8",status=200)

async def build_app():
    app=web.Application()
    app.add_routes([web.get("/",http_handler_main)])
    return app

bot.add_event_handler(tg_handler,events.NewMessage())
web.run_app(build_app(),port="80")

Since I updated to 3.8.1 this no longer works correctly I am using python 3.9.6 btw and Telethon version is still is the same as before this happened由于我更新到 3.8.1 这不再正常工作我正在使用 python 3.9.6 btw 并且 Telethon 版本仍然与发生这种情况之前相同

EDIT1: EXPECTED BEHAVIOR: Run the webserver and the telegram bot EDIT1:预期行为:运行网络服务器和电报机器人

web.run_app creates a new asyncio event loop. web.run_app创建一个新的asyncio事件循环。 Telethon by default uses the "current" asyncio event loop (which is the default for the main thread in this case). Telethon 默认使用“当前” asyncio事件循环(在这种情况下,这是主线程的默认设置)。 Because they're different even loops, they can't possibly work together.因为它们是不同的偶数循环,所以它们不可能一起工作。

Either create the TelegramClient inside async def build_app() (so it picks up the right event loop), or use web.run_app(..., loop=client.loop) .async def build_app()中创建TelegramClient (因此它会选择正确的事件循环),或者使用web.run_app(..., loop=client.loop)

If web.run_app does not support setting the loop, you will need to do whatever it's doing manually with client.loop instead.如果web.run_app不支持设置循环,您将需要使用client.loop手动执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM