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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
24b3a499a0b1658f274dc7090a20bafb2f40a3dd06d781a3a86bacf3f6f60e9e
|
|
| MD5 |
6207916617924a00f63167e42076954e
|
|
| BLAKE2b-256 |
b15a870eca69e062acf0f00909c39b719fdd9b74eb38346053b64130c8f6db09
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c0b23e438626694e622923ef5952806a936263094ad11d0316bcf1ab9994c088
|
|
| MD5 |
e839163b18b1417c441cca2ada12ebff
|
|
| BLAKE2b-256 |
45271d1fbc97d23cfc84b4182e57ef6376171ae1c3b545f0a439c795ed5ed942
|