I’m working on deploying a Telegram bot to Heroku using the python-telegram-bot library with webhook functionality. I’ve been trying to create a basic message repeater bot but I’m running into issues with the webhook configuration.
The bot should respond to user messages by sending back the same text, but it’s not working as expected. I think there might be something wrong with how I’m setting up the webhook or handling the requests.
Here’s my current code:
import telegram
from os import environ
from telegram.ext import Updater
from flask import Flask, request
from config import BOT_TOKEN, HEROKU_URL
server = Flask(__name__)
global telegram_bot
telegram_bot = telegram.Bot(token=BOT_TOKEN)
@server.route('/' + BOT_TOKEN, methods=['POST'])
def handle_webhook():
if request.method == "POST":
# parse the incoming message as Telegram update object
incoming_update = telegram.Update.de_json(request.get_json(force=True))
user_chat_id = incoming_update.message.chat.id
# encode message text for proper UTF-8 handling
user_message = incoming_update.message.text.encode('utf-8')
# send the same message back to user
telegram_bot.sendMessage(chat_id=user_chat_id, text=user_message)
return 'success'
if __name__ == "__main__":
server_port = int(environ.get('PORT', '5000'))
bot_updater = Updater(BOT_TOKEN)
# configure webhook settings
bot_updater.start_webhook(listen="0.0.0.0", port=server_port, url_path=BOT_TOKEN)
bot_updater.bot.setWebhook(HEROKU_URL + BOT_TOKEN)
bot_updater.idle()
server.run(environ.get('PORT'))
Can anyone help me identify what might be causing the webhook to fail? Any guidance would be really helpful!