Skip to main content

Pure Python 3 MTProto API Telegram client library, for bots and users

Project description

🚀 BeastX - Python Telegram Client Library

PyPI version Python License Telegram

BeastX is a powerful, feature-rich Python library for interacting with Telegram's MTProto API. Build bots, automate messages, manage chats, and access all of Telegram's features with a clean, intuitive interface.

✨ Credits


📦 Installation

Install from PyPI (Recommended)

pip install beastx-python

Install with Performance Enhancements

pip install beastx-python[fast]

Install from Source

git clone https://github.com/beastx-python
cd beastx-python
pip install -e .

🎯 Quick Start

1. Get API Credentials

  1. Visit my.telegram.org
  2. Log in with your phone number
  3. Go to API Development Tools
  4. Create a new application
  5. Copy your api_id and api_hash

2. Basic Example - Send a Message

from beastx import TelegramClient

# Your API credentials
api_id = 12345
api_hash = 'your_api_hash_here'

# Create client
client = TelegramClient('session_name', api_id, api_hash)

async def main():
    # Start the client
    await client.start()
    
    # Send a message
    await client.send_message('username', 'Hello from BeastX! 🚀')
    
    # Get your own info
    me = await client.get_me()
    print(f'Logged in as {me.username}')

# Run the client
with client:
    client.loop.run_until_completed(main())

3. Event Handler Example - Auto-Reply Bot

from beastx import TelegramClient, events

client = TelegramClient('session', api_id, api_hash)

@client.on(events.NewMessage(pattern='(?i)hello'))
async def handler(event):
    """Respond to messages containing 'hello'"""
    await event.respond('Hello! 👋 How can I help you?')

@client.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    """Handle /start command"""
    await event.respond(
        '**Welcome to BeastX Bot!**\n\n'
        'Available commands:\n'
        '/help - Show help\n'
        '/info - Get bot info'
    )

# Start the bot
client.start()
client.run_until_disconnected()

🌟 Key Features

📨 Messaging

# Send messages with formatting
await client.send_message('user', '**Bold** and __italic__ text')

# Send with buttons
from beastx.tl.custom import Button

await client.send_message('user', 'Choose:', buttons=[
    [Button.inline('Option 1', b'opt1'), Button.inline('Option 2', b'opt2')],
    [Button.url('Visit Website', 'https://example.com')]
])

# Edit messages
message = await client.send_message('user', 'Original text')
await message.edit('Updated text')

# Delete messages
await message.delete()

📁 File Operations

# Send files
await client.send_file('user', '/path/to/photo.jpg', caption='Check this out!')
await client.send_file('user', 'video.mp4')

# Download media
async for message in client.iter_messages('channel', limit=10):
    if message.photo:
        path = await message.download_media()
        print(f'Downloaded to: {path}')

# Download with progress
def progress(current, total):
    print(f'Downloaded {current} of {total} bytes ({current/total*100:.1f}%)')

await message.download_media(progress_callback=progress)

👥 User & Chat Management

# Get user info
user = await client.get_entity('username')
print(f'{user.first_name} {user.last_name}')

# Get chat participants
async for user in client.get_participants('channel'):
    print(user.username, user.id)

# Get dialogs (conversations)
async for dialog in client.iter_dialogs():
    print(dialog.name, dialog.id, dialog.unread_count)

# Admin operations
await client.edit_admin(chat, user, is_admin=True)
await client.kick_participant(chat, user)

📬 Advanced Features

# Message history
async for message in client.iter_messages('chat', limit=100):
    print(message.sender_id, message.text)

# Search messages
async for message in client.iter_messages('chat', search='keyword'):
    print(message.text)

# Forward messages
await client.forward_messages('destination', messages, 'source')

# Get message by ID
message = await client.get_messages('chat', ids=12345)

# Conversations (interactive flows)
async with client.conversation('user') as conv:
    await conv.send_message('What is your name?')
    response = await conv.get_response()
    await conv.send_message(f'Hello, {response.text}!')

🎨 Event System

BeastX provides a powerful event system for real-time updates:

from beastx import TelegramClient, events

client = TelegramClient('session', api_id, api_hash)

# New messages
@client.on(events.NewMessage)
async def new_message_handler(event):
    print(f'New message: {event.text}')

# Edited messages
@client.on(events.MessageEdited)
async def edit_handler(event):
    print(f'Message edited to: {event.text}')

# Callback queries (button clicks)
@client.on(events.CallbackQuery)
async def callback_handler(event):
    await event.answer('Button clicked!')
    await event.edit(f'You clicked: {event.data}')

# User status updates
@client.on(events.UserUpdate)
async def status_handler(event):
    if event.typing:
        print(f'User {event.user_id} is typing...')

# Chat actions (joins/leaves)
@client.on(events.ChatAction)
async def action_handler(event):
    if event.user_joined:
        await event.respond('Welcome to the chat!')

client.start()
client.run_until_disconnected()

📚 Complete Examples

Example 1: Download All Media from a Channel

from beastx import TelegramClient

client = TelegramClient('session', api_id, api_hash)

async def download_channel_media():
    await client.start()
    
    count = 0
    async for message in client.iter_messages('channel_username'):
        if message.media:
            await message.download_media(file=f'downloads/')
            count += 1
            print(f'Downloaded {count} files')

with client:
    client.loop.run_until_completed(download_channel_media())

Example 2: Bulk Message Sender

from beastx import TelegramClient
import asyncio

client = TelegramClient('session', api_id, api_hash)

async def bulk_send():
    await client.start()
    
    users = ['user1', 'user2', 'user3']
    message = 'Hello from BeastX!'
    
    for user in users:
        await client.send_message(user, message)
        await asyncio.sleep(1)  # Avoid flood limits

with client:
    client.loop.run_until_completed(bulk_send())

Example 3: Auto-Save Media Bot

from beastx import TelegramClient, events

client = TelegramClient('session', api_id, api_hash)

@client.on(events.NewMessage(pattern='.save'))
async def save_handler(event):
    """Save media from replied message"""
    if event.is_reply:
        reply = await event.get_reply_message()
        if reply.media:
            path = await reply.download_media()
            await event.respond(f'✅ Saved to: {path}')
        else:
            await event.respond('❌ No media in that message')

client.start()
client.run_until_disconnected()

🔧 Bot vs User Accounts

Bot Account (Bot Token)

client = TelegramClient('bot_session', api_id, api_hash)

# Start with bot token
bot_token = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'
client.start(bot_token=bot_token)

User Account (Phone Number)

client = TelegramClient('user_session', api_id, api_hash)

# Start with phone number
client.start(phone='+1234567890')
# You'll receive a code via Telegram

📖 Documentation


🎯 Common Use Cases

Use Case Description
Chat Bots Create interactive bots with commands and buttons
Automation Automate message sending, forwarding, and scheduling
Media Management Download and organize media from channels
User Scrapers Extract user lists from groups
Data Export Backup messages and media
Admin Tools Manage groups and channels programmatically
Analytics Track message statistics and engagement

⚙️ Installation Commands

Basic Installation

pip install beastx-python

With Cryptography Optimization

pip install beastx-python[cryptg]

With All Performance Features

pip install beastx-python[fast]

Development Installation

git clone https://github.com/beastx-python
cd beastx-python
pip install -e .[dev]

🛠️ Configuration

Session Files

BeastX automatically saves your authentication in session files:

# Creates 'my_account.session' file
client = TelegramClient('my_account', api_id, api_hash)

Multiple Accounts

# Account 1
client1 = TelegramClient('account1', api_id, api_hash)

# Account 2
client2 = TelegramClient('account2', api_id, api_hash)

🚨 Error Handling

from beastx import TelegramClient, errors

client = TelegramClient('session', api_id, api_hash)

async def safe_send():
    try:
        await client.send_message('user', 'Hello')
    except errors.FloodWaitError as e:
        print(f'Flood wait: {e.seconds} seconds')
        await asyncio.sleep(e.seconds)
    except errors.UserIsBlockedError:
        print('User has blocked the bot')
    except errors.ChatWriteForbiddenError:
        print('Cannot write in this chat')

await client.start()
await safe_send()

🌍 Community & Support


📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


🙏 Acknowledgments

BeastX is built upon the excellent Telethon library created by Lonami. We extend our deepest gratitude for the original work and continued maintenance of Telethon.

Special Thanks To:

  • Lonami - Creator of Telethon
  • Telegram Team - For the MTProto protocol
  • Python Community - For asyncio and related tools
  • All Contributors - Who help improve this library

🚀 Quick Command Reference

# Install
pip install beastx-python

# Install with extras
pip install beastx-python[fast]

# Upgrade
pip install --upgrade beastx-python

# Build from source
git clone https://github.com/beastx-python
cd beastx-python
python setup.py install

# Run tests
pytest tests/

# Build documentation
cd docs
sphinx-build -b html . _build

Made with ❤️ by GODMRUNAL

Based on Telethon by Lonami

DocumentationChannelGitHub

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

beastx_python-1.0.4.tar.gz (258.3 kB view details)

Uploaded Source

Built Distribution

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

beastx_python-1.0.4-py3-none-any.whl (290.9 kB view details)

Uploaded Python 3

File details

Details for the file beastx_python-1.0.4.tar.gz.

File metadata

  • Download URL: beastx_python-1.0.4.tar.gz
  • Upload date:
  • Size: 258.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for beastx_python-1.0.4.tar.gz
Algorithm Hash digest
SHA256 02f3154a8cc3325630db916fcd1749a36e556aff8ee81fccb57d1e9badb35c8c
MD5 5b939db4a882696195c66d0902e46da2
BLAKE2b-256 ecc5e68458a772815c38057619506b5a2f8ece2f142483abdee40fdb81b9f799

See more details on using hashes here.

File details

Details for the file beastx_python-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: beastx_python-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 290.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for beastx_python-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 325eb9d2ef8a5be95ac5548c42b2f32770b31735e7fb97b4323307ac487effda
MD5 db4f8920c91b7660092f6eb4df82aab7
BLAKE2b-256 b229085e8c43cae68e3f40b65088d74aef0b6359782bbf33f67979873dad9b76

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