【问题标题】:Deploy telegram with webhook使用 webhook 部署电报
【发布时间】:2021-02-08 03:15:48
【问题描述】:

我花了一天多的时间研究如何使用 webhook 而不是轮询来部署电报机器人。

即使在官方文档中,它也不适合我https://github.com/python-telegram-bot/python-telegram-bot/wiki/Webhooks

有人可以解释一下哦,给我一些工作教程的链接如何部署像这样的最基本的机器人

#!/usr/bin/env python
# -*- coding: utf-8 -*-

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

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


def help_command(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 main():

    TOKEN = "telegramToken"

    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_command))

    dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
    PORT = int(os.environ.get('PORT', '5000'))
    SERVER = 'myipserver/'
    CERT = 'cert.pem'
    updater.bot.setWebhook(SERVER + TOKEN, certificate=open(CERT, 'rb'))
    # updater.bot.setWebhook(SERVER + TOKEN) also dont working
    updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN)

    # updater.start_polling()

    updater.idle()

if __name__ == '__main__':
    main()

【问题讨论】:

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


    【解决方案1】:

    问题是 App Engine 中的默认端口是 8080 而电报中的 webhook 不支持此端口(仅端口 443、80、88 或 8443) https://core.telegram.org/bots/webhooks

    【讨论】:

      【解决方案2】:

      我在 Heroku 上运行我的 Telegram BOT,通常启动 webhook 然后设置它:

      updater.start_webhook(listen="0.0.0.0",
                            port=int(os.environ.get("PORT", 5000)),
                            url_path='token'
      updater.bot.setWebhook("https://myapp.com/token")
      
      updater.idle()
      

      在 Heroku 上部署时,您会获得一个使用 SSL (https://myapp.herokuapp.com) 的应用程序 URL,然后您可以通过 BotFather 对其进行配置。

      必须为 BotFather 提供 HTTPS 网址,我想知道您是否不这样做,或者您使用的 SSL 证书有问题(自签名?)

      【讨论】:

      • 我想在谷歌云上部署它。我不想在heroku上部署它。我把我的ip实例放在那里并在防火墙规则中打开端口5000
      • 没关系,我试图帮助您举一个真实的例子,您应该能够遵循相同的方法并在任何云提供商上进行部署。您应该向您的聊天机器人添加一个测试 URL(可能添加 Flask),以确认您可以使用 HTTPS 访问应用程序
      猜你喜欢
      • 2018-10-17
      • 2022-12-07
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 2019-03-14
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多