Simple Python framework for working with Telegram API and Mini Apps
Project description
TMA Framework
Advanced Python framework for Telegram user simulation and Mini App testing with full MTProto capabilities.
Features
- 👤 Full User Simulation - Act as a real Telegram user with MTProto
- 🤖 Bot Interaction - Send messages to bots and receive responses
- 📱 Automatic Mini App Discovery - Find and interact with Mini Apps from bots
- 🎭 Playwright Integration - Automated UI testing with Playwright
- 🔌 HTTP Client - API testing with httpx
- ⚙️ Simple Configuration - Environment variables and config objects
- 🔄 Async Support - Full async/await support
- 📊 Logging - Built-in logging with loguru
- 🚀 High Performance - Powered by msgspec for fast serialization and validation
Installation
# Install dependencies
uv add httpx telethon playwright msgspec loguru pyyaml aiofiles cryptography
# Install Playwright browsers
playwright install
Quick Start
Setup Requirements
Before using TMA Framework, you need:
-
Telegram API Credentials (from my.telegram.org):
- Go to "API development tools"
- Create new application
- Copy
api_idandapi_hash
-
Get Session String (one-time setup):
- Run:
python examples/get_session.py - Enter your API credentials and phone number
- Complete authentication (SMS code + 2FA if needed)
- Copy the generated session string
- Run:
-
Environment Variables:
export TMA_API_ID="your_api_id" export TMA_API_HASH="your_api_hash" export TMA_SESSION_STRING="your_session_string"
Basic Usage
import asyncio
from tma_framework import UserTelegramClient, Config
async def main():
# Configuration with session string
config = Config(
api_id=12345,
api_hash="your_api_hash",
session_string="your_session_string" # From get_session.py
)
# Initialize client (no authentication needed)
async with UserTelegramClient(config) as client:
user_info = await client.get_me()
print(f"User: {user_info.first_name} (@{user_info.username})")
# Interact with any bot
response = await client.interact_with_bot(
bot_username="example_bot",
command="/start",
wait_for_response=True
)
if response:
print(f"Bot response: {response.text}")
asyncio.run(main())
Mini App API Testing
import asyncio
from tma_framework import UserTelegramClient, MiniAppApi, Config
async def main():
config = Config(
api_id=12345,
api_hash="your_api_hash",
session_string="your_session_string"
)
async with UserTelegramClient(config) as client:
# Get Mini App from bot
mini_app = await client.get_mini_app_from_bot("example_bot")
if mini_app:
# Test API endpoints
async with MiniAppApi(mini_app.url, config) as api:
result = await api.make_request("/api/status", "GET")
print(f"API Test: {'✅ PASSED' if result.success else '❌ FAILED'}")
# Validate initData
is_valid = await api.validate_init_data(init_data, "bot_token")
print(f"InitData validation: {'✅ VALID' if is_valid else '❌ INVALID'}")
asyncio.run(main())
Mini App UI Testing
import asyncio
from tma_framework import UserTelegramClient, MiniAppUI, Config
async def main():
config = Config(
api_id=12345,
api_hash="your_api_hash",
session_string="your_session_string"
)
async with UserTelegramClient(config) as client:
# Get Mini App from bot
mini_app = await client.get_mini_app_from_bot("example_bot")
if mini_app:
# Test Mini App UI
async with MiniAppUI(mini_app.url, config) as ui:
# Setup browser and navigate
await ui.setup_browser()
await ui.page.goto(mini_app.url, wait_until="networkidle")
# UI interactions
await ui.fill_input("#username", "test_user")
await ui.click_element("#submit-button")
await ui.take_screenshot("test_screenshot.png")
asyncio.run(main())
Configuration
Environment Variables
# Required
export TMA_API_ID="12345"
export TMA_API_HASH="your_api_hash"
# Session (choose one)
export TMA_SESSION_STRING="session_string" # For saved sessions
export TMA_SESSION_FILE="session.session" # For file sessions
# Optional
export TMA_MINI_APP_URL="https://your-mini-app.com"
export TMA_MINI_APP_START_PARAM="start_param_value"
export TMA_TIMEOUT="30"
export TMA_RETRY_COUNT="3"
export TMA_RETRY_DELAY="1.0"
export TMA_LOG_LEVEL="INFO"
Config Object
from tma_framework import Config
# Using session string
config = Config(
api_id=12345,
api_hash="your_api_hash",
session_string="your_session_string"
)
# Using session file
config = Config(
api_id=12345,
api_hash="your_api_hash",
session_file="my_session.session"
)
API Reference
UserTelegramClient
Core Methods
get_me()- Get current user informationget_entity()- Get entity (user/chat) informationsend_message()- Send message to user/chatget_messages()- Get messages from chatinteract_with_bot()- Interact with any botget_mini_app_from_bot()- Get Mini App from botadd_event_handler()- Add event handlerstart_listening()- Start listening for messages
MiniAppApi
make_request()- Make HTTP request to API endpointvalidate_init_data()- Validate Telegram initData with HMAC
MiniAppUI
setup_browser()- Setup Playwright browserclick_element()- Click elementfill_input()- Fill input fieldwait_for_element()- Wait for elementtake_screenshot()- Take screenshotget_page_title()- Get page titleget_page_url()- Get page URLexecute_script()- Execute JavaScript
Examples
See the examples/ directory for more detailed examples:
mtproto_usage.py- Complete MTProto user simulation examplesget_session.py- Script to generate session string for authenticationsimple_auth.py- Simple authentication exampleerror_handling.py- Error handling and validation examplesadvanced_auth.py- Advanced authentication with step-by-step process
Documentation
For detailed information about TMA Framework, see:
- MTProto Migration Guide - Complete migration documentation
- API Reference - Detailed API documentation
- Examples - Comprehensive usage examples
Requirements
- Python 3.12+
- httpx
- telethon
- playwright
- msgspec
- loguru
- pyyaml
- aiofiles
- cryptography
Performance
TMA Framework uses msgspec for high-performance data validation and serialization:
- 2-4x faster JSON serialization compared to Pydantic
- 2-3x faster data validation
- 2-3x less memory usage
- Runtime type checking with zero-cost validation
Run the performance benchmarks:
uv run python tests/test_performance.py
License
MIT License
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 tma_test_framework-1.1.0.tar.gz.
File metadata
- Download URL: tma_test_framework-1.1.0.tar.gz
- Upload date:
- Size: 154.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
59b33baeb3602adcb0e24f0eeefb3d93e7991f6a1e90e7b5be99adc857d558f3
|
|
| MD5 |
582f526db9c8cb29d41430388667efa9
|
|
| BLAKE2b-256 |
ee1fd94f157e3f1620793e980047f180701ac4526b50da4c0d846adc179cd203
|
File details
Details for the file tma_test_framework-1.1.0-py3-none-any.whl.
File metadata
- Download URL: tma_test_framework-1.1.0-py3-none-any.whl
- Upload date:
- Size: 17.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
64255a0adc7673bc79a7aa3f4b4a7e594460f043b177e7fc9a9b9162eca40fd5
|
|
| MD5 |
ce9196f067b90df90eb61176d0e15608
|
|
| BLAKE2b-256 |
85a0c5e9296b5972f45a2fb0a2094e041055ce83441382b017655235456aa8f5
|