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 Configconfig = Config()port = 5000config.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())