Skip to content

ShenzeSun/tgbotResponseTest

Repository files navigation

Telegram Bot Response Time Monitor

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.

πŸš€ Features

πŸ”„ Session Management

  • 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

πŸ“Š Monitoring & Analytics

  • 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

πŸ›‘οΈ Robustness & Reliability

  • 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)

πŸ”§ Developer Experience

  • Environment Configuration: Secure credential management with .env files
  • 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

πŸ”’ Security & Privacy

  • Credential Protection: API keys stored in .env file (never in code)
  • Session Encryption: Telegram sessions use encrypted storage
  • Git Safety: All sensitive files automatically excluded from version control

πŸ“‹ Requirements

  • Python 3.7+
  • Telegram API credentials (API ID and API Hash)
  • Active Telegram account

πŸš€ Quick Start

Complete setup in 5 steps:

  1. Clone and setup:

    git clone <repository-url>
    cd tgbotResponseTest
    pip install -r requirements.txt
  2. Configure credentials:

    python setup.py
    # Interactive setup - enter your API credentials
  3. Validate setup:

    python test_config.py
    # Confirms everything is ready
  4. Test session management:

    python test_session_fix.py
    # Validates session handling
  5. Start monitoring:

    python res_bot.py
    # First run: Login with phone + verification code
    # Future runs: Instant startup, no login needed!

πŸ”‘ First Run Experience

$ 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...

⚑ Subsequent Runs

$ python res_bot.py
πŸ”§ Loading configuration...
πŸ’Ύ Found existing session - no login required
πŸ”„ Using existing session (no login required)
βœ… Successfully connected to Telegram
πŸš€ Starting monitoring...

οΏ½πŸ› οΈ Installation

  1. Clone the repository:

    git clone <repository-url>
    cd tgbotResponseTest
  2. Create a virtual environment (recommended):

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies:

    pip install -r requirements.txt
  4. Set up configuration:

    cp .env.example .env

    Edit .env with 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

πŸ”‘ Getting Telegram API Credentials

  1. Visit my.telegram.org/apps
  2. Log in with your Telegram account
  3. Create a new application
  4. Copy the API ID and API Hash to your .env file

βš™οΈ Configuration Options

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 ❌

πŸ“ Example Configuration

# 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=true

🚦 Usage

🎯 Primary Usage

Start monitoring:

python res_bot.py

Stop monitoring:

  • Press Ctrl+C (graceful shutdown)
  • Create stop.flag file in project directory
  • Automatic stop after MAX_RUNTIME_HOURS

πŸ› οΈ Utility Scripts

Setup and Configuration:

python setup.py           # Interactive setup wizard
python test_config.py     # Validate configuration
python test_session_fix.py # Test session management

Session 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 mode

🌍 Environment Variables

You 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.py

πŸ”„ Configuration Options

Run with custom settings:

# Set custom message count and threshold
export MESSAGE_COUNT=50
export RESPONSE_THRESHOLD_SECONDS=3
python res_bot.py

Single run (no loop):

export LOOP=false
python res_bot.py

πŸ“Š Output and Logging

The application provides enhanced logging with emojis and detailed information:

🎨 Log Message Types

  • ⚑ 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

πŸ“ Enhanced Log Output Example

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.

πŸ“ Log Files

  • Console Output: Real-time monitoring with colors and emojis
  • File Output: bot_response_times.log for permanent records
  • Session Logs: Stored in sessions/ directory (auto-managed)

πŸ›‘οΈ Error Handling

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

πŸ”„ Session Management

The application now features persistent session management, meaning you only need to authenticate once:

πŸ”‘ First Run (Authentication Required)

  • 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

πŸš€ Subsequent Runs (No Authentication)

  • Sessions are automatically reused
  • No need to re-enter credentials or verification codes
  • Instant startup and monitoring

πŸ› οΈ Session Management Tools

List existing sessions:

python manage_sessions.py list

Clear all sessions:

python manage_sessions.py clear

Clear specific session:

python manage_sessions.py clear @botusername

Interactive management:

python manage_sessions.py

πŸ“ Session Storage

  • 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

πŸ’‘ Session Tips

  • 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

πŸ“ Project Structure

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

πŸ“‚ Directory Breakdown

Core Application:

  • res_bot.py - Main monitoring application with all features
  • requirements.txt - Minimal dependencies (pyrogram, python-dotenv)

Utilities & Setup:

  • setup.py - Interactive configuration wizard
  • test_config.py - Validates setup and dependencies
  • test_session_fix.py - Tests session management functionality
  • manage_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 documentation
  • PROJECT_SUMMARY.md - High-level project overview
  • SESSION_IMPROVEMENTS.md - Session management details
  • LICENSE - MIT license for open source distribution

Generated Files:

  • sessions/ - Directory for persistent Telegram sessions
  • bot_response_times.log - Application logs and monitoring data

πŸ› Troubleshooting

Common Issues

  1. "API_ID is required"

    • Ensure your .env file contains valid API_ID and API_HASH
    • Check that the .env file is in the project root directory
  2. "Authentication failed"

    • Verify your API credentials are correct
    • Delete session files and try again
    • Ensure your Telegram account is active
  3. "Rate limited"

    • The application handles rate limiting automatically
    • Consider increasing delays between messages if persistent
  4. "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

Debug Mode

For additional debugging, you can modify the logging level in the code:

logger.setLevel(logging.DEBUG)

🀝 Contributing

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.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ License

This project is open source and available under the MIT License.

⚠️ Disclaimer

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.

πŸ”— Links

πŸ“ž Support

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

About

Telegram Bot Response Time Monitor

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages