Skip to main content

Declarative, developer-friendly library for building Telegram bots

Project description

TeleKit

TeleKit Library

Telekit is a declarative, developer-friendly library for building Telegram bots. It streamlines common bot operations, automates routine tasks, and provides a clear, structured way to implement complex logic without boilerplate.

Telekit comes with a built-in DSL for defining scenes, menus, FAQ pages, and multi-step flows, allowing developers to create fully interactive bots with minimal code. The library also handles message formatting, user input, and callback routing automatically, letting you focus on the bot’s behavior instead of repetitive tasks.

self.chain.sender.set_text(Bold("Hello world!"))
self.chain.sender.set_photo("robot.png")
self.chain.set_inline_keyboard({"👋 Hello, Bot": self.handle_greeting})
self.chain.send()

Example taken out of context

@ main {
    title   = "🎉 Fun Facts Quiz";
    message = "Test your knowledge with 10 fun questions!";

    buttons {
        question_1("Start Quiz");
    }
}

@ question_1 {
    ...
}

Telekit DSL example

Even in its beta stage, Telekit accelerates bot development, offering ready-to-use building blocks for commands, user interactions, and navigation. Its declarative design makes bots easier to read, maintain, and extend.

Key features:

  • Declarative bot logic with chains for effortless handling of complex workflows
  • Ready-to-use DSL for FAQs and other interactive scripts
  • Automatic handling of message formatting via Sender and callback routing
  • Lightweight, maintainable, and easy-to-extend code

GitHub PyPi Community Tutorial

Contents

Overview

To get the most out of Telekit, we recommend following the full, step-by-step tutorial that covers everything from installation to advanced features and DSL usage.

Even if you don’t go through the entire guide right now, you can quickly familiarize yourself with the core concepts, key building blocks, and basic workflows of Telekit below. This section will introduce you to chains, handlers, message formatting, and some examples, giving you a solid foundation to start building bots right away.

Below is an example of a bot that responds to messages like "My name is {name}":

import telekit

class NameHandler(telekit.Handler):

    @classmethod
    def init_handler(cls) -> None:
        cls.on.text("My name is {name}").invoke(cls.display_name)

    def display_name(self, name: str) -> None:
        self.chain.sender.set_title(f"Hello {name}!")
        self.chain.sender.set_message("Your name has been set. You can change it below if you want")
        self.chain.set_inline_keyboard({"✏️ Change": self.change_name})
        self.chain.edit()

    def change_name(self):
        self.chain.sender.set_title("⌨️ Enter your name...")
        self.chain.sender.set_message("Please, type your new name below:")

        @self.chain.entry_text(delete_user_response=True)
        def name_handler(message, name: str):
            self.display_name(name)

        self.chain.edit()

telekit.Server("TOKEN").polling()

Let’s see how it works in practice 👇

Message formatting:

  • You can configure everything manually:
self.chain.sender.set_text("*Hello, user!*\n\nWelcome to the Bot!")
self.chain.sender.set_parse_mode("markdown")
  • Or let Telekit handle the layout for you:
self.chain.sender.set_title("👋 Hello, user!") # Bold title
self.chain.sender.set_message("Welcome to the Bot!")  # Italic message after the title

Approximate result:

👋 Hello, user!

Welcome to the Bot!

If you want more control, you can use the following methods:

self.chain.sender.set_use_italics(False)
self.chain.sender.set_use_newline(False)
self.chain.sender.set_parse_mode("HTML")
self.chain.sender.set_reply_to(message)
self.chain.sender.set_chat_id(chat_id)

# And this is just the beginning...

Want to add an image or an effect in a single line?

self.chain.sender.set_effect(self.chain.sender.Effect.HEART)
self.chain.sender.set_photo("url, bytes or path")

Telekit decides whether to use bot.send_message or bot.send_photo automatically!

Text Styling with Styles

Telekit provides a convenient style classes to create styled text objects for HTML or Markdown:

Bold("Bold") + " and " + Italic("Italic")

Combine multiple styles:

Strikethrough(Bold("Hello") + Italic("World!"))

Then pass it to set_text, set_title, or other sender methods, and the sender will automatically determine the correct parse_mode.

For more details, see our tutorial

Handling callbacks and Logic

If your focus is on logic and functionality, Telekit is the ideal library:

Inline keyboard with callback support:

# Inline keyboard `label-callback`:
# - label:    `str`
# - callback: `Chain` | `str` | `func()` | `func(message)`
self.chain.set_inline_keyboard(
    {
        "« Change": prompt,  # Executes `prompt()` when clicked
        "Yes »": lambda: print("User: Okay!"),  # Runs this lambda when clicked
        "Youtube": "https://youtube.com"  # Opens a link
    }, row_width=2
)

# Inline keyboard `label-value`:
# - label: `str`
# - value: `Any`
@self.chain.inline_keyboard({
    "Red": (255, 0, 0),
    "Green": (0, 255, 0),
    "Blue": (0, 0, 255),
}, row_width=3)
def _(message, value: tuple[int, int, int]) -> None:
    r, g, b = value
    self.chain.set_message(f"You selected RGB color: ({r}, {g}, {b})")
    self.chain.edit()

Receiving messages with callback support:

# Receive any message type:
@self.chain.entry(
    filter_message=lambda message: bool(message.text),
    delete_user_response=True
)
def handler(message):
    print(message.text)

# Receive text message:
@self.chain.entry_text()
def name_handler(message, name: str):
    print(name)

# Inline keyboard with suggested options:
chain.set_entry_suggestions(["Suggestion 1", "Suggestion 2"])

# Receive a .zip document:
@self.chain.entry_document(allowed_extensions=(".zip",))
def doc_handler(message: telebot.types.Message, document: telebot.types.Document):
    print(document.file_name, document)

# Receive a text document (Telekit auto-detects encoding):
@self.chain.entry_text_document(allowed_extensions=(".txt", ".js", ".py"))
def text_document_handler(message, text_document: telekit.types.TextDocument):
    print(
        text_document.text,      # "Example\n ..."
        text_document.file_name, # "example.txt"
        text_document.encoding,  # "utf-8"
        text_document.document   # <telebot.types.Document>
    )

Telekit is lightweight yet powerful, giving you a full set of built-in tools and solutions for building advanced Telegram bots effortlessly.

  • You can find more information about the decorators by checking their doc-strings in Python.

Quick Start

Telekit is published in PyPI, so it can be installed with one command:

pip install telekit

You can write the entire bot in a single file, but it’s recommended to organize your project using a simple structure like this one:

handlers/
    __init__.py
    start.py    # `/start` handler
    help.py     # `/help` handler
    ...
server.py       # entry point

Here is a server.py example (entry point) for a project on TeleKit

import telekit
import handlers # Package with all your handlers

telekit.Server("BOT_TOKEN").polling()

Here you can see an example of the handlers/__init__.py file:

from . import (
    start, help #, ...
)

Here is an example of defining a handler using TeleKit (handlers/start.py file):

import telekit

class StartHandler(telekit.Handler):

    @classmethod
    def init_handler(cls) -> None:
        ...

One-file bot example (Echo Bot):

import telekit

class EchoHandler(telekit.Handler):

    @classmethod
    def init_handler(cls) -> None:
        cls.on.text().invoke(cls.echo) # accepts all text messages

    def echo(self) -> None:
        self.chain.sender.set_text(f"{self.message.text}!")
        self.chain.send()

telekit.Server("TOKEN").polling()

For a full walkthrough, check out our tutorial or see Examples


Developer

Telegram: Romashka

Gravatar: Romashka

Community


Changelog:

1.2.0

✅ New Features

Sender Improvements

  • set_document method - sets a file object (any document) to be sent to the user.
  • set_text_as_document method - converts text into a temporary document (BytesIO) and sets it for sending.
  • set_video method - sets the video for the message.
  • set_video_note method — sets a video note (round video) for the message.
  • set_animation method - sets the animation for the message.
  • set_audio method — sets an audio file (music) for the message.
  • set_voice method — sets a voice message (OGG) for the message.
  • remove_attachments method - clears all attachments from the message or object, resetting photo, media, and document
  • ChatAction and send_chat_action for chat action support.

Handler Improvements

Chain Improvements

DSL Improvements

  • Added support for {{variables}} in title= and message=.
    • HTML and Markdown tags in variable values are automatically sanitized.
    • Recursive variable replacement is prevented (only first-level substitution is performed).
    • Example: (<b>username</b> - bold; {{first_name}} and {{username}} - sanitized>)
@ main {
    title = "Welcome, {{first_name:user}}!"; // "user" is default value
    message = "Did you know your <b>username</b> is {{username}}? Cool, isn't it?";
    parse_mode = "html";
}
  • Improved indentation handling in multiline strings.
  • display_script_data() method. Prints the semantic model of the script to the console.
  • Mixin refactor.

⏳ Delayed

  • DSL warning for strings with too many buttons or excessive text
  • Localization support for self.user.enable_logging() (currently global)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

telekit-1.2.0.tar.gz (56.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

telekit-1.2.0-py3-none-any.whl (65.6 kB view details)

Uploaded Python 3

File details

Details for the file telekit-1.2.0.tar.gz.

File metadata

  • Download URL: telekit-1.2.0.tar.gz
  • Upload date:
  • Size: 56.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.11

File hashes

Hashes for telekit-1.2.0.tar.gz
Algorithm Hash digest
SHA256 b49b45dd9c6e99e45c684e67b95b7149d4efbd8f69fee5fb0de6f4c38a4bac6c
MD5 db90ab1762a8d358d54458dc240680d6
BLAKE2b-256 5c4dfd3c0bce7837836dd022d706126fcb38317881d44c5bd3996a007c5fbc8d

See more details on using hashes here.

File details

Details for the file telekit-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: telekit-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 65.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.11

File hashes

Hashes for telekit-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f6b100a146078d6a5cfcf3fc527e878f2fcff2be326d5a0bd79421e872e51672
MD5 da5db6881781f68b2d0272b233580826
BLAKE2b-256 b51297d2b3301ba64572b4642f15a04526e75a6a9495c69353a3bb4a0bc045ea

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page