Skip to main content

An experimental full MTProto Python client library

Project description

TGLib

PyPI Version Python Versions License Stars Status

An experimental, full-featured MTProto Python client library for Telegram.
Built from scratch. Async-first. Lightweight. Telethon-style API.


โš ๏ธ Experimental

TGLib is currently in early development. APIs may change without notice. Use in production at your own risk. Contributions and feedback are welcome!


โœจ Features

  • ๐Ÿ” Full MTProto implementation โ€” low-level Telegram protocol support
  • โšก Async-first โ€” built entirely on asyncio
  • ๐Ÿ”„ Sync & Async support โ€” use whichever style you prefer
  • ๐Ÿ—„๏ธ Session persistence โ€” via aiosqlite
  • ๐Ÿ”’ Encryption โ€” powered by pyaes and pycryptodome
  • ๐Ÿค– Bot & User client โ€” supports both bot tokens and phone login
  • ๐Ÿชถ Lightweight โ€” minimal dependencies, maximum control
  • ๐Ÿ Python 3.10+ โ€” uses modern Python features

๐Ÿ“ฆ Installation

From PyPI:

pip install tglib

From source:

git clone https://github.com/ankit-chaubey/TGLib.git
cd TGLib
pip install -e .

๐Ÿš€ Quick Start

Get your api_id and api_hash from my.telegram.org.
Never hardcode credentials โ€” use environment variables!

export API_ID=your_api_id
export API_HASH=your_api_hash

๐Ÿ“– Usage Styles

TGLib supports three usage styles, just like Telethon.

1. Async (recommended)

import asyncio
import os
from tglib import TelegramClient

client = TelegramClient(
    session="my_session",
    api_id=int(os.environ["API_ID"]),
    api_hash=os.environ["API_HASH"],
)

async def main():
    await client.start(phone="+1234567890")
    me = await client.get_me()
    print(f"Logged in as: {me.first_name}")
    await client.disconnect()

asyncio.run(main())

2. Async Context Manager (cleanest)

import asyncio
import os
from tglib import TelegramClient

async def main():
    async with TelegramClient(
        session="my_session",
        api_id=int(os.environ["API_ID"]),
        api_hash=os.environ["API_HASH"],
    ) as client:
        me = await client.get_me()
        print(f"Logged in as: {me.first_name}")

asyncio.run(main())

3. Sync (beginner-friendly, no asyncio needed)

import os
from tglib import TelegramClient

with TelegramClient(
    session="my_session",
    api_id=int(os.environ["API_ID"]),
    api_hash=os.environ["API_HASH"],
) as client:
    me = client.run(client.get_me())
    print(f"Logged in as: {me.first_name}")

๐Ÿค– Bot Example

import asyncio
import os
from tglib import TelegramClient

client = TelegramClient(
    session="bot_session",
    api_id=int(os.environ["API_ID"]),
    api_hash=os.environ["API_HASH"],
)

@client.on(None)  # handle all updates
async def handler(update):
    print(update)

async def main():
    await client.start(bot_token=os.environ["BOT_TOKEN"])
    print("Bot is running...")
    await client.run_until_disconnected()

asyncio.run(main())

๐Ÿ“ก Sending Messages

# Send a plain message
await client.send_message("username", "Hello from TGLib!")

# Send with markdown
await client.send_message("username", "**Bold** and *italic*", parse_mode="md")

# Send with HTML
await client.send_message("username", "<b>Bold</b> text", parse_mode="html")

# Reply to a message
await client.send_message("username", "Replying!", reply_to=message_id)

๐Ÿ“ฅ Receiving Messages

async def main():
    await client.start(phone="+1234567890")

    # Get recent messages
    messages = await client.get_messages("username", limit=10)
    for msg in messages.messages:
        print(msg.message)

    # Get dialogs
    dialogs = await client.get_dialogs(limit=20)

asyncio.run(main())

๐Ÿ”„ run_until_disconnected

Keep your client or bot alive until manually stopped (Ctrl+C):

# Async
await client.run_until_disconnected()

# Sync
client.run(client.run_until_disconnected())

๐Ÿ”ง Dependencies

Package Purpose
pyaes AES encryption for MTProto
pycryptodome RSA and additional crypto
aiosqlite Async session storage

๐Ÿ“ Project Structure

TGLib/
โ”œโ”€โ”€ tglib/
โ”‚   โ”œโ”€โ”€ __init__.py          # Entry point
โ”‚   โ”œโ”€โ”€ client.py            # Main TelegramClient
โ”‚   โ”œโ”€โ”€ crypto/              # Encryption & MTProto crypto
โ”‚   โ”œโ”€โ”€ network/             # TCP transport & MTProto sender
โ”‚   โ”œโ”€โ”€ sessions/            # SQLite & Memory sessions
โ”‚   โ”œโ”€โ”€ tl/                  # TL schema types & functions
โ”‚   โ”‚   โ”œโ”€โ”€ types/           # Telegram object types
โ”‚   โ”‚   โ””โ”€โ”€ functions/       # Telegram API functions
โ”‚   โ”œโ”€โ”€ errors/              # RPC & custom errors
โ”‚   โ””โ”€โ”€ helpers.py           # Utility functions
โ”œโ”€โ”€ setup.py
โ””โ”€โ”€ README.md

๐Ÿค Contributing

Contributions are very welcome! Here's how to get started:

# Fork the repo, then:
git clone https://github.com/YOUR_USERNAME/TGLib.git
cd TGLib
pip install -e .
  1. Create a new branch: git checkout -b feature/your-feature
  2. Make your changes
  3. Push and open a Pull Request

๐Ÿ› Issues & Feedback

Found a bug or have a suggestion?
๐Ÿ‘‰ Open an issue


๐Ÿ“„ License

This project is licensed under the MIT License โ€” see the LICENSE file for details.


๐Ÿ‘ค Author

Ankit Chaubey
๐Ÿ“ง ankitchaubey.dev@gmail.com
๐Ÿ™ github.com/ankit-chaubey


Made with โค๏ธ and Python

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

tglib-0.1.2.tar.gz (412.6 kB view details)

Uploaded Source

Built Distribution

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

tglib-0.1.2-py3-none-any.whl (456.5 kB view details)

Uploaded Python 3

File details

Details for the file tglib-0.1.2.tar.gz.

File metadata

  • Download URL: tglib-0.1.2.tar.gz
  • Upload date:
  • Size: 412.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for tglib-0.1.2.tar.gz
Algorithm Hash digest
SHA256 58e606401145929c17befd743e4b6a05f5aa973f3a655557e7ea2c576b984f63
MD5 4465f5e0fa0bc9081853f418a1508ce4
BLAKE2b-256 4be230af46ed1e0228af7a2b3dcfd142d85fe3082afd4a5877136b7fc8b2f7de

See more details on using hashes here.

File details

Details for the file tglib-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: tglib-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 456.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for tglib-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 77a7b3e7a2b8a558abbf6783bae08efe8666f9a4304c391f172d69d02805733b
MD5 3d91f7788f88de79fa55cd63105e06fd
BLAKE2b-256 2ad6bb8b4bb66030f990008073fc511a5734fe3a518e64fe03a5cf6d2286a015

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