beastx-python 1.0.4
Pure Python 3 MTProto API Telegram client library, for bots and users
License: MIT
Requires Python: >=3.7
Keywords: telegram, telegram-client, mtproto, api, bot, asyncio, beastx

# 🚀 BeastX - Python Telegram Client Library

[![PyPI version](https://img.shields.io/badge/pypi-v1.0.3-blue.svg)](https://pypi.org/project/beastx-python/)
[![Python](https://img.shields.io/badge/python-3.7+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Telegram](https://img.shields.io/badge/Telegram-@BEASTX__BOTS-blue.svg)](https://t.me/BEASTX_BOTS)

**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

- **Original Telethon**: Created by [Lonami](https://github.com/LonamiWebs) - [Telethon Repository](https://github.com/LonamiWebs/Telethon)
- **BeastX Developer**: [t.me/GODMRUNAL](https://t.me/GODMRUNAL)
- **Official Channel**: [@BEASTX_BOTS](https://t.me/BEASTX_BOTS)
- **GitHub**: [github.com/beastx-python](https://github.com/beastx-python)

---

## 📦 Installation

### Install from PyPI (Recommended)

```bash
pip install beastx-python
```

### Install with Performance Enhancements

```bash
pip install beastx-python[fast]
```

### Install from Source

```bash
git clone https://github.com/beastx-python
cd beastx-python
pip install -e .
```

---

## 🎯 Quick Start

### 1. Get API Credentials

1. Visit [my.telegram.org](https://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

```python
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

```python
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

```python
# 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

```python
# 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

```python
# 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

```python
# 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:

```python
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

```python
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

```python
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

```python
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)

```python
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)

```python
client = TelegramClient('user_session', api_id, api_hash)

# Start with phone number
client.start(phone='+1234567890')
# You'll receive a code via Telegram
```

---

## 📖 Documentation

- **Full Documentation**: [beastx-python.github.io](https://beastx-python.github.io)
- **API Reference**: Complete coverage of all methods and events
- **Examples**: [See examples folder](examples/)
- **Telegram Channel**: [@BEASTX_BOTS](https://t.me/BEASTX_BOTS)
- **Original Telethon Docs**: [docs.telethon.dev](https://docs.telethon.dev)

---

## 🎯 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
```bash
pip install beastx-python
```

### With Cryptography Optimization
```bash
pip install beastx-python[cryptg]
```

### With All Performance Features
```bash
pip install beastx-python[fast]
```

### Development Installation
```bash
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:

```python
# Creates 'my_account.session' file
client = TelegramClient('my_account', api_id, api_hash)
```

### Multiple Accounts

```python
# Account 1
client1 = TelegramClient('account1', api_id, api_hash)

# Account 2
client2 = TelegramClient('account2', api_id, api_hash)
```

---

## 🚨 Error Handling

```python
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

- **Telegram Channel**: [@BEASTX_BOTS](https://t.me/BEASTX_BOTS)
- **Developer**: [t.me/GODMRUNAL](https://t.me/GODMRUNAL)
- **GitHub Issues**: [Report bugs](https://github.com/beastx-python/issues)
- **Original Telethon**: [Lonami's Telethon](https://github.com/LonamiWebs/Telethon)

---

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

## 🙏 Acknowledgments

**BeastX** is built upon the excellent [Telethon](https://github.com/LonamiWebs/Telethon) library created by [Lonami](https://github.com/LonamiWebs). 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

```bash
# 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
```

---

<div align="center">

**Made with ❤️ by [GODMRUNAL](https://t.me/GODMRUNAL)**

**Based on [Telethon](https://github.com/LonamiWebs/Telethon) by [Lonami](https://github.com/LonamiWebs)**

**[Documentation](https://beastx-python.github.io) • [Channel](https://t.me/BEASTX_BOTS) • [GitHub](https://github.com/beastx-python)**

</div>