Sova Kefirova
Sova Kefirova

Reputation: 201

telegram bot with webhook on python

Im trying to make chat bot with webhook. It takes place on VPS server with VPS_IP. I use code from example webhook_aiohttp_echo_bot.py.

My code:

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,
)

When I call https://my-domain:8443, I get:

enter image description here

enter image description here

It goes without errors, but bot doesn't answer me. Where is my mistake?

Upvotes: 1

Views: 2795

Answers (1)

Sova Kefirova
Sova Kefirova

Reputation: 201

It turned out the problem is two things. First: the file with the code had to be located in the /my token/ folder, because this is implied in the code. Second: Telegram does not like certificates from Lets encrypt (https://api.telegram.org/botTOKEN/getWebhookInfo allowed me to understand this), so I had to do them myself with the following command: 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"

Upvotes: 1

Related Questions