A standalone Python application that connects to Telegram as a bot and logs all direct messages received.
- ✅ Connects to Telegram bot using token from
.envfile - ✅ Receives and logs direct messages only
- ✅ Logs messages in format:
sender - timestamp - text - ✅ Appends messages to
MESSAGES.txtfile - ✅ 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)
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
python3 -m venv venv
source venv/bin/activatepip install python-telegram-bot --upgradeCreate 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" >> .envGet your bot token from @BotFather on Telegram. Use your bot's username (without @) for PRIVATE_BOT_NAME.
source venv/bin/activate
python3 main.pyThe bot will:
- Load the bot name and token from
.env - Connect to Telegram
- Start polling for messages
- Print and log all direct messages received
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?
Run all tests:
source venv/bin/activate
python3 -m unittest discover -s . -p "test_*.py" -vRun 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_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
This project was built using Test-Driven Development (TDD):
- Phase 1: Write unit tests for each component
- Phase 2: Implement components to pass tests
- Phase 3: Write integration tests
- Phase 4: Test full pipeline together
- 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
The application will:
- Log errors to console/stderr
- Catch connection failures and exit with error code
- Log all operations to help with debugging
# 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.pySend 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?
Press Ctrl+C to gracefully shutdown the bot.
- Ensure bot is started (@BotFather)
- Check token is correct in
.env - Verify internet connection
- Send direct message (not group chat)
- Check
.envfile exists in project root - Verify line format:
PRIVATE_BOT_TOKEN=token_here - No extra spaces around
=or token
- Ensure write permissions in project directory
- Check MESSAGES.txt isn't locked by another process
- 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
- python-telegram-bot: Telegram Bot API wrapper (installed via pip)
- Python 3.9+: Runtime environment
- Standard library: asyncio, logging, pathlib
See project root for license information.