Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up python-telegram-bot webhook on Heroku?

I'm using the python-telegram-bot wrapper, and I've been trying to host a simple echo telegram bot on Heroku adapting a pre-existing example that was meant for the Google App Engine as well as the webhook guide on the wiki, but to no avail.

I do not seem to be able to get the webhook to work, and for the bot to echo messages correctly.

I can't seem to figure out what's wrong, so any help to point me in the right direction would be much appreciated!

My attempt is detailed below.

import telegram
from os import environ
from telegram.ext import Updater
from flask import Flask, request
from credentials import TOKEN, APP_URL

app = Flask(__name__)

global bot
bot = telegram.Bot(token=TOKEN)


@app.route('/' + TOKEN, methods=['POST'])
def webhook_handler():
    if request.method == "POST":
        # retrieve the message in JSON and then transform it to Telegram object
        update = telegram.Update.de_json(request.get_json(force=True))

        chat_id = update.message.chat.id

        # Telegram understands UTF-8, so encode text for unicode compatibility
        text = update.message.text.encode('utf-8')

        # repeat the same message back (echo)
        bot.sendMessage(chat_id=chat_id, text=text)

    return 'ok'


if __name__ == "__main__":
    PORT = int(environ.get('PORT', '5000'))
    updater = Updater(TOKEN)

    # add handlers
    updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN)
    updater.bot.setWebhook(APP_URL + TOKEN)
    updater.idle()
    app.run(environ.get('PORT'))
like image 745
Shinlos Avatar asked Jan 16 '17 17:01

Shinlos


1 Answers

in the wiki you'll find the easiest example.

https://github.com/python-telegram-bot/python-telegram-bot/wiki/Webhooks#heroku

In short, do not try to use flask. Use the built-in webserver.

like image 77
Eldin Avatar answered Oct 04 '22 23:10

Eldin