使用pyTelegramBotAPI将telegram bot部署到Heroku时,请使用开放端口



在尝试托管用pyTelegramBotAPI库和aiohttp-webhook编写的Telegram bot时,我遇到了一个问题:Telegram只支持开放端口80、88、443和8443上的webhook。与此同时,Heroku的医生说:每个web进程只需绑定到一个端口,并侦听来自该端口的请求。要绑定的端口由Heroku指定为port环境变量那么有没有一种方法可以在Heroku上使用webhook部署telegram机器人程序?我从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,
)

当然,Heroku将web应用程序绑定到$PORT,并在https://0.0.0.0:(Heroku给应用程序的端口(。但这对Telegram不起作用!如果我尝试使用手动将其绑定到端口8443WEBHOOK_PORT = 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)

相关内容

最新更新