Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Python TelegramBots

A pure and modern python package to communicate with telegram bot api.

About

This is an async wrapper over telegram bot api written using python ( + 3.10 ).

This package tries to be close to the bot api interface and there are almost nothing more than it. Of course the package is extendable and other features can be installed separately.

  • All objects and methods ( 6.0 ) are implemented in python using dataclasses.

  • Serialization stuff are done to convert api python objects to json-like (dict, list) objects and then json-string and reverse.

  • A simple and async http client is available that uses aiohttp to send requests.

This package contains no full-featured client or bound methods! there're only some classes and a client.

Consider

This a raw wrapper! To add more functionality, you can use custom-telegrambots.

These two can be installed together ( and they should ).

How to

All api methods are available under following namespace:

telegrambots.wrapper.types.methods

And for objects

telegrambots.wrapper.types.methods

Make a request

You can use our async client to make requests.

import asyncio

from telegrambots.wrapper import TelegramBotsClient
from telegrambots.wrapper.types.methods import SendMessage
from telegrambots.wrapper.types.objects import (
    InlineKeyboardButton,
    InlineKeyboardMarkup,
)


async def main():
    client = TelegramBotsClient("BOT_TOKEN")

    message = await client(
        SendMessage(
            123456789,
            "Here is a message from python-telegrambots",
            reply_markup=InlineKeyboardMarkup(
                InlineKeyboardButton.with_url(
                    "Repo", "https://github.com/python-telegrambots"
                )
            ),
        )
    )

    print(message.message_id)


if __name__ == "__main__":
    asyncio.run(main())

Everything is documented and well type hinted.

Send a file or even multiple files ( local or online ).

import asyncio
from pathlib import Path

from telegrambots.wrapper import TelegramBotsClient
from telegrambots.wrapper.types.methods import SendMediaGroup
from telegrambots.wrapper.types.objects import InputFile, InputMediaPhoto


async def main():
    client = TelegramBotsClient("BOT_TOKEN")

    file_path_1 = Path(__file__).parent.resolve().joinpath("test_photo_1.jpg")
    file_path_2 = Path(__file__).parent.resolve().joinpath("test_photo_2.jpg")

    with InputFile(file_path_1) as file: # You need to open files manually if you're using Path.
        with SendMediaGroup( # All sub files will be closed after this
            123456789,
            [
                InputMediaPhoto(file, "My first photo"),
                InputMediaPhoto(InputFile(open(file_path_2, "rb"), "test_photo_2.jpg")), # Directly open and use file.
                InputMediaPhoto("https://imgur.com/t/funny/MpMGFRQ"),
            ],
        ) as send_media_group:
            result = await client(send_media_group)

            print(result.__len__())


if __name__ == "__main__":
    asyncio.run(main())

Send multiple requests using one aiohttp.ClientSession.

import asyncio

from telegrambots.wrapper import TelegramBotsClient
from telegrambots.wrapper.types.methods import (
    SendMessage,
    EditMessageText,
    DeleteMessage,
)


async def main():
    client = TelegramBotsClient("BOT_TOKEN")

    async with client:

        message = await client(
            SendMessage(12345678, "It's a long time that want to say ... I love you.")
        )

        edited_message = await client(
            EditMessageText(
                chat_id=message.chat.id,
                message_id=message.message_id,
                text="Oh sorry, how are you today??!",
            )
        )

        assert edited_message

        await client(
            DeleteMessage(
                chat_id=edited_message.chat.id, message_id=edited_message.message_id
            )
        )


if __name__ == "__main__":
    asyncio.run(main())

Print things! usual way or pretty.

import asyncio

from telegrambots.wrapper import TelegramBotsClient
from telegrambots.wrapper.types.methods import SendMessage


async def main():
    client = TelegramBotsClient("BOT_TOKEN")

    async with client:

        message = await client(SendMessage(12345678, "It's Show Time."))

        # let's see what we got.
        print(message)
        # Message(message_id=134, date=1651407978, chat=Chat(id=106296897, ...
        # ---- A long story here ----

        # make it more clear
        print(message.pretty_str())
        # {
        #     "chat": {
        #         "first_name": "A̤̮ʀαՏH",
        #         "id": 12345678,
        #         "type": "private"
        #     },
        #     "date": 1651407978,
        #     "from": {
        #         "first_name": "TelegramBots Test",
        #         "id": 87654321,
        #         "is_bot": true,
        #         "username": "TestBot"
        #     },
        #     "message_id": 134,
        #     "text": "It's Show Time."
        # }

if __name__ == "__main__":
    asyncio.run(main())

Manually serialize or deserialize any object.

import json
from telegrambots.wrapper.types.objects import Update
from telegrambots.wrapper.serializations import serialize, deserialize

json_object = """
{
    "update_id":10000,
    "callback_query": {
        "id": "4382bfdwdsb323b2d9",
        "from": {
            "last_name":"Test Lastname",
            "type": "private",
            "id":1111111,
            "first_name":"Test Firstname",
            "username":"Testusername",
            "is_bot":false
        },
        "chat_instance":"4382bfdwdsb323b2d9",
        "data": "Data from button callback",
        "inline_message_id": "1234csdbsk4839"
    }
}
"""

update = deserialize(Update, json.loads(json_object))  # type of Update

dict_like = json.dumps(serialize(update))

print(dict_like)
# {'update_id': 10000, 'callback_query': {'id': '4382bfdwdsb323b2d9', 'from': {'id': 1111111, 'is_bot': False, 'first_name': 'Test Firstname', 'last_name': 'Test Lastname', 'username': 'Testusername'}, 'chat_instance': '4382bfdwdsb323b2d9', 'inline_message_id': '1234csdbsk4839', 'data': 'Data from button callback'}}

Install

The preview package is available at PYPI.

Metadata

Release files for telegrambots 0.0.13rc0

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

Source distribution (sdist)

Source distribution for telegrambots 0.0.13rc0
File Size Uploaded Provenance Actions
telegrambots-0.0.13rc0.tar.gz 85.8 kB Without provenance Details for telegrambots-0.0.13rc0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for telegrambots 0.0.13rc0
File Interpreter ABI Platform Actions
telegrambots-0.0.13rc0-py3-none-any.whl Python 3 none any Details for telegrambots-0.0.13rc0-py3-none-any.whl

Total release size: 321.7 kB

Release files / telegrambots-0.0.13rc0.tar.gz

Download URL telegrambots-0.0.13rc0.tar.gz
Size 85.8 kB
Tags Source
SHA-256 checksum
How to use checksums
05d6eb778ca61bfd47ed7006de93e2314f944f8f15b2cc698d66981a395d1462
BLAKE2b-256 checksum
How to use checksums
92a140963b8d32e6fe7766aadfef5a95c9aa76ea720008ec138a02323d0a7474
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.0 CPython/3.9.12

Release files / telegrambots-0.0.13rc0-py3-none-any.whl

Download URL telegrambots-0.0.13rc0-py3-none-any.whl
Size 236.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
35e03d39bbef751a50fe88b2401237c905e43f95435ce8e3790c17f2ddd3cf92
BLAKE2b-256 checksum
How to use checksums
2bec38103c3afedaeeb0da929f17dd4ca984b2cfa1ff990998027d6fedea12df
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.0 CPython/3.9.12

Security for telegrambots 0.0.13rc0

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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