pythonflaskpython-telegram-botpythonanywheretelegram-webhook

Python flask application webhook for Telegram bot not working


This is my code for a flask application. I am running it on pythonanywhere free tier.


from telegram import Update
from telegram.ext import (ApplicationBuilder, ContextTypes, CommandHandler,MessageHandler, filters)
from flask import Flask, request, Response
import os
import telegram

API_KEY = 'telegram token'
app = Flask(__name__)
SECRET = "flask secret key"

CERT = 'path to cert.pem'
CERT_KEY = 'path to private.key'

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(chat_id=update.effective_chat.id, text="No one allowed to use persian characters while I'm running.")

application = ApplicationBuilder().token(API_KEY).build()
start_handler = CommandHandler('start', start)
application.add_handler(start_handler)


@app.route('/', methods=['GET'])
def default():
    return Response('Get ok', status=200)

@app.route('/{}'.format(SECRET), methods=["POST"])
def telegram_webhook():
    application.run_webhook(
        listen='0.0.0.0',
        port=8443,
        secret_token= SECRET,
        key = CERT_KEY,
        cert = CERT,
        ip_address='35.173.69.207',
        webhook_url='https://pouya74.pythonanywhere.com:8443/{}'.format(SECRET),
    )
    print(request.get_json())
    if request.method == 'POST':
        update = request.get_json()
        if "message" in update:
            chat_id = update["message"]["chat"]["id"]
            if "text" in update["message"]:
                return Response(update, status=200)
        return Response(f'Message was not in update object.\n{update}', status=200)

When I try to request from '/' it gives me response for this url. But for the next route I try to run a webhook, but in error logs of the server it gives me runtime error 'Event loop is closed.' Also I tried to place this code block

    application.run_webhook(
        listen='0.0.0.0',
        port=8443,
        secret_token= SECRET,
        key = CERT_KEY,
        cert = CERT,
        ip_address='35.173.69.207',
        webhook_url='https://pouya74.pythonanywhere.com:8443/{}'.format(SECRET),
    )

out of the route function 'telegram_webhook' but it gives me a sock.bind() error which says 'address already in use'. I am wondering what is the proper way to run webhook for telegram bot.


Solution

  • Application.run_webhook is mostly meant as convenience function for use cases where you only run a bot in your script. For running multiple asyncio-frameworks in the same script, it's better to call the methods directly that run_webhook calls. We also have a dedicited wiki section on that.


    Disclaimer: I'm currently the maintainer of python-telegram-bot.