Skip to main content

Telegram Bot Logger

PyPI Version Python Version

Telegram Bot Logger is a Python library that allows you to send logging logs to Telegram using the Bot API. It simplifies the process of integrating Telegram bot notifications into your Python applications, making it easy to monitor and manage your application's logs.

screenshot

Installation

You can install telegram_bot_logger using pip:

pip install telegram-bot-logger

Usage

Replace YOUR_BOT_TOKEN and chat_ids with your actual bot token and chat IDs. You can obtain a bot token by creating a new bot on Telegram and obtaining it from the BotFather.

import telegram_bot_logger

import logging


logger = logging.getLogger("telegram_bot_logger_example")

handler = telegram_bot_logger.TelegramMessageHandler(
    bot_token = "YOUR_BOT_TOKEN",  # Required; bot's token from @BotFather
    chat_ids = [
        12345678,
        -1001234567890,  # For group chat id, make sure you pass the chat id as integer
        "@username"
    ],  # Required; you can pass id as integer or username as string
    api_server = telegram_bot_logger.api_server.TelegramAPIServer(
        base = "https://api.telegram.org/bot{bot_token}/{method}"
    ),  # Optional; set by default
    format_type = "text" or "TEXT" or telegram_bot_logger.formatters.FormatType.TEXT,  # Optional; also can be "DOCUMENT", by default it is "TEXT"
    document_name_strategy = "timestamp" or "TIMESTAMP" or telegram_bot_logger.formatters.DocumentNameStrategy.TIMESTAMP,  # Optional; used to define documents' names; also can be "ARGUMENT", by default it is "TIMESTAMP"
    proxies = {
        "http://": "http://localhost:8080"
    } or "http://localhost:8080",  # Optional; "dict[scheme, url]" or just "url", please see httpx's supported proxy types
    formatter = formatters.TelegramHTMLTextFormatter(),  # Optional; you can create your own class inherited from formatters.TelegramBaseFormatter and pass it
    additional_body = {
        "reply_to_message_id": 1
    }  # Optional; additional request body on sendMessage and sendDocument
)

logger.setLevel(logging.DEBUG)

logger.addHandler(handler)


logger.debug("debug-message")
# Or:
logger.debug("debug-message", extra={"document_name": 123})  # 123 is an argument; to use this feature you need to set `format_type = formatters.FormatType.DOCUMENT` and `document_name_strategy = formatters.DocumentNameStrategy.ARGUMENT` while initiating TelegramMessageHandler

It is highly recommend using string formatters in log messages, as these are not expanded if the logging level is not high enough, making difference in performance critical applications:

# Use string formatter to avoid formatting an excessive log message argument 
long_list = list(range(1000))
logger.info("My long list is: %s", long_list)

You can also show tracebacks:

try:
    raise RuntimeError("Ooops I did it again")
except Exception as e:
    logger.exception(e)

screenshot-exception

Closing the handler

This logging handler creates a daemon background thread, as it uses Python's internal QueueHandler. The thread is closed with Python's atexit handler. However for some applications, like pytest, to cleanly shut down, you may need to shutdown the handler manually.

# Release any background threads created by the Telegram logging handler
handler.close()

More examples

Here is an example how to customise Telegram output a bit:

import logging
import telegram_bot_logger
from telegram_bot_logger.formatters import TelegramHTMLTextFormatter

# Fine tune our Telegram chat output
formatter = TelegramHTMLTextFormatter()
formatter._EMOTICONS[logging.DEBUG] = "📜"  # Patch in the emoticon by logging level
formatter._TAG_FORMAT = ""  # Disable tags in the output
formatter._HEADER_FORMAT = "<pre>{emoticon} {message}{description}</pre>"  # Disable line number and module name in the output

telegram_handler = telegram_bot_logger.TelegramMessageHandler(
    bot_token = "YOUR_BOT_TOKEN",
    chat_ids = [
        -1001234567890,
    ],
    format_type = "text",
    formatter = formatter,
    level = logging.INFO
)

logging.getLogger().addHandler(telegram_handler)

Stay Updated

For the latest news and updates, follow my Telegram Channel.

Metadata

Release files for telegram-bot-logger 0.0.4.post0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for telegram-bot-logger 0.0.4.post0
File Size Uploaded Provenance Actions
telegram_bot_logger-0.0.4.post0.tar.gz 9.3 kB With provenance Details for telegram_bot_logger-0.0.4.post0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for telegram-bot-logger 0.0.4.post0
File Interpreter ABI Platform Actions
telegram_bot_logger-0.0.4.post0-py3-none-any.whl Python 3 none any Details for telegram_bot_logger-0.0.4.post0-py3-none-any.whl

Total release size: 18.1 kB

Release files / telegram_bot_logger-0.0.4.post0.tar.gz

Download URL telegram_bot_logger-0.0.4.post0.tar.gz
Size 9.3 kB
Tags Source
SHA-256 checksum
How to use checksums
ffebfe5c8abff27e86bece99d42a774afee564ba46e48181deac3901d0ea9e7e
BLAKE2b-256 checksum
How to use checksums
b37e8b5d376b5234ebf7fdcde62e22fb6dc8a4bb51897293a5471c21ddfacec7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Feb 6, 2025.

Transparency log

Release files / telegram_bot_logger-0.0.4.post0-py3-none-any.whl

Download URL telegram_bot_logger-0.0.4.post0-py3-none-any.whl
Size 8.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
917ecf8903aea0f49419b1e4bfb82fcc2b721f38c57c643d4f6b48559c40e02c
BLAKE2b-256 checksum
How to use checksums
0fce8bd35a661129ae73afcfa4aa0995f1615652cd148afdea1eef5060506da6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Feb 6, 2025.

Transparency log

Security for telegram-bot-logger 0.0.4.post0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for telegram_bot_logger-0.0.4.post0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Feb 6, 2025.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page