繁体   English   中英

在 python 上使用 webhook 的电报机器人

[英]telegram bot with webhook on python

我正在尝试使用 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 时,我得到:

在此处输入图片说明

在此处输入图片说明

它没有错误,但机器人没有回答我。 我的错误在哪里?

原来问题是两件事。 首先:带有代码的文件必须位于/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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM