how to use telethon in flask site?



Flask is a wsgi server, telethon support asgi server only, in this blog lets see how to use telethon in flask 


Telethon is asyncio based so you need to install async supported flask first

pip install flask[async]

 

Convert your flask website wsgi to asgi 


install asgiref using pip

pip install asgiref

 

convert Wsgi To Asgi 

from asgiref.wsgi import WsgiToAsgi

from flask import Flask

app = Flask(__name__)

asgi_app = WsgiToAsgi(app)


however you cant run asgi_app using flask's inbuilt app.run() method so we need to use Asynchronous Server to run it .



Method1 - use hypercorn


install using pip

pip install hypercorn


use hypercorn.asyncio method

import hypercorn.asyncio
from hypercorn.config import Config
config = Config()
port = 5000
config.bind = [f"0.0.0.0:{port}"]
await hypercorn.asyncio.serve(asgi_app, Config()) 
#run in asyncio function


Method2 - using uvicorn


install using pip

pip install uvicorn


using uvicorn.Server.serve() method

import uvicorn
config = uvicorn.Config("__main__:asgi_app", port=5000, log_level="info")
server = uvicorn.Server(config)
await server.serve() #run in asyncio function


Sample code telethon + flask + uvicorn


import asyncio, os
import uvicorn
from flask import Flask
from asgiref.wsgi import WsgiToAsgi
from telethon import TelegramClient, events
from telethon.sessions import StringSession

app = Flask(__name__)
asgi_app = WsgiToAsgi(app)

client = TelegramClient("...")

@app.route('/')
async def hello_world():
return 'Hello World'

@client.on(events.NewMessage(pattern='/start'))
async def start(event):
return await event.respond('hello World!')

async def start():
    await client.start()
    config = uvicorn.Config("__main__:asgi_app", port=5000, log_level="info")
    server = uvicorn.Server(config)
    await server.serve()
    #no need # await client.run_until_disconnected()

if __name__ == "__main__":
    client.loop.run_until_complete(start())



now you can use telethon handler with your flask website without any issue. however i still recommend to use quart because its more asyncio friendly!