2021-01-30 14:15:39 +01:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# A library that provides a Python interface to the Telegram Bot API
|
2024-02-19 20:06:25 +01:00
|
|
|
# Copyright (C) 2015-2024
|
2021-01-30 14:15:39 +01:00
|
|
|
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Lesser Public License
|
|
|
|
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
2021-10-08 08:17:00 +02:00
|
|
|
# pylint: disable=missing-module-docstring
|
2022-04-24 12:38:09 +02:00
|
|
|
import asyncio
|
2022-05-19 12:47:53 +02:00
|
|
|
import json
|
2022-04-24 12:38:09 +02:00
|
|
|
from http import HTTPStatus
|
2023-12-14 21:37:00 +01:00
|
|
|
from pathlib import Path
|
2024-03-24 21:04:10 +01:00
|
|
|
from socket import socket
|
2021-01-30 14:15:39 +01:00
|
|
|
from ssl import SSLContext
|
2022-04-24 12:38:09 +02:00
|
|
|
from types import TracebackType
|
2023-12-14 21:37:00 +01:00
|
|
|
from typing import TYPE_CHECKING, Optional, Type, Union
|
2021-01-30 14:15:39 +01:00
|
|
|
|
2022-10-31 10:12:18 +01:00
|
|
|
# Instead of checking for ImportError here, we do that in `updater.py`, where we import from
|
|
|
|
# this module. Doing it here would be tricky, as the classes below subclass tornado classes
|
2021-01-30 14:15:39 +01:00
|
|
|
import tornado.web
|
|
|
|
from tornado.httpserver import HTTPServer
|
|
|
|
|
2023-12-14 21:37:00 +01:00
|
|
|
try:
|
|
|
|
from tornado.netutil import bind_unix_socket
|
|
|
|
|
|
|
|
UNIX_AVAILABLE = True
|
|
|
|
except ImportError:
|
|
|
|
UNIX_AVAILABLE = False
|
|
|
|
|
2021-01-30 14:15:39 +01:00
|
|
|
from telegram import Update
|
2023-04-10 17:01:35 +02:00
|
|
|
from telegram._utils.logging import get_logger
|
2022-05-05 09:27:54 +02:00
|
|
|
from telegram.ext._extbot import ExtBot
|
2021-01-30 14:15:39 +01:00
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from telegram import Bot
|
|
|
|
|
2023-04-10 17:01:35 +02:00
|
|
|
# This module is not visible to users, so we log as Updater
|
|
|
|
_LOGGER = get_logger(__name__, class_name="Updater")
|
|
|
|
|
2021-01-30 14:15:39 +01:00
|
|
|
|
|
|
|
class WebhookServer:
|
2022-04-24 12:38:09 +02:00
|
|
|
"""Thin wrapper around ``tornado.httpserver.HTTPServer``."""
|
|
|
|
|
2021-05-29 16:18:16 +02:00
|
|
|
__slots__ = (
|
2022-04-24 12:38:09 +02:00
|
|
|
"_http_server",
|
|
|
|
"_server_lock",
|
|
|
|
"_shutdown_lock",
|
2024-02-05 19:24:00 +01:00
|
|
|
"is_running",
|
|
|
|
"listen",
|
|
|
|
"port",
|
2023-12-14 21:37:00 +01:00
|
|
|
"unix",
|
2021-05-29 16:18:16 +02:00
|
|
|
)
|
|
|
|
|
2021-01-30 14:15:39 +01:00
|
|
|
def __init__(
|
2023-12-14 21:37:00 +01:00
|
|
|
self,
|
|
|
|
listen: str,
|
|
|
|
port: int,
|
|
|
|
webhook_app: "WebhookAppClass",
|
|
|
|
ssl_ctx: Optional[SSLContext],
|
2024-03-24 21:04:10 +01:00
|
|
|
unix: Optional[Union[str, Path, socket]] = None,
|
2021-01-30 14:15:39 +01:00
|
|
|
):
|
2023-12-14 21:37:00 +01:00
|
|
|
if unix and not UNIX_AVAILABLE:
|
|
|
|
raise RuntimeError("This OS does not support binding unix sockets.")
|
2022-04-24 12:38:09 +02:00
|
|
|
self._http_server = HTTPServer(webhook_app, ssl_options=ssl_ctx)
|
2021-01-30 14:15:39 +01:00
|
|
|
self.listen = listen
|
|
|
|
self.port = port
|
|
|
|
self.is_running = False
|
2024-03-24 21:04:10 +01:00
|
|
|
self.unix = None
|
|
|
|
if unix and isinstance(unix, socket):
|
|
|
|
self.unix = unix
|
|
|
|
elif unix:
|
|
|
|
self.unix = bind_unix_socket(str(unix))
|
2022-04-24 12:38:09 +02:00
|
|
|
self._server_lock = asyncio.Lock()
|
|
|
|
self._shutdown_lock = asyncio.Lock()
|
2021-01-30 14:15:39 +01:00
|
|
|
|
2023-05-18 07:57:59 +02:00
|
|
|
async def serve_forever(self, ready: Optional[asyncio.Event] = None) -> None:
|
2022-04-24 12:38:09 +02:00
|
|
|
async with self._server_lock:
|
2023-12-14 21:37:00 +01:00
|
|
|
if self.unix:
|
2024-03-24 21:04:10 +01:00
|
|
|
self._http_server.add_socket(self.unix)
|
2023-12-14 21:37:00 +01:00
|
|
|
else:
|
|
|
|
self._http_server.listen(self.port, address=self.listen)
|
2021-01-30 14:15:39 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
self.is_running = True
|
2021-01-30 14:15:39 +01:00
|
|
|
if ready is not None:
|
|
|
|
ready.set()
|
|
|
|
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug("Webhook Server started.")
|
2021-01-30 14:15:39 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def shutdown(self) -> None:
|
|
|
|
async with self._shutdown_lock:
|
2021-01-30 14:15:39 +01:00
|
|
|
if not self.is_running:
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug("Webhook Server is already shut down. Returning")
|
2021-01-30 14:15:39 +01:00
|
|
|
return
|
2022-04-24 12:38:09 +02:00
|
|
|
self.is_running = False
|
|
|
|
self._http_server.stop()
|
|
|
|
await self._http_server.close_all_connections()
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug("Webhook Server stopped")
|
2021-01-30 14:15:39 +01:00
|
|
|
|
|
|
|
|
|
|
|
class WebhookAppClass(tornado.web.Application):
|
2022-04-24 12:38:09 +02:00
|
|
|
"""Application used in the Webserver"""
|
|
|
|
|
2022-06-27 18:54:11 +02:00
|
|
|
def __init__(
|
2023-05-18 07:57:59 +02:00
|
|
|
self,
|
|
|
|
webhook_path: str,
|
|
|
|
bot: "Bot",
|
|
|
|
update_queue: asyncio.Queue,
|
|
|
|
secret_token: Optional[str] = None,
|
2022-06-27 18:54:11 +02:00
|
|
|
):
|
|
|
|
self.shared_objects = {
|
|
|
|
"bot": bot,
|
|
|
|
"update_queue": update_queue,
|
|
|
|
"secret_token": secret_token,
|
|
|
|
}
|
2023-03-25 19:18:04 +01:00
|
|
|
handlers = [(rf"{webhook_path}/?", TelegramHandler, self.shared_objects)]
|
2021-03-13 16:21:03 +01:00
|
|
|
tornado.web.Application.__init__(self, handlers) # type: ignore
|
2021-01-30 14:15:39 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
def log_request(self, handler: tornado.web.RequestHandler) -> None:
|
|
|
|
"""Overrides the default implementation since we have our own logging setup."""
|
2021-01-30 14:15:39 +01:00
|
|
|
|
|
|
|
|
2021-10-08 08:17:00 +02:00
|
|
|
# pylint: disable=abstract-method
|
2022-04-24 12:38:09 +02:00
|
|
|
class TelegramHandler(tornado.web.RequestHandler):
|
2022-05-12 18:18:40 +02:00
|
|
|
"""BaseHandler that processes incoming requests from Telegram"""
|
2021-01-30 14:15:39 +01:00
|
|
|
|
2024-02-05 19:24:00 +01:00
|
|
|
__slots__ = ("bot", "secret_token", "update_queue")
|
2021-01-30 14:15:39 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
SUPPORTED_METHODS = ("POST",) # type: ignore[assignment]
|
|
|
|
|
2022-06-27 18:54:11 +02:00
|
|
|
def initialize(self, bot: "Bot", update_queue: asyncio.Queue, secret_token: str) -> None:
|
2022-04-24 12:38:09 +02:00
|
|
|
"""Initialize for each request - that's the interface provided by tornado"""
|
2021-10-08 08:17:00 +02:00
|
|
|
# pylint: disable=attribute-defined-outside-init
|
2021-01-30 14:15:39 +01:00
|
|
|
self.bot = bot
|
2024-02-07 20:45:57 +01:00
|
|
|
self.update_queue = update_queue
|
|
|
|
self.secret_token = secret_token
|
2022-06-27 18:54:11 +02:00
|
|
|
if secret_token:
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug(
|
2022-09-17 15:08:54 +02:00
|
|
|
"The webhook server has a secret token, expecting it in incoming requests now"
|
2022-06-27 18:54:11 +02:00
|
|
|
)
|
2021-01-30 14:15:39 +01:00
|
|
|
|
|
|
|
def set_default_headers(self) -> None:
|
2022-04-24 12:38:09 +02:00
|
|
|
"""Sets default headers"""
|
2021-01-30 14:15:39 +01:00
|
|
|
self.set_header("Content-Type", 'application/json; charset="utf-8"')
|
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
async def post(self) -> None:
|
|
|
|
"""Handle incoming POST request"""
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug("Webhook triggered")
|
2021-01-30 14:15:39 +01:00
|
|
|
self._validate_post()
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2021-01-30 14:15:39 +01:00
|
|
|
json_string = self.request.body.decode()
|
|
|
|
data = json.loads(json_string)
|
2022-04-24 12:38:09 +02:00
|
|
|
self.set_status(HTTPStatus.OK)
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug("Webhook received data: %s", json_string)
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
update = Update.de_json(data, self.bot)
|
|
|
|
except Exception as exc:
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.critical(
|
2022-04-24 12:38:09 +02:00
|
|
|
"Something went wrong processing the data received from Telegram. "
|
2024-07-06 16:09:04 +02:00
|
|
|
"Received data was *not* processed! Received data was: %r",
|
|
|
|
data,
|
2022-04-24 12:38:09 +02:00
|
|
|
exc_info=exc,
|
|
|
|
)
|
2023-12-09 17:35:23 +01:00
|
|
|
raise tornado.web.HTTPError(
|
|
|
|
HTTPStatus.BAD_REQUEST, reason="Update could not be processed"
|
|
|
|
) from exc
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2021-01-30 14:15:39 +01:00
|
|
|
if update:
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug(
|
2022-10-07 11:51:53 +02:00
|
|
|
"Received Update with ID %d on Webhook",
|
|
|
|
# For some reason pylint thinks update is a general TelegramObject
|
|
|
|
update.update_id, # pylint: disable=no-member
|
|
|
|
)
|
2022-04-24 12:38:09 +02:00
|
|
|
|
2021-06-06 11:48:48 +02:00
|
|
|
# handle arbitrary callback data, if necessary
|
|
|
|
if isinstance(self.bot, ExtBot):
|
|
|
|
self.bot.insert_callback_data(update)
|
2022-04-24 12:38:09 +02:00
|
|
|
|
|
|
|
await self.update_queue.put(update)
|
2021-01-30 14:15:39 +01:00
|
|
|
|
|
|
|
def _validate_post(self) -> None:
|
2022-04-24 12:38:09 +02:00
|
|
|
"""Only accept requests with content type JSON"""
|
2021-01-30 14:15:39 +01:00
|
|
|
ct_header = self.request.headers.get("Content-Type", None)
|
|
|
|
if ct_header != "application/json":
|
2022-04-24 12:38:09 +02:00
|
|
|
raise tornado.web.HTTPError(HTTPStatus.FORBIDDEN)
|
2022-06-27 18:54:11 +02:00
|
|
|
# verifying that the secret token is the one the user set when the user set one
|
|
|
|
if self.secret_token is not None:
|
|
|
|
token = self.request.headers.get("X-Telegram-Bot-Api-Secret-Token")
|
|
|
|
if not token:
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug("Request did not include the secret token")
|
2022-06-27 18:54:11 +02:00
|
|
|
raise tornado.web.HTTPError(
|
|
|
|
HTTPStatus.FORBIDDEN, reason="Request did not include the secret token"
|
|
|
|
)
|
|
|
|
if token != self.secret_token:
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug("Request had the wrong secret token: %s", token)
|
2022-06-27 18:54:11 +02:00
|
|
|
raise tornado.web.HTTPError(
|
|
|
|
HTTPStatus.FORBIDDEN, reason="Request had the wrong secret token"
|
|
|
|
)
|
2021-01-30 14:15:39 +01:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
def log_exception(
|
|
|
|
self,
|
|
|
|
typ: Optional[Type[BaseException]],
|
|
|
|
value: Optional[BaseException],
|
|
|
|
tb: Optional[TracebackType],
|
|
|
|
) -> None:
|
|
|
|
"""Override the default logging and instead use our custom logging."""
|
2023-04-10 17:01:35 +02:00
|
|
|
_LOGGER.debug(
|
2022-04-24 12:38:09 +02:00
|
|
|
"%s - %s",
|
2021-01-30 14:15:39 +01:00
|
|
|
self.request.remote_ip,
|
2022-04-24 12:38:09 +02:00
|
|
|
"Exception in TelegramHandler",
|
|
|
|
exc_info=(typ, value, tb) if typ and value and tb else value,
|
2021-01-30 14:15:39 +01:00
|
|
|
)
|