Fix Telethon event loop lifecycle

This commit is contained in:
Tanner
2026-11-22 17:32:13 +00:00
parent 38265f6201
commit ffd46f9d66
2 changed files with 35 additions and 7 deletions
+14 -5
View File
@@ -5,7 +5,6 @@ logging.basicConfig(
level=logging.DEBUG if os.environ.get('DEBUG') else logging.INFO)
import settings
import asyncio
import json
import requests
from datetime import datetime
@@ -14,7 +13,7 @@ from telethon import TelegramClient, events
from aiohttp import web
bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN)
bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH)
TANNER = 79316791
messages = {}
@@ -126,8 +125,18 @@ async def submit(request):
return web.Response(text='Thanks! Your message is pending approval.')
async def telegram_lifecycle(app):
# Connect Telethon on aiohttp's event loop and disconnect before it closes.
await bot.start(bot_token=settings.API_TOKEN)
try:
yield
finally:
await bot.disconnect()
app = web.Application()
app.router.add_post('/', submit)
app.cleanup_ctx.append(telegram_lifecycle)
if __name__ == '__main__':
bot.start()
app = web.Application()
app.router.add_post('/', submit)
web.run_app(app, port=8123)
+21 -2
View File
@@ -16,11 +16,18 @@ ROOT = Path(__file__).parent
class _FakeBot:
def __init__(self):
self.started_loop = None
self.disconnected_loop = None
def on(self, event):
return lambda callback: callback
def start(self, **kwargs):
return self
async def start(self, **kwargs):
self.started_loop = asyncio.get_running_loop()
async def disconnect(self):
self.disconnected_loop = asyncio.get_running_loop()
def load_service():
@@ -102,6 +109,18 @@ class T0SigUpgradeTests(unittest.TestCase):
self.assertTrue(TelegramClient)
self.assertTrue(events.NewMessage)
def test_telethon_starts_and_stops_on_aiohttp_lifecycle_loop(self):
async def exercise_lifecycle():
loop = asyncio.get_running_loop()
self.assertIsNone(service.bot.started_loop)
lifecycle = service.telegram_lifecycle(service.app)
await lifecycle.__anext__()
self.assertIs(service.bot.started_loop, loop)
await lifecycle.aclose()
self.assertIs(service.bot.disconnected_loop, loop)
asyncio.run(exercise_lifecycle())
if __name__ == '__main__':
unittest.main()