【发布时间】:2021-01-21 15:10:45
【问题描述】:
我正在尝试使用 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 时,我得到:
它没有错误,但机器人没有回答我。我的错在哪里?
【问题讨论】:
-
尝试将
WEBHOOK_HOST设置为 '0.0.0.0'。看看它是否有效 -
它在
set_webhook with“保留IP地址0.0.0.0”中推送错误 -
不是
WEBHOOK_URL_BASE- 而是WEBHOOK_HOST(保持WEBHOOK_URL_BASE为VPS_IP) -
它没有帮助。机器人运行没有错误,但没有回答
-
为什么你用浏览器而不是 Telegram 来调用机器人?
标签: python telegram-bot vps