我正在尝试使用Webhook制作聊天机器人。它在带有VPS_IP
的VPS服务器上进行。我使用示例webhook_aiohttp_echo_bot.py中的代码。
我的代码:
import ssl
from aiohttp import web
import telebot
API_TOKEN = 'my api token'
WEBHOOK_HOST = VPS_IP
WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open')
WEBHOOK_LISTEN = VPS_IP # In some VPS you may need to put here the IP addr
WEBHOOK_SSL_CERT = '/etc/letsencrypt/live/my domain/fullchain.pem' # Path to the ssl certificate
WEBHOOK_SSL_PRIV = '/etc/letsencrypt/live/my domain/privkey.pem' # Path to the ssl private key
WEBHOOK_URL_BASE = "https://{}:{}".format(WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/{}/".format(API_TOKEN)
bot = telebot.TeleBot(API_TOKEN)
app = web.Application()
# Process webhook calls
async def handle(request):
if request.match_info.get('token') == bot.token:
request_body_dict = await request.json()
update = telebot.types.Update.de_json(request_body_dict)
bot.process_new_updates([update])
return web.Response()
else:
return web.Response(status=403)
app.router.add_post('/{token}/', handle)
# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
bot.reply_to(message,
("Hi there, I am EchoBot.\n"
"I am here to echo your kind words back to you."))
# Handle all other messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_message(message):
bot.reply_to(message, message.text)
bot.remove_webhook()
bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH,
certificate=open(WEBHOOK_SSL_CERT, 'r'))
# 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,
)
当我致电https:// my-domain:8443时,我得到:
它没有错误,但是漫游器没有回答我。我的错误在哪里?
答案 0 :(得分:1)
原来问题是两件事。首先:带代码的文件必须位于/my token/
文件夹中,因为这在代码中暗含。第二:Telegram不喜欢Lets加密的证书(https://api.telegram.org/botTOKEN/getWebhookInfo
让我理解了这一点),因此我必须自己使用以下命令:openssl req -newkey rsa: 2048 -sha256 -nodes -keyout private .key -x509 -days 365 -out public.pem -subj "/ C = US / ST = New York / L = Brooklyn / O = Example Brooklyn Company / CN = YOUR_DOMAIN"