Skip to content

openskillsagent/telegram

Repository files navigation

Telegram Bot Message Receiver

A standalone Python application that connects to Telegram as a bot and logs all direct messages received.

Features

  • ✅ Connects to Telegram bot using token from .env file
  • ✅ Receives and logs direct messages only
  • ✅ Logs messages in format: sender - timestamp - text
  • ✅ Appends messages to MESSAGES.txt file
  • ✅ Prints messages to console in real-time
  • ✅ Graceful error handling with logging
  • ✅ Stays connected and consumes messages continuously
  • ✅ Comprehensive test coverage (27 unit/integration tests)

Project Structure

telegram/
├── main.py                    # Application entry point
├── .env                       # Bot token & name configuration
├── MESSAGES.txt              # Log file for messages
├── src/
│   ├── env_loader.py        # Load token & name from .env
│   ├── message_formatter.py # Format messages (sender - timestamp - text)
│   ├── file_logger.py       # Append messages to MESSAGES.txt
│   ├── message_handler.py   # Filter direct messages & extract data
│   └── bot_handler.py       # Telegram bot connection & polling
├── test_env_loader.py       # Tests for .env loading
├── test_message_formatter.py # Tests for message formatting
├── test_file_logger.py      # Tests for file logging
├── test_message_handler.py  # Tests for message handling
└── test_integration.py      # Integration tests for full pipeline

Setup

1. Create Virtual Environment

python3 -m venv venv
source venv/bin/activate

2. Install Dependencies

pip install python-telegram-bot --upgrade

3. Configure Bot Token and Name

Create a .env file in the project root with your bot configuration:

echo "PRIVATE_BOT_NAME=your_bot_username" > .env
echo "PRIVATE_BOT_TOKEN=your_bot_token_here" >> .env

Get your bot token from @BotFather on Telegram. Use your bot's username (without @) for PRIVATE_BOT_NAME.

Running the Application

source venv/bin/activate
python3 main.py

The bot will:

  1. Load the bot name and token from .env
  2. Connect to Telegram
  3. Start polling for messages
  4. Print and log all direct messages received

Message Format

Messages are logged in the format:

sender - YYYY-MM-DD HH:MM:SS - message text

Example:

John Doe - 2026-02-24 10:30:45 - Hello, how are you?

Running Tests

Run all tests:

source venv/bin/activate
python3 -m unittest discover -s . -p "test_*.py" -v

Run specific test file:

python3 -m unittest test_env_loader.py -v
python3 -m unittest test_message_formatter.py -v
python3 -m unittest test_file_logger.py -v
python3 -m unittest test_message_handler.py -v
python3 -m unittest test_integration.py -v

Test Coverage

  • test_env_loader.py: 4 tests

    • Load token from .env file
    • Handle missing token
    • Handle missing .env file
    • Strip whitespace from token
  • test_message_formatter.py: 5 tests

    • Format messages correctly
    • Handle special characters
    • Handle multiline text
    • Format timestamps as YYYY-MM-DD HH:MM:SS
    • Handle empty text
  • test_file_logger.py: 5 tests

    • Create MESSAGES.txt if not exists
    • Append to existing file
    • Add newlines to messages
    • Preserve message order
    • Handle multiline messages
  • test_message_handler.py: 10 tests

    • Filter direct messages only
    • Extract sender from user data
    • Use username as fallback
    • Use user ID as final fallback
    • Extract message text
    • Extract message timestamp
  • test_integration.py: 3 tests

    • Full message pipeline (load → format → log)
    • Multiple messages logged in order
    • Special characters preserved

Architecture

TDD Approach

This project was built using Test-Driven Development (TDD):

  1. Phase 1: Write unit tests for each component
  2. Phase 2: Implement components to pass tests
  3. Phase 3: Write integration tests
  4. Phase 4: Test full pipeline together

Component Responsibilities

  • env_loader.py: Loads and validates bot token and name from .env
  • message_formatter.py: Formats messages with sender, timestamp, and text
  • file_logger.py: Appends formatted messages to file with newlines
  • message_handler.py: Filters direct messages and extracts sender/timestamp/text data
  • bot_handler.py: Manages Telegram bot connection, polling, and error handling
  • main.py: Entry point that orchestrates all components

Error Handling

The application will:

  • Log errors to console/stderr
  • Catch connection failures and exit with error code
  • Log all operations to help with debugging

Usage Example

# 1. Setup
python3 -m venv venv
source venv/bin/activate
pip install python-telegram-bot --upgrade

# 2. Configure
echo "PRIVATE_BOT_NAME=your_bot_username" > .env
echo "PRIVATE_BOT_TOKEN=YOUR_TOKEN" >> .env

# 3. Run tests
python3 -m unittest discover -s . -p "test_*.py"

# 4. Start the bot
python3 main.py

Send a direct message to your bot on Telegram, and it will:

  • Print to console
  • Append to MESSAGES.txt

Example output:

John Doe - 2026-02-24 10:30:45 - Hello bot!
Jane Smith - 2026-02-24 10:32:10 - How are you?

Stopping the Bot

Press Ctrl+C to gracefully shutdown the bot.

Troubleshooting

Bot not receiving messages

  • Ensure bot is started (@BotFather)
  • Check token is correct in .env
  • Verify internet connection
  • Send direct message (not group chat)

Token loading error

  • Check .env file exists in project root
  • Verify line format: PRIVATE_BOT_TOKEN=token_here
  • No extra spaces around = or token

File permission error

  • Ensure write permissions in project directory
  • Check MESSAGES.txt isn't locked by another process

Testing Notes

  • All tests use mocking to avoid actual Telegram API calls
  • Tests verify format, not network connectivity
  • Integration tests verify full pipeline works together
  • 27 tests total, all passing

Dependencies

  • python-telegram-bot: Telegram Bot API wrapper (installed via pip)
  • Python 3.9+: Runtime environment
  • Standard library: asyncio, logging, pathlib

License

See project root for license information.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages