thinlog.handlers.telegram module#

Handler that sends log records to Telegram via the Bot API.

class thinlog.handlers.telegram.TelegramHandler(settings: TelegramHandlerSettings | dict[str, Any])[source]#

Bases: Handler

Send log records to a Telegram chat via the Bot API.

Short messages are sent as regular Telegram messages. Messages exceeding MAX_MESSAGE_LEN are uploaded as document attachments with a truncated caption.

Per-record overrides (chat_id, token, topic_id, disable) can be provided via a handlers_context.telegram dict on the log record.

Parameters:

settings – A TelegramHandlerSettings or a dict of its fields.

API_ENDPOINT = 'https://api.telegram.org'#
property client: Client#

Lazily initialised httpx.Client.

close() None[source]#

Close the underlying HTTP client.

emit(record: LogRecord) None[source]#

Format the record and send it to Telegram.

Short messages are sent via sendMessage; long messages are uploaded as a document via sendDocument. Supports per-record overrides via record.handlers_context["telegram"].

classmethod format_url(token: str, method: str) str[source]#

Build a Telegram Bot API URL for the given method.

request(method: str, bot_token: str | None = None, **kwargs: Any) Any[source]#

Call a Telegram Bot API method and return the JSON response.

send_document(text: str, document: BytesIO, **kwargs: Any) Any[source]#

Send a document with a caption via sendDocument.

send_message(text: str, **kwargs: Any) Any[source]#

Send a text message via sendMessage.

class thinlog.handlers.telegram.TelegramHandlerSettings(token: str, chat_id: int | str, topic_id: int | str | None = None, level: str | int = 0, timeout: int = 5, disable_notification: bool = False, disable_web_page_preview: bool = True, proxy: str | None = None)[source]#

Bases: object

Settings for TelegramHandler.

The first instance created is stored as a global singleton accessible via global_instance().

Parameters:
  • token – Telegram Bot API token.

  • chat_id – Target chat ID (group, channel, or user).

  • topic_id – Optional forum topic (message thread) ID.

  • level – Minimum log level (name or int).

  • timeout – HTTP request timeout in seconds.

  • disable_notification – Send silently.

  • disable_web_page_preview – Disable link previews in messages.

  • proxy – Optional HTTP proxy URL.

chat_id: int | str#
disable_notification: bool = False#
disable_web_page_preview: bool = True#
classmethod global_instance() TelegramHandlerSettings | None[source]#

Return the first-created settings instance, or None.

level: str | int = 0#
proxy: str | None = None#
timeout: int = 5#
token: str#
topic_id: int | str | None = None#