Python Flask with Telethon

Question:

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()
Asked By: Robert Brown

||

Answers:

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.

Answered By: norus

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.

Answered By: Ian Elvister

In your place I would consider using Quart it’s suggested on Telethon own’s documentation and it’s much easier.