2

I want to use Telethon Telegram API from my Flask Web App. But when I am running it, I am getting following error:

RuntimeError: There is no current event loop in thread 'Thread-1'.

I think there is some issues with asyncio. But I am not sure about that.

Here is my code

#!/usr/bin/python3 from flask import Flask from telethon import TelegramClient from telethon import sync app = Flask(__name__) @app.route('/') def index(): api_id = XXXXXX api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' client = TelegramClient('XXXXXX', api_id, api_hash) client.start() return 'Index Page' if __name__ == '__main__': app.run() 

3 Answers 3

3

Here's what I learned after trying this out. First, Make sure you know what asyncio is, it's really super easy. Then You can work on it with more productivity.

Telethon uses asyncio which means that when you call blocking methods you have to wait until the coroutine finishes.

client.loop ###Doesn't work inside flask, it might have to do with threads. 

You can easily import asyncio and use the main loop. like this.

import asyncio loop = asyncio.get_event_loop() 

Now you're ready to wait for coroutines to finish.

  1. Create a new async function and add await to the blocking methods.
  2. Execute the code using the main event loop.

Here's a code sample.

async def getYou(): return await client.get_me() @app.route("/getMe", methods=['GET']) def getMe(): return {"MyTelegramAccount": loop.run_until_complete(getYou())} 

And one more thing. don't use telethon.sync, it's not fully translated to sync, it uses the above pattern it awaits all of the methods.

Sign up to request clarification or add additional context in comments.

1 Comment

What if you also need your route handler method to be async?
1

Basically, it's due to Python's GIL. If you don't want to dig into asyncio internals, just pip3 install telethon-sync and you're good to go.

6 Comments

No worries. There's also more info on telethon.readthedocs.io/en/stable/extra/basic/…
its deprecated, any other solution?
@SaebMolaee see Can I use Flask with the library? in the documentation.
@Lonami It's interesting why you don't recommend Flask with Telethon, Can you give details on your idea.
Flask is threaded. Telethon uses asyncio. Using threads and asyncio is an unnecessary headache, even if you know what you're doing. I have nothing against flask per se, but there are flask-like alternatives which are asyncio-native.
|
0

What worked for me is to use the same loop of the telethon client:

# Telegram client client = TelegramClient('session_id', api_id, api_hash) # Get event loop loop = client.loop @app.route("/get_data", methods=["GET"]) async def get_data(): await client.start() # or any telethon async function if __name__ == "__main__": loop.run_until_complete(app.run()) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.