繁体   English   中英

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

[英]How to create webhook for telegram bot with heroku?

我正在尝试使用 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()

使用网络钩子:

# 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.start_polling() 调用并改用它。

Heroku python-telegram-bot 的 Webhook

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM