使用pyTelegramBotAPI将电报bot部署到Heroku时,使用开放端口

rkttyhzu  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(103)

在尝试托管用pyTelegramBotAPI库和aiohttp webhook编写的Telegram bot时,我遇到了一个问题:Telegram仅支持开放端口80、88、443和8443上的webhook。同时,Heroku文档指出:* 每个web进程只绑定到一个端口,并监听来自该端口的请求。要绑定到的端口由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,
)

当然,Heroku会将Web应用绑定到$PORT,并在www.example.com上运行https://0.0.0.0:(不管Heroku给了应用什么端口)。但这在Telegram上不起作用!如果我尝试手动将其绑定到端口8443,并使用WEBHOOK_PORT = 8443,我会得到一个Heroku错误Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch。我的Procfile是web: python main.py。我该怎么办?

yduiuuwa

yduiuuwa1#

示例中有一个错误。您不需要在webhook URL中指定端口。Heroku提供的端口是用于绑定应用程序的,而不是用于从外部访问服务器的。
更改此项

WEBHOOK_URL_BASE = "https://{}:{}".format(WEBHOOK_HOST, WEBHOOK_PORT)

WEBHOOK_URL_BASE = "https://{}".format(WEBHOOK_HOST)

相关问题