【问题标题】:How to create webhook for telegram bot with heroku?如何使用heroku为电报机器人创建webhook?
【发布时间】:2020-05-27 17:34:26
【问题描述】:

我正在尝试使用 webhook 部署一个简单的 echo2 机器人。轮询工作正常。但是,我想通过 webhook 使用机器人。对于这个问题,我在互联网上没有找到任何容易理解的答案。 我需要在以下代码中进行哪些更改才能使机器人使用 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()

【问题讨论】:

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


    【解决方案1】:

    使用网络钩子:

    # 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

    【讨论】:

    • 嘿..!感谢您的回答。
    • updater.bot.setWebhook('https://rexxxxxxxxbot.herokuapp.com/1289991195:AAHWmkxxxxxxxxxxxxMZrIcBOl3Y') updater.start_webhook(listen="0.0.0.0", port=8443, url_path='1289991195:xxxxxxxxxxxxZ5YTMZrIcBOl3Y') updater.idle() 这是我添加到代码中的内容。我还删除了 updater.polling()。但机器人仍然无法正常工作。 (我刚刚在 Heroku 上创建了一个简单的应用程序,并将 url 复制到我的代码中。我没有更改任何配置。)
    • 我已经更新了答案:在 Heroku 上你需要动态绑定分配给你的端口(使用 $PORT)PS 避免发布你真正的 Telegram Token
    【解决方案2】:

    您可以删除 updater.start_polling() 调用并改用它。

    Webhook for Heroku python-telegram-bot

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 2021-06-29
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2018-10-17
      • 2017-06-16
      • 2017-08-11
      相关资源
      最近更新 更多