如何使用heroku为电报机器人创建webhook?

时间:2020-05-27 17:34:26

标签: python telegram telegram-bot python-telegram-bot telegram-webhook

我正在尝试使用Webhook部署一个简单的echo2机器人。轮询工作正常。但是,我想通过webhook使用该机器人。我在互联网上找不到任何易于理解的答案。 我需要在以下代码中进行哪些更改才能使Bot使用webhook ..正常工作?

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)


# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text('Hi!')


def help(update, context):
    """Send a message when the command /help is issued."""
    update.message.reply_text('Help!')


def echo(update, context):
    """Echo the user message."""
    update.message.reply_text(update.message.text)


def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)


def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater("TOKEN", use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()


if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:0)

使用网络挂钩:

# Use env variable PORT
PORT = int(os.environ.get("PORT", 3978)) 
updater.start_webhook(listen="0.0.0.0", port=PORT, url_path='TELEGRAM_TOKEN')

updater.bot.setWebhook('https://mywebhook/TELEGRAM_TOKEN')

注意:

  • 设置您的BotFather收到的TELEGRAM_TOKEN
  • 设置相关端口(可能取决于运行Webhook的应用程序):上面的示例显示了如何在Heroku上绑定端口
  • webhook必须在HTTPS上侦听

答案 1 :(得分:0)

您只需删除updater.start_polling()调用并使用它即可。

Webhook for Heroku python-telegram-bot

确保您已经在heroku上创建了应用程序。