如何在Heroku上设置python-telegram-bot webhook?

Shi*_*los 6 python-telegram-bot telegram-bot

我正在使用python-telegram-bot包装器,我一直在尝试在Heroku上托管一个简单的回声电报机器人,以适应用于Google App Engine 的预先存在的示例以及维基上的webhook指南,但无济于事.

我似乎无法使webhook工作,并且机器人能够正确地回显消息.

我似乎无法弄清楚什么是错的,所以任何帮助指出我正确的方向将非常感谢!

我的尝试详述如下.

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'))
Run Code Online (Sandbox Code Playgroud)

Eld*_*din 5

在 wiki 中,您会找到最简单的示例。

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

总之,不要尝试使用flask。使用内置的网络服务器。