cbgram

Telegram MTProto, Python on top, Rust underneath.

An async framework for user accounts and bots. Drop-in for Pyrogram, with crypto and file transfers running in compiled Rust.

$pip install cbgram
Get startedMeet cbcrypto
Your codehandlers
cbgramPython API
cbcryptoRust core
TelegramMTProto

Overview

cbgram is a modern, async-first framework for the Telegram MTProto API. Sign in as a user or run as a bot and use everything an official client can.

It is a drop-in replacement for Pyrogram. New code can use from cbgram import …, and existing from pyrogram import … code keeps working, because both names point to the same module. The same holds for code written for Pyrogram forks that import as pyrogram.

Features

Drop-inMigrate from Pyrogram with no code changes.
Async nativeFull async/await, still usable synchronously via app.run().
Rust coreMTProto crypto and the file engine run compiled.
Up to dateGifts, Stories, Topics, Business, Giveaways, latest layer.
Users & botsOne framework for accounts and bot tokens.
Type-hintedEvery type and method annotated for your editor.
StorageSQLite by default, Mongo and Redis extras.
ProxyBuilt on python-socks with asyncio.

Install

Both packages are on PyPI. Python 3.10+ is required. cbcrypto is pulled in automatically by cbgram, and you can also install it on its own.

pip install cbgram
pip install cbcrypto
pip install cbgram cbcrypto
pip install "cbgram[fast]"
ExtraInstallAdds
fastpip install "cbgram[fast]"uvloop (Linux, macOS)
mongopip install "cbgram[mongo]"MongoDB storage
redispip install "cbgram[redis]"Redis storage
Uninstall pyrogram, kurigram or pyrofork first. They share the same pyrogram/ folder and overwrite each other.

Quick start

Get api_id and api_hash from my.telegram.org, then:

from cbgram import Client, filters

app = Client("my_account", api_id=12345, api_hash="your_hash")

@app.on_message(filters.private)
async def hello(client, message):
    await message.reply("Hello from cbgram!")

app.run()

Login & sessions

The first run asks for your phone number and code, then saves a session file named after the client. For a bot, pass its token.

bot = Client("my_bot", api_id=12345, api_hash="your_hash", bot_token="123:ABC")

# keep the session in memory only
tmp = Client("temp", api_id=12345, api_hash="your_hash", in_memory=True)

# async style instead of app.run()
async def main():
    async with bot:
        await bot.send_message("me", "online")

Handlers

Decorate a coroutine and cbgram calls it for matching updates.

DecoratorFires on
@app.on_message()new messages
@app.on_edited_message()edited messages
@app.on_deleted_messages()deletions
@app.on_callback_query()inline button presses
@app.on_inline_query()inline mode queries

Filters

Combine filters with &, | and ~.

@app.on_message(filters.command(["start", "help"]) & filters.private)
async def start(client, message): ...

@app.on_message(filters.group & filters.regex(r"^hi\b") & ~filters.me)
async def greet(client, message): ...

@app.on_message(filters.photo | filters.video | filters.document)
async def media(client, message): ...

Inline buttons

from cbgram.types import InlineKeyboardMarkup, InlineKeyboardButton

@app.on_message(filters.command("start"))
async def start(client, message):
    await message.reply("Choose:", reply_markup=InlineKeyboardMarkup([
        [InlineKeyboardButton("Website", url="https://example.com"),
         InlineKeyboardButton("Help", callback_data="help")]]))

@app.on_callback_query()
async def pressed(client, query):
    await query.answer("You pressed " + query.data)

Media & files

Downloads and uploads by path go through the Rust engine automatically. Progress callbacks receive the bytes done and the total.

async def progress(current, total):
    print(f"{current * 100 / total:.1f}%")

@app.on_message(filters.document)
async def save(client, message):
    path = await message.download(progress=progress)
    await client.send_document("me", path, progress=progress)

await app.send_photo("me", "photo.jpg", caption="Sent with cbgram")

Proxy & storage

app = Client("acc", api_id=12345, api_hash="your_hash", proxy=dict(
    scheme="socks5", hostname="127.0.0.1", port=1080,
    username="user", password="pass"))

Sessions use SQLite by default. Install the mongo or redis extra to use those backends. Proxied and in-memory transfers fall back to the Python path automatically.

cbcrypto sub-project

The Rust engine behind cbgram. It handles MTProto crypto (AES-IGE, AES-CTR, KDF, message pack/unpack) and the download/upload engine with sockets, pacing and file writes. It detects AES-NI, VAES and AVX-512 at runtime.

$pip install cbcrypto
LayerPython (cbgram)Rust (cbcrypto)
Handshake, sessions, handlers, types✔
AES-IGE / CTR, KDF✔
download_media, save_filerequest logictransport and writes
import cbcrypto
print(cbcrypto.backend())   # e.g. aes_ni=true vaes=true
enc = cbcrypto.ige256_encrypt(data, key, iv)

Speed race

Same job, same machine, same time limit. The farther a bar runs, the faster the library. The leader reaches the checkered line.

Speed in MB/s, higher is faster. Measured on one core with AES-NI and VAES; your numbers will differ.

Switches

VariableDefaultMeaning
CBGRAM_RUST_CORE10 forces the pure-Python transfer path
CBGRAM_UVLOOPoff1 enables uvloop on Linux and macOS
CBCRYPTO_DEBUGoffper-request engine trace on stderr

Development

git clone https://github.com/abhiadi23/cbgram.git
cd cbgram
pip install uv
uv sync --frozen --extra dev
uv run poe api     # generate TL API types
uv run poe test    # run the tests

Made by Cantarella Bots

Full credit to Cantarella Bots and abhiadi23 for cbgram and cbcrypto.
Built on the work of Dan (delivrance) and the Pyrogram project.

Released under the GNU LGPL v3 or later. · Source · Issues · cbcrypto