Skip to main content
Shirdal Logo

One Python framework for Telegram bots and userbots. Write your handlers once, run them on the Bot API or on a native MTProto 2.0 client.

English | فارسی

PyPI Python CI License: LGPL v3


Why Shirdal

Telegram has two very different APIs, and most libraries only cover one of them. Switching means rewriting your bot.

Shirdal puts everything above the network layer (dispatcher, filters, context, FSM, middleware, scheduler, storage) behind a single TransportAdapter interface. Your handlers don't know or care what is underneath, so moving from a bot token to a user account is a one-line change.

   Handlers · Filters · FSM · Middleware · Scheduler · Plugins · Storage
                                  │
                           TransportAdapter
        ┌──────────────┬──────────┴────────┬──────────────────┐
        ▼              ▼                   ▼                  ▼
  BotAPIAdapter  NativeMTProtoAdapter  Telethon / Hydrogram  MockAdapter
  (HTTP + webhook)  (built-in MTProto 2.0)   (wrappers)      (offline tests)

Features

Framework

  • Typed Context with helpers such as reply, edit, react, pin, download, reply_media and typing
  • Composable filters (&, |, ~, regex, commands, callbacks)
  • Multi-step conversations with StatesGroup (FSM)
  • Middleware, @bot.every() scheduler, and MultiBot for running several accounts at once
  • Hot-reloadable plugins: edit a file in plugins/ and it reloads without a restart
  • Storage backends: SQLite, Redis, MySQL, plus EncryptedStorage for sensitive data
  • AntiFloodAdapter with automatic FLOOD_WAIT handling and per-chat pacing

Bot API

  • Dependency-free HTTP client with keep-alive (optional msgspec for faster JSON)
  • Built-in asyncio webhook server with secret-token verification and a /health endpoint
  • Support for recent Bot API features: colored buttons, custom emoji, rich messages, ephemeral replies, draft streaming, member tags and topics

Native MTProto 2.0

  • Pure Python implementation: TL codec and schema code generator, AES-256-IGE, key exchange, encrypted sessions, TCP transport
  • Login with code, 2FA password or bot token; DC migration; reconnects and update gap recovery
  • Peer cache, chunked parallel file upload and download
  • Optional Rust acceleration through shircrypt

Installation

pip install shirdal

Optional extras:

pip install "shirdal[fast]"       # uvloop + msgspec + shircrypt
pip install "shirdal[shircrypt]"  # Rust-accelerated AES-IGE
pip install "shirdal[telethon]"   # Telethon adapter
pip install "shirdal[hydrogram]"  # Hydrogram adapter
pip install "shirdal[redis]"      # Redis storage
pip install "shirdal[mysql]"      # MySQL storage

Requires Python 3.11 or newer.

Quick start

Bot API

import os
from shirdal import (
    BotAPIAdapter, ButtonStyle, Context, Shirdal,
    button, callback, command, incoming, inline_keyboard,
)

bot = Shirdal(BotAPIAdapter(os.environ["BOT_TOKEN"]))

@bot.on(incoming & command("start", prefix="/"))
async def start(ctx: Context) -> None:
    kb = inline_keyboard([[
        button("Approve", "act:ok", style=ButtonStyle.SUCCESS),
        button("Reject", "act:no", style=ButtonStyle.DANGER),
    ]])
    await ctx.reply("<b>Choose an action:</b>", reply_markup=kb)

@bot.on_callback(callback(prefix="act:"))
async def on_action(ctx: Context) -> None:
    await ctx.answer("Done")

if __name__ == "__main__":
    bot.run()

Userbot (native MTProto)

import os
from shirdal import Context, DeviceProfile, NativeMTProtoAdapter, Shirdal, command, outgoing

adapter = NativeMTProtoAdapter(
    int(os.environ["API_ID"]),
    os.environ["API_HASH"],
    session_path="account.sqlite",
    device=DeviceProfile.desktop(),
)

bot = Shirdal(adapter, plugins_dir="plugins", hot_reload=True)

@bot.on(command("ping") & outgoing)
async def ping(ctx: Context) -> None:
    await ctx.edit("Pong!", auto_delete=10)

if __name__ == "__main__":
    bot.run()

More runnable examples live in examples/.

Command line

shirdal new my_bot --adapter botapi   # scaffold a project (botapi, telethon, hydrogram, mock)
shirdal doctor                        # check Python version and optional dependencies
shirdal run main.py                   # run an entry script

Testing your bot

MockAdapter runs your handlers fully offline, with no network and no Telegram account. Push fake updates in, assert on what was sent out. The project's own test suite is built this way:

PYTHONPATH=src python3 -m unittest discover -s tests -v

Production notes

  • Enable logging to see which crypto backend is active at startup:
    import logging
    logging.basicConfig(level=logging.INFO)
    # shirdal 1.0.x started | crypto backend: shircrypt-rust (v1.0.x)
    
  • Use WebhookServer behind a reverse proxy (nginx, Caddy) and always set a secret token.
  • Keep .sqlite session files private. They contain your account's authorization key.

Project status

Shirdal is young. The Bot API side and the framework layer are covered by an automated test suite. The native MTProto client is a from-scratch implementation that is mostly tested against simulated servers, so expect rough edges on real accounts and please report them. The MTProto code has not had an independent security audit; for high-stakes accounts, prefer an established client such as Telethon through the provided adapter.

Documentation

Contributing

Bug reports, ideas and pull requests are welcome. See CONTRIBUTING.md. For security issues, please follow SECURITY.md instead of opening a public issue.

License

LGPL-3.0-or-later

Metadata

Release files for shirdal 1.0.11

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

Source distribution (sdist)

Source distribution for shirdal 1.0.11
File Size Uploaded Provenance Actions
shirdal-1.0.11.tar.gz 584.9 kB With provenance Details for shirdal-1.0.11.tar.gz

Built distribution (wheel)

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

Total release size: 754.1 kB

Release files / shirdal-1.0.11.tar.gz

Download URL shirdal-1.0.11.tar.gz
Size 584.9 kB
Tags Source
SHA-256 checksum
How to use checksums
d545ea4646c653796002fb1be5983ead70a148d5159baf53e943cc413661756f
BLAKE2b-256 checksum
How to use checksums
2b8b213b7fce5e55826ced4d41d2770aa75afdc2e03e269aad3fcfeadb027640
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 26, 2026.

Transparency log

Release files / shirdal-1.0.11-py3-none-any.whl

Download URL shirdal-1.0.11-py3-none-any.whl
Size 169.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
48332658c68e0f338a52795885d090e9eab6454f3ee05dff7cfe1ed4ecd47089
BLAKE2b-256 checksum
How to use checksums
94fede60485fd28ea65f2cd98a48ace64037c6a68c0da10b4ee87b6a34c69958
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 26, 2026.

Transparency log

Security for shirdal 1.0.11

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 shirdal-1.0.11.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 Nov 26, 2026.

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