Skip to main content

An advanced, easy-to-use Telegram Bot Framework with MongoDB support

Project description

PyTgGram - Advanced Telegram Bot Framework

PyTgGram is a powerful, easy-to-use asynchronous Telegram Bot Framework built with Python 3.7+. It provides a simple and intuitive API for building Telegram bots with advanced features like MongoDB integration, flood control, rate limiting, and plugin support.

๐ŸŒŸ Features

ยท ๐Ÿš€ Asynchronous by design - Built on async/await for high performance ยท ๐Ÿ’พ Multiple storage options - Memory, Redis, JSON, and MongoDB support ยท ๐Ÿ›ก๏ธ Flood control - Automatic handling of Telegram rate limits ยท โšก Rate limiting - Controlled API request pacing ยท ๐Ÿ”Œ Plugin system - Extensible architecture for custom functionality ยท ๐Ÿ“‹ Advanced filters - Complex filter combinations for precise message handling ยท ๐Ÿ”ง Sync & Async clients - Both synchronous and asynchronous interfaces ยท ๐Ÿ“Š MongoDB integration - Full MongoDB support with models and CRUD operations ยท ๐ŸŽฏ Type hints - Full type hint support for better development experience ยท ๐Ÿ“ฆ Comprehensive API - Support for all major Telegram Bot API methods

๐Ÿ“ฆ Installation

From PyPI (Coming Soon)

pip install pytggram

From Source

git clone https://github.com/hasnainkk-07/pytgbot.git
cd pytggram
pip install -e .

Dependencies

pip install aiohttp motor redis

๐Ÿš€ Quick Start

Create a simple bot:

from pytggram import Client, filters

# Create bot instance
bot = Client("YOUR_BOT_TOKEN_HERE")

# Command handler
@bot.command(['start', 'help'])
async def start_command(client, message):
    await message.reply(
        "๐Ÿš€ Welcome to PyTgGram Bot!\n\n"
        "Available commands:\n"
        "/start - Show this help\n"
        "/echo [text] - Echo your text\n"
        "/info - Get user info"
    )

# Message handler with filter
@bot.on_message(filters.Text(contains='thank') & filters.Private)
async def thank_you_handler(client, message):
    await message.reply("You're welcome! ๐Ÿ˜Š")

if __name__ == "__main__":
    bot.run()

๐Ÿ“ Project Structure

pytggram/
โ”œโ”€โ”€ __init__.py                 # Package exports and version info
โ”œโ”€โ”€ client.py                   # Main asynchronous client
โ”œโ”€โ”€ sync_client.py              # Synchronous client wrapper
โ”œโ”€โ”€ exceptions.py               # Custom exceptions
โ”œโ”€โ”€ dispatcher.py               # Update dispatcher with priority groups
โ”œโ”€โ”€ router.py                   # Handler routing system
โ”œโ”€โ”€ types/                      # Telegram API types
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ message.py              # Message type
โ”‚   โ”œโ”€โ”€ user.py                 # User type
โ”‚   โ”œโ”€โ”€ chat.py                 # Chat type
โ”‚   โ”œโ”€โ”€ callback.py             # Callback query type
โ”‚   โ”œโ”€โ”€ inline.py               # Inline query types
โ”‚   โ”œโ”€โ”€ poll.py                 # Poll types
โ”‚   โ””โ”€โ”€ payments.py             # Payment types
โ”œโ”€โ”€ handlers/                   # Update handlers
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ message_handler.py      # Message handler
โ”‚   โ”œโ”€โ”€ callback_handler.py     # Callback handler
โ”‚   โ”œโ”€โ”€ inline_handler.py       # Inline handler
โ”‚   โ”œโ”€โ”€ poll_handler.py         # Poll handler
โ”‚   โ””โ”€โ”€ handler.py              # Base handler class
โ”œโ”€โ”€ filters.py                  # Message filters system
โ”œโ”€โ”€ methods/                    # Telegram API methods
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ auth.py                 # Authentication methods
โ”‚   โ”œโ”€โ”€ messages.py             # Message methods
โ”‚   โ”œโ”€โ”€ chats.py                # Chat methods
โ”‚   โ”œโ”€โ”€ inline.py               # Inline methods
โ”‚   โ”œโ”€โ”€ payments.py             # Payment methods
โ”‚   โ””โ”€โ”€ advanced.py             # Advanced methods
โ”œโ”€โ”€ utils/                      # Utility functions
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ helpers.py              # Helper functions
โ”‚   โ”œโ”€โ”€ decorators.py           # Decorators
โ”‚   โ”œโ”€โ”€ rate_limiter.py         # Rate limiting
โ”‚   โ”œโ”€โ”€ flood_control.py        # Flood control
โ”‚   โ””โ”€โ”€ mongodb_helpers.py      # MongoDB utilities
โ”œโ”€โ”€ storage/                    # Storage backends
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ memory_storage.py       # In-memory storage
โ”‚   โ”œโ”€โ”€ redis_storage.py        # Redis storage
โ”‚   โ”œโ”€โ”€ json_storage.py         # JSON file storage
โ”‚   โ””โ”€โ”€ mongodb_storage.py      # MongoDB storage
โ”œโ”€โ”€ plugins/                    # Plugin system
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ””โ”€โ”€ example_plugin.py       # Example plugin
โ”œโ”€โ”€ api/                        # API utilities
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ””โ”€โ”€ telegram_api.py         # Low-level API wrapper
โ””โ”€โ”€ database/                   # MongoDB database layer
    โ”œโ”€โ”€ __init__.py
    โ”œโ”€โ”€ models.py               # Database models
    โ”œโ”€โ”€ crud.py                 # CRUD operations
    โ””โ”€โ”€ connection.py           # Database connection

๐Ÿ”ง Usage Examples

Basic Bot with Commands

from pytggram import Client, filters

bot = Client("YOUR_BOT_TOKEN_HERE")

@bot.command(['start', 'help'])
async def start_handler(client, message):
    await message.reply("Hello! I'm a PyTgGram bot!")

@bot.command(['echo'])
async def echo_handler(client, message):
    if message.command_args:
        await message.reply(f"Echo: {message.command_args}")
    else:
        await message.reply("Please provide text to echo")

@bot.on_message(filters.Private)
async def private_message_handler(client, message):
    await message.reply("Thanks for your message in private chat!")

if __name__ == "__main__":
    bot.run()

Advanced Bot with MongoDB

from pytggram import Client, filters, MongoDBStorage

# Create bot with MongoDB storage
bot = Client("YOUR_BOT_TOKEN_HERE")
mongo_storage = MongoDBStorage("mongodb://localhost:27017", "my_bot_db")

@bot.command(['start'])
async def start_handler(client, message):
    user = message.from_user
    # Store user in MongoDB
    await mongo_storage.set(user.id, "start_count", 1)
    await message.reply(f"Welcome {user.full_name}! You're user #{user.id}")

@bot.command(['stats'])
async def stats_handler(client, message):
    user = message.from_user
    start_count = await mongo_storage.get(user.id, "start_count", 0)
    await message.reply(f"You've started the bot {start_count} times")

async def main():
    await mongo_storage.connect()
    bot.run()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Inline Query Bot

from pytggram import Client, filters, types

bot = Client("YOUR_BOT_TOKEN_HERE")

@bot.inline_handler()
async def inline_query_handler(client, inline_query):
    from pytggram.types import InlineQueryResultArticle, InputTextMessageContent
    
    results = [
        InlineQueryResultArticle(
            id="1",
            title="Hello World",
            input_message_content=InputTextMessageContent("Hello from PyTgGram! ๐Ÿš€")
        ),
        InlineQueryResultArticle(
            id="2",
            title="Current Time",
            input_message_content=InputTextMessageContent(f"Current time: {datetime.now()}")
        )
    ]
    
    await client.answer_inline_query(inline_query.id, results, cache_time=300)

if __name__ == "__main__":
    bot.run()

Bot with Keyboard Buttons

from pytggram import Client, filters, types

bot = Client("YOUR_BOT_TOKEN_HERE")

@bot.command(['start'])
async def start_handler(client, message):
    from pytggram.types import ReplyKeyboardMarkup, KeyboardButton
    
    keyboard = ReplyKeyboardMarkup([
        [KeyboardButton("Option 1"), KeyboardButton("Option 2")],
        [KeyboardButton("Contact", request_contact=True)],
        [KeyboardButton("Location", request_location=True)]
    ], resize_keyboard=True)
    
    await message.reply("Choose an option:", reply_markup=keyboard)

@bot.on_message(filters.Text("Option 1"))
async def option1_handler(client, message):
    await message.reply("You selected Option 1!")

@bot.on_message(filters.Text("Option 2"))
async def option2_handler(client, message):
    await message.reply("You selected Option 2!")

if __name__ == "__main__":
    bot.run()

๐Ÿ“š API Reference

Client Class

The main client class for interacting with the Telegram Bot API.

from pytggram import Client

bot = Client(
    token="YOUR_BOT_TOKEN",
    max_retries=3,              # Maximum retry attempts
    request_timeout=30,          # Request timeout in seconds
    flood_sleep_threshold=10     # Flood control threshold
)

Handlers

PyTgGram supports various handler types:

# Message handler
@bot.on_message(filters.Command('start'))
async def handler(client, message):
    pass

# Callback handler
@bot.on_callback(filters.CallbackData('button_click'))
async def handler(client, callback):
    pass

# Inline handler
@bot.on_inline(filters.InlinePattern('search'))
async def handler(client, inline_query):
    pass

# Poll handler
@bot.on_poll()
async def handler(client, poll):
    pass

Filters

Advanced filtering system for precise message handling:

from pytggram import filters

# Command filter
filters.Command(['start', 'help'])

# Text filter
filters.Text(contains='hello')
filters.Text(startswith='hi')
filters.Text(endswith='bye')

# Regex filter
filters.Regex(r'^hello.*')

# Chat type filters
filters.Private
filters.Group
filters.Channel

# Combined filters
filters.Command('start') & filters.Private
filters.Text(contains='help') | filters.Command('help')

Storage Options

Multiple storage backends available:

from pytggram import MemoryStorage, RedisStorage, JSONStorage, MongoDBStorage

# In-memory storage (default)
storage = MemoryStorage()

# Redis storage
storage = RedisStorage(host='localhost', port=6379, db=0)

# JSON file storage
storage = JSONStorage('data.json')

# MongoDB storage
storage = MongoDBStorage('mongodb://localhost:27017', 'bot_db')

๐Ÿ”Œ Plugins System

Extend functionality with plugins:

# plugins/my_plugin.py
from pytggram import Client, filters

def setup_plugin(client: Client):
    @client.command(['plugin'])
    async def plugin_command(client, message):
        await message.reply("This is from a plugin!")
    
    return {
        'name': 'My Plugin',
        'version': '1.0.0',
        'description': 'Example plugin for PyTgGram'
    }

# main.py
from pytggram import Client
from plugins.my_plugin import setup_plugin

bot = Client("YOUR_BOT_TOKEN_HERE")
setup_plugin(bot)

if __name__ == "__main__":
    bot.run()

โš™๏ธ Configuration

Environment Variables

export BOT_TOKEN="your_bot_token"
export MONGODB_URI="mongodb://localhost:27017"
export REDIS_URL="redis://localhost:6379"

Custom Session Configuration

import aiohttp
from pytggram import Client

session = aiohttp.ClientSession(
    timeout=aiohttp.ClientTimeout(total=30),
    connector=aiohttp.TCPConnector(limit=100)
)

bot = Client("YOUR_BOT_TOKEN_HERE", session=session)

๐Ÿšจ Error Handling

from pytggram import Client, APIException, FloodException

bot = Client("YOUR_BOT_TOKEN_HERE")

@bot.on_message(filters.Command('test'))
async def test_handler(client, message):
    try:
        # Some API call that might fail
        await client.send_message(message.chat.id, "Test message")
    except FloodException as e:
        print(f"Flood control: wait {e.retry_after} seconds")
    except APIException as e:
        print(f"API error: {e} (code: {e.code})")
    except Exception as e:
        print(f"Unexpected error: {e}")

๐Ÿ“Š MongoDB Integration

PyTgGram provides full MongoDB integration:

from pytggram import Client, MongoDBStorage, MongoDBCRUD
from pytggram.database import User, Chat, Message

bot = Client("YOUR_BOT_TOKEN_HERE")
storage = MongoDBStorage("mongodb://localhost:27017", "bot_db")
crud = MongoDBCRUD(storage.connection)

@bot.on_message(filters.Private)
async def message_handler(client, message):
    # Save user to database
    user = await crud.get_or_create_user(message.from_user.__dict__)
    
    # Save chat to database
    chat = await crud.get_or_create_chat(message.chat.__dict__)
    
    # Save message to database
    message_data = Message(
        message_id=message.message_id,
        chat_id=message.chat.id,
        user_id=message.from_user.id,
        text=message.text
    )
    await crud.save_message(message_data)
    
    # Store user data
    await storage.set(message.from_user.id, "message_count", 1)

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Setup

git clone https://github.com/hasnainkk-07/pytgbot.git
cd pytggram
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -e .[dev]

Running Tests

pytest tests/ -v

๐Ÿ“„ License

PyTgGram is licensed under the MIT License. See LICENSE for details.

๐Ÿ™ Acknowledgments

ยท Inspired by Pyrogram and python-telegram-bot ยท Built with aiohttp for async HTTP requests ยท MongoDB support with motor


PyTgGram - Making Telegram Bot Development Easy and Fun! ๐Ÿš€

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

test_pytggram-1.0.5.tar.gz (38.9 kB view details)

Uploaded Source

Built Distribution

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

test_pytggram-1.0.5-py3-none-any.whl (52.7 kB view details)

Uploaded Python 3

File details

Details for the file test_pytggram-1.0.5.tar.gz.

File metadata

  • Download URL: test_pytggram-1.0.5.tar.gz
  • Upload date:
  • Size: 38.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.23

File hashes

Hashes for test_pytggram-1.0.5.tar.gz
Algorithm Hash digest
SHA256 24b3a499a0b1658f274dc7090a20bafb2f40a3dd06d781a3a86bacf3f6f60e9e
MD5 6207916617924a00f63167e42076954e
BLAKE2b-256 b15a870eca69e062acf0f00909c39b719fdd9b74eb38346053b64130c8f6db09

See more details on using hashes here.

File details

Details for the file test_pytggram-1.0.5-py3-none-any.whl.

File metadata

  • Download URL: test_pytggram-1.0.5-py3-none-any.whl
  • Upload date:
  • Size: 52.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.23

File hashes

Hashes for test_pytggram-1.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 c0b23e438626694e622923ef5952806a936263094ad11d0316bcf1ab9994c088
MD5 e839163b18b1417c441cca2ada12ebff
BLAKE2b-256 45271d1fbc97d23cfc84b4182e57ef6376171ae1c3b545f0a439c795ed5ed942

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