Search code examples
pythonflaskruntime-errorpython-asynciotelethon

Python Flask with Telethon


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()

Solution

  • 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.