在Heroku部署使用pyTelegramBotAPI的电报机器人时,请使用开放端口

2024-04-26 00:07:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在尝试托管使用pyTelegramBotAPI库和aiohttp webhooks编写的Telegram bot时,我遇到了一个问题:Telegram仅支持开放端口80、88、443和8443上的webhooks。与此同时,Heroku博士说: 每个web进程只绑定到一个端口,并侦听来自该端口的请求。要绑定到的端口由Heroku指定为端口环境变量 那么,有没有一种方法可以在Heroku上使用webhooks部署电报机器人呢?我稍微修改了PyTapi的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端口给了应用程序什么)。但这不适用于电报!如果我尝试使用手动将其绑定到端口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。 我该怎么办


Tags: to端口importwebappsslmessageheroku