【问题标题】:telegram bot with webhook on python在 python 上带有 webhook 的电报机器人
【发布时间】: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_BASEVPS_IP
  • 它没有帮助。机器人运行没有错误,但没有回答
  • 为什么你用浏览器而不是 Telegram 来调用机器人?

标签: python telegram-bot vps


【解决方案1】:

原来问题在于两件事。首先:带有代码的文件必须位于/my token/ 文件夹中,因为这是在代码中隐含的。第二:Telegram 不喜欢 Lets encrypt 的证书(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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-07
    • 2019-03-14
    • 2021-05-28
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    相关资源
    最近更新 更多