I built a telegram bot with python-telegram-bot and I created a webhook with flask.
I tried deploying to ubuntu and running the server with gunicorn. However, I think both the telegram bot and flask app needs to be started but I cant seem to get this to work. I have only succeeded in running either of the two.
This is my code.
from flask import Flask, Blueprint
import logging
from telegram.ext import ApplicationBuilder, CommandHandler, Application, ContextTypes
from config.configuration import Config as CG
from bot.trivial_operations import start, unknown_handler, echo, logger
from bot.pdf_operations import conv_handler_file
from flask import Blueprint, request
from telegram import Update, Bot
telegram_token = CG.telegram_api_key
def create_app():
app = Flask(__name__)
app.config.from_object(CG)
# app.register_blueprint(webhook_bp)
application = (
Application.builder().token(telegram_token).updater(None).build()
)
@app.route("/webhook", methods=["POST"])
async def webhook():
logger.info("Received webhook")
logger.info(request.get_json(force=True))
# await application.process_update(Update.de_json(data=request.get_json(force=True), bot=bot))
await application.update_queue.put(
Update.de_json(data=request.get_json(force=True), bot=application.bot)
)
return 'ok'
application.add_handler(CommandHandler('echo', echo))
application.add_handler(CommandHandler('start', start))
application.add_handler(conv_handler_file)
application.add_handler(unknown_handler)
return app, application
async def main():
app_, bot = create_app()
await bot.initialize()
await bot.start()
logger.info("Flask not")
app_.run(host="127.0.0.1", port=5002)
logger.info("Flask running")
await bot.stop()
await bot.shutdown()
my wsgi.py file
import asyncio
from config.app import main, create_app
app = create_app()[0]
if __name__ == "__main__":
asyncio.run(main())
and my gunicorn service
Description=Gunicorn instance to serve assist-me
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/home/apps/assist_app/src
Environment="PATH=/home/apps/assist_app/venv/bin"
ExecStart=/home/apps/assist_app/venv/bin/gunicorn -k gevent --workers 3 --bind unix:/home/apps/assist_app/src/assist_me.sock wsgi:app
[Install]
WantedBy=multi-user.target
This is a link to an example from the documentation.
example