[英]Use an open port when deploying telegram bot using pyTelegramBotAPI to Heroku
在尝试托管使用 pyTelegramBotAPI 库和 aiohttp webhook 编写的 Telegram 机器人时,我遇到了一个问题:Telegram 仅支持开放端口 80、88、443 和 8443 上的 webhook。同时,Heroku 文档说:每个 Z2567A5EC9705EB7AC2C984033E01 进程简单地绑定到端口, 并监听来自该端口的请求。 要绑定的端口由 Heroku 作为 PORT 环境变量分配。 那么有没有办法在 Heroku 上使用 webhook 部署电报机器人? 我从 pyTelegramBotAPI 的 github repo 稍微修改了这个示例代码:
import os
import ssl
import requests
import telebot
from aiohttp import web
WEBHOOK_HOST = 'pdf-tg-bot.herokuapp.com'
WEBHOOK_PORT = os.getenv('PORT', default=8443) # 443, 80, 88 or 8443 (port need to be 'open')
WEBHOOK_LISTEN = '0.0.0.0'
WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate
WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key
WEBHOOK_URL_BASE = "https://{}:{}".format(WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/{}/".format(TOKEN)
app = web.Application()
bot = telebot.TeleBot(TOKEN, parse_mode=None)
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Run /new to create a new document.")
# some other message handlers
# Build ssl context
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.load_cert_chain(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV)
# Start aiohttp server
web.run_app(
app,
host=WEBHOOK_LISTEN,
port=WEBHOOK_PORT,
ssl_context=context,
)
Of course, Heroku binds the web app to $PORT and it runs on https://0.0.0.0:(whatever port Heroku gave the app). 但这不适用于电报! 如果我尝试使用WEBHOOK_PORT = 8443
手动将其绑定到端口 8443 ,我会如预期的那样得到 Heroku 错误Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
。 我的 Procfile 是web: python main.py
。 我应该怎么办?
示例中有错误。 您无需在 webhook URL 中指定端口。 Heroku提供的端口是供应用程序绑定的,不是供外部访问服务器的。
改变这个
WEBHOOK_URL_BASE = "https://{}:{}".format(WEBHOOK_HOST, WEBHOOK_PORT)
至
WEBHOOK_URL_BASE = "https://{}".format(WEBHOOK_HOST)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.