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.3.tar.gz (258.2 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.3-py3-none-any.whl (290.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: beastx_python-1.0.3.tar.gz
  • Upload date:
  • Size: 258.2 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.3.tar.gz
Algorithm Hash digest
SHA256 d201c8ff986040283f3b847853bcdf3598b91f65e8be268153775decec704162
MD5 309da88bb5fc3a901e00d42ab75733c4
BLAKE2b-256 a219a0587fb555895ef11c5de2795d7be402f08b42e9e08eab0339ae93507ec1

See more details on using hashes here.

File details

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

File metadata

  • Download URL: beastx_python-1.0.3-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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 b2f18e788647f31c50dc5fb2c9462241a057c974f78979b6b066c7898c216d0f
MD5 9dcaa79b288c545ef528a38e83b4a042
BLAKE2b-256 107acd70622de32187af668f446b958061c60c9293d7ff6ef88e7e9046b13172

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