Skip to main content
Pre-release

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

TeleKit

PyPI Python PyPI Downloads

Telekit

Telekit is a declarative, developer-friendly framework for building Telegram bots. It gives developers a dedicated Sender for composing and sending messages and a Chain for handling dialogue between the user and the bot. The framework also handles inline keyboards and callback routing automatically, letting you focus on the bot's behavior instead of repetitive tasks.

import telekit

class MyStartHandler(telekit.Handler):
    @classmethod
    def init_handler(cls):
        cls.on.command('start').invoke(cls.handle_start)

    def handle_start(self):
        self.chain.sender.set_text("Hello!")
        self.chain.sender.set_photo("robot.png")
        self.chain.send()

TOKEN: str = telekit.utils.read_token(".env")

telekit.Server(TOKEN).polling()

Send "Hello!" with a photo on /start

Telekit comes with a built-in DSL, allowing developers to create fully interactive bots with minimal code. It also integrates Jinja, giving you loops, conditionals, expressions, and filters to generate dynamic content.

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

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

See the full example

Even in its beta stage, Telekit accelerates bot development, offering typed command parameters, text styling via Bold(), Italic(), a built-in declarative calendar picker (!), emoji game results for 🎲 🎯 🏀 ⚽ 🎳 🎰, and much more out of the box. Its declarative design makes bots easier to read, maintain, and extend.

Key features:

  • Chains handle complex conversations without state machines
  • Ready-to-use DSL for FAQs and interactive scripts
  • Automatic message formatting via Sender and callback routing
  • Automatic file_id caching: local files are uploaded once and reused afterwards
  • Deep Linking with type-checked Command Parameters
  • Built-in Permission and Logging system
  • Reusable Traits for pluggable behavior modules
  • Works with pyTelegramBotAPI

GitHub PyPI Telegram Community

Contents

Overview

In Telekit, dialogs read like normal method calls. You point to the next step. Telekit calls it when the user replies.

Entries

No state machines. Just tell Telekit which method should handle the next user message.

def handle(self):
    self.chain.sender.set_text("👋 Hello! What is your name?")
    self.chain.set_entry_text(self.handle_name)
    self.chain.send()

def handle_name(self, name: str):
    self.chain.sender.set_text(f"Nice to meet you, {name}!")
    self.chain.send()

handle sends a message and registers handle_name as the next step with set_entry_text. When the user replies, Telekit calls handle_name and passes the reply as a plain str.

That's it. No enums. No manual state tracking. No boilerplate.

Inline Keyboards

The fastest way to add buttons to a message. Pass a dict where each key is the button label and each value is the callback to run when pressed:

self.chain.set_inline_keyboard(
    {
        "✏️ Change": self.change_name,
        "❌ Delete": self.delete,
    }
)

row_width controls how many buttons appear per row:

self.chain.set_inline_keyboard(
    {
        "One":   self.one,
        "Two":   self.two,
        "Three": self.three,
        "Four":  self.four,
        "Five":  self.five,
    },
    row_width=(3, 2)  # first row: 3 buttons, second row: 2
)
╭──────────┬──────────┬──────────╮
│   One    │   Two    │  Three   │
├──────────┴──┬───────┴──────────┤
│    Four     │       Five       │
╰─────────────┴──────────────────╯

For precise row layout or conditional buttons, use InlineKeyboard, a builder you compose step by step:

self.chain.set_keyboard(
    InlineKeyboard()
        .add_callback("-", self.decrement, style="danger")
        .add_callback("+", self.increment, style="success")
    .row()
        .add_callback("↺ Reset", self.reset)
)
╭──────────┬──────────╮
│    -     │    +     │
├──────────┴──────────┤
│       ↺ Reset       │
╰─────────────────────╯

InlineKeyboard is built by chaining method calls. Just call .row() to start a new row.

Not just callback buttons

Method Description
add_callback(...) Button that fires a callback function.
add_link(...) Button that opens a URL.
add_copy(...) Button that copies text to the clipboard.
add_alert(...) Button that shows a popup alert dialog.
add_notification(...) Button that shows a brief top-of-chat notification.
add_static(...) Decorative button with no action.
add_webapp(...) Button that opens a Telegram Mini App.
add_suggest(...) Button that simulates the user sending a message.

Reply Keyboards

Reply keyboards replace the system keyboard with buttons at the bottom of the chat. Tapping one sends its text as a message, or triggers a system action like sharing a phone number or location.

self.chain.set_keyboard(
    ReplyKeyboard(one_time_keyboard=True)
        .add_text("Hello!")
        .add_text("Hi")
    .row()
        .add_contact("📱 Share phone")
        .add_location("📍 Share location")
)

Command Parameters

Telekit can parse and validate command parameters for you.

from telekit.parameters import *

class GreetHandler(telekit.Handler):
    @classmethod
    def init_handler(cls) -> None:
        cls.on.command("greet", params=[Int(), Str()]).invoke(cls.handle)

    def handle(self, age: int | None = None, name: str | None = None):
        if age is None or name is None:
            self.chain.sender.set_text("Usage: /greet <age> <name>")
        else:
            self.chain.sender.set_text(f"Hello, {name}! You are {age} years old. Next year you'll turn {age + 1} 😅")
        self.chain.send()

Now /greet 128 Dracula or even /greet 64 "Alice Reingold" are parsed automatically.

Dialogue

Dialogs are built as a chain of steps. Each method waits for the user before continuing.

class DialogueHandler(telekit.Handler):

    @classmethod
    def init_handler(cls) -> None:
        cls.on.text("hello", "hi", "hey").invoke(cls.handle_hello)

    def handle_hello(self) -> None:
        self.chain.sender.set_text("👋 Hello! What is your name?")
        if self.user.first_name:
            self.chain.set_entry_suggestions([self.user.first_name])
        self.chain.set_entry_text(self.handle_name)
        self.chain.send()

    def handle_name(self, name: str) -> None:
        self.user_name = name
        self.chain.sender.set_text("Nice! How are you feeling today?")
        self.chain.set_entry_text(self.handle_feeling)
        self.chain.send()

    def handle_feeling(self, feeling: str) -> None:
        self.chain.sender.set_text(f"Got it, {self.user_name.title()}! You feel: {feeling}")
        self.chain.set_inline_keyboard({"↺ Restart": self.handle_hello})
        self.chain.send()

How it works:

  • The handler reacts to "hello", "hi", or "hey" in any case.
  • handle_hello asks for the user's name.ч
  • set_entry_suggestions attaches the user's Telegram first_name as a suggestion button.
  • handle_name stores the name in self.user_name.
  • handle_feeling closes the flow and adds a "↺ Restart" button that routes back to the start.

It reads like regular Python because it is regular Python.

Sender

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

self.chain.sender.set_effect(Effect.HEART) # Add effect to message. Use enum or string
self.chain.sender.set_photo("robot.png") # Attach photo. URL, file_id, or path
self.chain.sender.set_document("README.md") # Attach document. URL, file_id, or path
self.chain.sender.set_text_as_document("Hello, this is a text document!") # Convert string to text document
self.chain.sender.send_chat_action(ChatAction.TYPING) # Send chat action. Use enum or string

Local files are uploaded to Telegram once. Telekit stores the returned file_id in a database and reuses it on every next send, so repeated messages with the same photo, document or video go out almost instantly.

Styles

Describe formatting as objects instead of writing raw HTML or Markdown.

from telekit.styles import *

def handle(self) -> None:
    self.chain.sender.set_text(
        Bold("Text style examples:\n"),
        Stack(
            Bold("Bold text"),
            Italic("Italic text"),
            Bold(Italic("Bold + italic")),
            Link("Link", url="https://example.com"),
            BotLink("Deep link", username="MyBot", start="promo_42"),
            start="- {{index}}. ",
            sep=".\n",
        )
    )
    self.chain.send()

You describe structure. Telekit turns that structure into HTML or MarkdownV2:

<b>Text style examples:</b>

- 1. <b>Bold text</b>.
- 2. <i>Italic text</i>.
- 3. <b><i>Bold + italic</i></b>.
- 4. <a href="https://example.com">Link</a>.
- 5. <a href="https://t.me/MyBot?start=promo_42">Deep link</a>

You skip manual escaping and the broken formatting one stray character causes.

Telekit DSL

Prefer not to write dialog logic in Python? Use the built-in DSL with Jinja support.

import telekit

class QuizHandler(telekit.DSLHandler):
    @classmethod
    def init_handler(cls) -> None:
        cls.analyze_string(script)
        cls.on.command("start").invoke(cls.start_script)

script = """
$ timeout {
    time = 20; // 20 sec.
}

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

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

@ question_1 {
    title   = "🐶 Question 1";
    message = "Which animal is the fastest on land?";
    buttons {
        _lose("Elephant");
        next("Cheetah");       // correct answer
        _lose("Horse");
        _lose("Lion");
    }
}

/* ... */
"""

telekit.Server(BOT_TOKEN).polling()

Key features of the Telekit DSL:

  • Scene-based architecture
  • Anonymous scenes
  • Automatic navigation stack management
  • Input handling
  • Images support and link buttons
  • Template variables
  • Custom variables
  • Hooks (Python API integration)
  • Jinja template engine
🎆 Click to see what you can do with the DSL
Telekit Example 7 Telekit Example 8
Telekit Example 7 Telekit Example 8

Traits

Traits are reusable behavior modules you can mix into any handler.

Here's the built-in CalendarPick trait: a user picks a date from an inline calendar, and a callback handles the result.

from telekit.traits import CalendarPick

class CalendarHandler(CalendarPick, telekit.Handler):

    @classmethod
    def init_handler(cls) -> None:
        cls.on.command("calendar").invoke(cls.handle)

    def handle(self) -> None:
        self.chain.sender.set_title("📅 Choose a date")
        self.chain.sender.set_message("Select any date — past or future:")
        self.chain.sender.set_remove_text(False)

        self.calendar_pick(self.handle_date) # HERE

    def handle_date(self, date: datetime.date) -> None:
        self.chain.sender.set_text(f"You picked: {date}")
        self.chain.send()
Result
Telekit Calendar Example

Example Bot

Run this to launch an example bot:

import telekit

telekit.example(YOUR_BOT_TOKEN)

It includes example commands, dialogs, keyboards, and style usage.

Why Telekit

  • Chains instead of an FSM.
  • Declarative, behavior-focused bot logic with minimal boilerplate.
  • Automatic callback routing and input handling.
  • Automatic file_id caching for local files: no re-uploads, no manual bookkeeping.
  • Styles API for rich text (Bold, Italic, links) with automatic escaping.
  • Deep linking and typed command parameters.
  • Built-in DSL for menus, FAQs, and simple bots.
  • Reusable Traits for composable behavior, including a built-in calendar picker.
  • Zero-code mode Obsidian Canvas mode.
  • Works with pyTelegramBotAPI.

Telekit focuses on one job: making Telegram bot development easier.


Changelog

v2.6.0 a7

Server

  • Added restart parameter to Server: "always" (default), "network" or "never"; accepts RestartMode or the matching string
  • Deprecated Server(auto_restart=...): True is now restart="always", False is restart="never"; emits DeprecationWarning and a log warning. Cannot be combined with restart (TypeError)
  • Added network protection to Server.polling() and Server.long_polling(): restarts are now delayed by exponential backoff (5 s up to 60 s, reset after 120 s of stable work) instead of a fixed 10 s / 5 s. Tunable via Server.RESTART_DELAY_MIN, RESTART_DELAY_MAX and STABLE_AFTER
  • Added restart="network": survives only network errors and Bot API 429, 500, 502, 503, 504; any other error (bad token, 409 conflict, bugs) is re-raised. retry_after from Telegram is respected
  • Changed Server.__init__() to wait for the Bot API to become reachable before calling getMe (skipped for restart="never" and when apihelper.proxy is set)
  • Fixed Server.polling() and Server.long_polling() restarting after stop_polling(): they now return instead
  • Fixed a failed getMe in the restart cycle killing the server and hiding the original error
  • Fixed bot tokens leaking into logs through request URLs: they are now masked as bot<hidden>
  • Changed log levels in Server: network errors are logged as WARNING (without traceback), unexpected errors as ERROR (with traceback), FATAL is kept for [server dead].

Logging

  • Added Rich output for logs when rich is installed; set TELEKIT_NO_RICH=1 to disable it
  • Added direct exports server_logger, library_logger, user_logger and get_user_logger() to _logger.py. logger.server, logger.library, logger.users(), _server and _library still work
  • Added set_level(), disable_user_logging() and UserLogger.exception()
  • Changed telekit loggers to propagate=False: records no longer reach the root logger, so they are not duplicated when the app configures it. Attach custom handlers to logging.getLogger("telekit")
  • Changed enable_file_logging() to be idempotent, to create parent folders, and to use one format (with filename:lineno) for all files, including server.log
  • Fixed UserLogger reporting its own module as the log source

Sender

  • Added a FileIdCache that stores Telegram file_id for local files (photo, document, video, animation, audio, voice, video note), so repeated sends skip the upload
  • Added BaseSender.configure_file_cache(): a class method that sets the database path, table name and global on/off switch
  • Added Sender.set_use_file_cache(): a per-sender override of the global setting (None restores it)
  • Changed missing local files to raise on send() instead of in the setter
  • A rejected cached file_id is dropped and the send is retried with the original file
  • Notes: URLs, bytes and file-like objects are not cached; rich messages and media groups are unaffected. A changed file is detected by size/mtime, with a SHA-256 comparison as a fallback

v2.6.0 a6 (fixes #6)

  • Reworked the timeout engine to fix thread exhaustion with many concurrent chats (#6): every set_timeout() used to start its own threading.Timer (one OS thread per waiting chat), so ~1000 active users crashed the bot with can't start new thread
  • Timeout callback exceptions are now logged
  • Added configure_timeouts(max_workers, *, idle_timeout, log_worker_changes, warn_on_max_workers) to tune the worker pool, log worker start/stop, and control the "all workers busy" warning (enabled by default)

v2.6.0 a4

  • Added handle_handoff() to Handler: a shortcut for handoff(handler).handle() that takes the target handler as an argument, so it can be passed to add_callback() without an extra closure
  • Added handle_handoff_back_or() to TrackHandoffOrigin: a closure-free counterpart of handoff_back_or()
  • Reworked handoff_back_or() as a thin functools.partial wrapper around handle_handoff_back_or()
  • Fixed the handoff_back_or() docstring: the returned callable forwards its arguments to handle() instead of being zero-argument
  • Converted the handoff() docstring to reST

v2.6.0 a3

  • Added support for Rich HTML messages (Bot API 10.1+)
  • Added the _rich.py module for Rich HTML parsing and serialization
  • Added new rich tags to styles.py for enhanced text formatting
  • Added the rich.py example handler demonstrating Rich HTML: inline styles, blocks, lists, tables, media, and sender integration

v2.6.0 a2

  • Reworked .env and token/canvas file reading in utils
  • Added full .env syntax support: comments, export, quotes and escapes, multi-line values, $VAR interpolation
  • Added the cache parameter (default True) and clear_cache()
  • Added detailed errors with fix suggestions and creation commands, and new Env*Error exceptions
  • Changed load_env() to raise EnvFileNotFoundError for a missing file instead of returning {}

v2.6.0 a1

  • Added a module-loading utility to utils

v2.6.0 a0

  • Improved formatting in _on.py

Metadata

Release files for telekit 2.6.0a7

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

Source distribution (sdist)

Source distribution for telekit 2.6.0a7
File Size Uploaded Provenance Actions
telekit-2.6.0a7.tar.gz 205.7 kB Without provenance Details for telekit-2.6.0a7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for telekit 2.6.0a7
File Interpreter ABI Platform Actions
telekit-2.6.0a7-py3-none-any.whl Python 3 none any Details for telekit-2.6.0a7-py3-none-any.whl

Total release size: 435.1 kB

Release files / telekit-2.6.0a7.tar.gz

Download URL telekit-2.6.0a7.tar.gz
Size 205.7 kB
Tags Source
SHA-256 checksum
How to use checksums
489bcd47e9627b5d193b97dcb9356712da5183c22ff79c08e004b6d85d3eec9f
BLAKE2b-256 checksum
How to use checksums
eec4f1a0a21ce1babd2f110c46657441c091c0af324c31cb6b45be9c9da91a6e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.11

Release files / telekit-2.6.0a7-py3-none-any.whl

Download URL telekit-2.6.0a7-py3-none-any.whl
Size 229.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2338941e37e23293ce99a2328989b2fbcf83e48387bc9e02a8552480812c72f4
BLAKE2b-256 checksum
How to use checksums
4f5bf7964b0d4594c67ebaad1b7eb90f5700d2b88a53343215096854aa7dcf60
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.11

Security for telekit 2.6.0a7

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.

Release history Release notifications | RSS feed

This release
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