-1

I am new to Python and trying to initialize the Telethon Client on start of a Flask app like

def telegram_initailize():
    global client
    global loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    client = TelegramClient(
        session=MOBILE, api_id=int(API_ID), api_hash=API_HASH, loop=loop
    )

And then when a request comes trying to use it as

def run_when_request_come():
    global client
    with client:
      # logic here

But it errors out to RuntimeError: There is no current event loop in thread 'Thread-2 (process_request_thread)

Shifting the code of telegram_initialize inside run_when_request_come works well but it will initialize the client and loop everytime the function is executed

Navitas28
  • 745
  • 4
  • 13
  • asyncio loops are per-thread. you'd need to create a new loop on every thread, if you need actual help, post a runnable merged minimal code with imports so people can edit it, other than that, use a different framework than flask that is friendlier with asyncio – MustA Apr 24 '23 at 10:09

1 Answers1

0

TelegramClient's loop parameter has been deprecated and no longer has any effect. You can read more about this in Python's changelog and deprecation notes in the documentation for asyncio.

telegram_initailize is correct, but you can only use that client from the same thread. You cannot call telegram_initailize from "Thread 1" and use it in "Thread 2". That's not safe, and it will not work.

See How to combine python asyncio with threads? instead, or consider using an asyncio alternative to Flask.

Lonami
  • 5,945
  • 2
  • 20
  • 38