A production-ready Python application for monitoring and measuring response times of Telegram bots. This tool helps you track bot performance, identify slow responses, and maintain quality metrics for your Telegram bot services.
- One-Time Authentication: Login once with phone/code, then run forever
- Persistent Sessions: Automatic session storage and reuse
- Session Tools: Built-in utilities to manage, list, and clear sessions
- Secure Storage: Sessions stored in dedicated directory, excluded from git
- Real-time Monitoring: Send messages to bots and measure response times
- Performance Metrics: Track fast/slow responses with configurable thresholds
- Batch Processing: Monitor bots in configurable batches with intervals
- Detailed Logging: Comprehensive logging to both file and console with emojis
- Advanced Error Handling: Handles API rate limits, connection issues, and auth errors
- Graceful Shutdown: Proper signal handling (Ctrl+C, SIGTERM) for clean termination
- Auto Recovery: Handles network issues and Telegram API errors gracefully
- Stop Controls: Multiple ways to stop monitoring (signals, flag files, time limits)
- Environment Configuration: Secure credential management with
.envfiles - Guided Setup: Interactive setup script for easy configuration
- Configuration Validation: Built-in tests to validate setup before running
- Session Testing: Utilities to test and validate session management
- Credential Protection: API keys stored in
.envfile (never in code) - Session Encryption: Telegram sessions use encrypted storage
- Git Safety: All sensitive files automatically excluded from version control
- Python 3.7+
- Telegram API credentials (API ID and API Hash)
- Active Telegram account
Complete setup in 5 steps:
-
Clone and setup:
git clone <repository-url> cd tgbotResponseTest pip install -r requirements.txt
-
Configure credentials:
python setup.py # Interactive setup - enter your API credentials -
Validate setup:
python test_config.py # Confirms everything is ready -
Test session management:
python test_session_fix.py # Validates session handling -
Start monitoring:
python res_bot.py # First run: Login with phone + verification code # Future runs: Instant startup, no login needed!
$ python res_bot.py
π§ Loading configuration...
β
Configuration loaded successfully
π― Target bot: @your_bot
π No existing session found - first-time login required
π± You will need to enter your phone number and verification code
π Connecting to Telegram...
Please enter your phone number: +1234567890
Please enter the code: 12345
β
Successfully connected to Telegram
π€ Authenticated as: Your Name (@your_username)
π Starting monitoring...$ python res_bot.py
π§ Loading configuration...
πΎ Found existing session - no login required
π Using existing session (no login required)
β
Successfully connected to Telegram
π Starting monitoring...-
Clone the repository:
git clone <repository-url> cd tgbotResponseTest
-
Create a virtual environment (recommended):
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Set up configuration:
cp .env.example .env
Edit
.envwith your configuration:# Telegram API Configuration API_ID=your_api_id_here API_HASH=your_api_hash_here # Bot Monitoring Configuration TARGET_BOT_USERNAME=@your_bot_username DURATION_MINUTES=1 MESSAGE_COUNT=20 MAX_RUNTIME_HOURS=24 RESPONSE_THRESHOLD_SECONDS=5
- Visit my.telegram.org/apps
- Log in with your Telegram account
- Create a new application
- Copy the
API IDandAPI Hashto your.envfile
| Variable | Description | Default | Required |
|---|---|---|---|
API_ID |
Telegram API ID | - | β |
API_HASH |
Telegram API Hash | - | β |
TARGET_BOT_USERNAME |
Bot username to monitor | @hwjz | β |
DURATION_MINUTES |
Duration between monitoring batches | 1 | β |
MESSAGE_COUNT |
Number of messages per batch | 20 | β |
MAX_RUNTIME_HOURS |
Maximum total runtime | 24 | β |
RESPONSE_THRESHOLD_SECONDS |
Threshold for slow responses | 5 | β |
LOOP |
Enable continuous monitoring | true | β |
# Telegram API Configuration (Required)
API_ID=12345678
API_HASH=abcd1234efgh5678ijkl9012mnop3456
# Bot Monitoring Configuration (Optional)
TARGET_BOT_USERNAME=@your_bot_here
DURATION_MINUTES=2
MESSAGE_COUNT=10
MAX_RUNTIME_HOURS=12
RESPONSE_THRESHOLD_SECONDS=3
LOOP=trueStart monitoring:
python res_bot.pyStop monitoring:
- Press
Ctrl+C(graceful shutdown) - Create
stop.flagfile in project directory - Automatic stop after
MAX_RUNTIME_HOURS
Setup and Configuration:
python setup.py # Interactive setup wizard
python test_config.py # Validate configuration
python test_session_fix.py # Test session managementSession Management:
python manage_sessions.py list # List all sessions
python manage_sessions.py clear # Clear all sessions
python manage_sessions.py clear @botname # Clear specific session
python manage_sessions.py # Interactive modeYou can also use environment variables instead of .env file:
export API_ID=your_api_id
export API_HASH=your_api_hash
export TARGET_BOT_USERNAME=@your_bot
python res_bot.pyRun with custom settings:
# Set custom message count and threshold
export MESSAGE_COUNT=50
export RESPONSE_THRESHOLD_SECONDS=3
python res_bot.pySingle run (no loop):
export LOOP=false
python res_bot.pyThe application provides enhanced logging with emojis and detailed information:
- β‘ Fast Response: Response received within threshold
- π Slow Response: Response took longer than threshold
- β No Response: No response received within 10 seconds
- π¦ Rate Limited: Temporary rate limiting by Telegram
- π Session Status: Session creation and reuse information
- π€ Authentication: User info and login status
- π Statistics: Batch results and performance metrics
β οΈ Warnings: Non-critical issues- β Errors: Critical errors requiring attention
2025-07-03 19:41:52 - INFO - π§ Loading configuration...
2025-07-03 19:41:52 - INFO - β
Configuration loaded successfully
2025-07-03 19:41:52 - INFO - π― Target bot: @your_bot
2025-07-03 19:41:52 - INFO - οΏ½ Found existing session - no login required
2025-07-03 19:41:52 - INFO - οΏ½π Starting Telegram Bot Response Monitor
2025-07-03 19:41:52 - INFO - π Configuration: Target: @your_bot, Messages per batch: 20, Duration: 1 minutes, Loop: True
2025-07-03 19:41:52 - INFO - π Starting batch loop #1
2025-07-03 19:41:52 - INFO - π [@your_bot] Using existing session (no login required)
2025-07-03 19:41:52 - INFO - π [@your_bot] Connecting to Telegram...
2025-07-03 19:41:53 - INFO - β
[@your_bot] Successfully connected to Telegram
2025-07-03 19:41:53 - INFO - π€ [@your_bot] Authenticated as: Your Name (@your_username)
2025-07-03 19:41:53 - INFO - πΉ [@your_bot] Sending message #1: aB3kM9pL
2025-07-03 19:41:54 - INFO - β‘ [@your_bot] Fast response time: 0.85s
2025-07-03 19:41:57 - INFO - πΉ [@your_bot] Sending message #2: xY7nQ2vF
2025-07-03 19:42:03 - WARNING - π [@your_bot] Slow response (6.12s) for message 'xY7nQ2vF'
2025-07-03 19:42:15 - INFO - π [@your_bot] Batch #1 Result: 1 slow responses out of 20 messages.- Console Output: Real-time monitoring with colors and emojis
- File Output:
bot_response_times.logfor permanent records - Session Logs: Stored in
sessions/directory (auto-managed)
The application includes comprehensive error handling for:
- Authentication Errors: Invalid API credentials
- Rate Limiting: Automatic retry with exponential backoff
- Network Issues: Connection timeouts and network errors
- API Errors: Telegram API-specific errors
- Configuration Errors: Invalid or missing configuration values
The application now features persistent session management, meaning you only need to authenticate once:
- On first run, you'll need to provide your phone number and verification code
- Sessions are automatically saved in the
sessions/directory - This is a one-time setup per account
- Sessions are automatically reused
- No need to re-enter credentials or verification codes
- Instant startup and monitoring
List existing sessions:
python manage_sessions.py listClear all sessions:
python manage_sessions.py clearClear specific session:
python manage_sessions.py clear @botusernameInteractive management:
python manage_sessions.py- Sessions are stored in
sessions/directory - Files are automatically excluded from git
- Safe to delete if you want to re-authenticate
- Each bot gets its own session file
- Sessions persist across computer restarts
- If authentication fails, clear the session and try again
- Sessions are tied to your Telegram account, not the bot
- You can run multiple bots with the same session
tgbotResponseTest/
βββ res_bot.py # π Main monitoring application
βββ manage_sessions.py # π§ Session management utility
βββ setup.py # π― Guided setup wizard
βββ test_config.py # β
Configuration validator
βββ test_session_fix.py # π Session management tester
βββ requirements.txt # π¦ Python dependencies
βββ .env.example # π Environment configuration template
βββ .env # π Your configuration (not in git)
βββ .gitignore # π« Git ignore rules
βββ README.md # π Documentation (this file)
βββ LICENSE # βοΈ MIT license
βββ PROJECT_SUMMARY.md # π Project overview
βββ SESSION_IMPROVEMENTS.md # π Session management docs
βββ __init__.py # π Package initialization
βββ sessions/ # πΎ Session storage directory (auto-created)
βββ bot_response_times.log # π Application logs (generated)
βββ .git/ # ποΈ Git repository data
Core Application:
res_bot.py- Main monitoring application with all featuresrequirements.txt- Minimal dependencies (pyrogram, python-dotenv)
Utilities & Setup:
setup.py- Interactive configuration wizardtest_config.py- Validates setup and dependenciestest_session_fix.py- Tests session management functionalitymanage_sessions.py- Session management tools
Configuration:
.env.example- Template configuration file.env- Your actual configuration (excluded from git).gitignore- Comprehensive exclusions for Python projects
Documentation:
README.md- Complete documentationPROJECT_SUMMARY.md- High-level project overviewSESSION_IMPROVEMENTS.md- Session management detailsLICENSE- MIT license for open source distribution
Generated Files:
sessions/- Directory for persistent Telegram sessionsbot_response_times.log- Application logs and monitoring data
-
"API_ID is required"
- Ensure your
.envfile contains validAPI_IDandAPI_HASH - Check that the
.envfile is in the project root directory
- Ensure your
-
"Authentication failed"
- Verify your API credentials are correct
- Delete session files and try again
- Ensure your Telegram account is active
-
"Rate limited"
- The application handles rate limiting automatically
- Consider increasing delays between messages if persistent
-
"No response within 10s"
- The target bot might be offline or slow
- Check if the bot username is correct
- Verify the bot is responsive manually
For additional debugging, you can modify the logging level in the code:
logger.setLevel(logging.DEBUG)Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is open source and available under the MIT License.
This tool is for legitimate monitoring purposes only. Please respect Telegram's Terms of Service and rate limits. The authors are not responsible for any misuse of this tool.
If you encounter any issues or have questions, please open an issue in the GitHub repository with:
- Detailed description of the problem
- Steps to reproduce
- Your configuration (without sensitive data)
- Relevant log output