如何用heroku为telegram机器人创建webhook?

问题描述 投票:1回答:1

我正试图使用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个回答
0
投票

使用webhook。

# 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')

注意:

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

0
投票

你可以删除updater.start_polling()调用,然后用这个代替。

用于Heroku的Webhook python-telegram-bot的应用程序

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

© www.soinside.com 2019 - 2024. All rights reserved.