Skip to content

nessergio/tg-sm

Repository files navigation

Telegram Session Manager (tg-sm)

A REST API service for managing Telegram bot sessions across multiple accounts. Built with FastAPI and Telethon.

Features

  • 🔐 Manage multiple Telegram bot sessions
  • 🔄 Master/slave session architecture for verification code handling
  • 💾 Redis-backed session persistence
  • 🚀 FastAPI-based REST API
  • 🐳 Docker and docker-compose support
  • 🧪 Comprehensive test suite
  • 🔒 Security scanning with Trivy
  • 📦 Modern Python packaging with pyproject.toml

Project Structure

tg-sm/
├── src/
│   └── tg_sm/              # Main package
│       ├── __init__.py     # Package initialization
│       ├── main.py         # Application entry point
│       ├── api.py          # FastAPI routes and endpoints
│       ├── client.py       # Telegram client logic
│       └── models.py       # Pydantic data models
├── tests/                  # Test suite
│   ├── __init__.py
│   ├── test_models.py      # Model tests
│   └── test_api.py         # API endpoint tests
├── pyproject.toml          # Package configuration
├── requirements.txt        # Production dependencies
├── requirements-dev.txt    # Development dependencies
├── Dockerfile              # Multi-stage Docker build
├── docker-compose.yml      # Docker Compose configuration
├── .gitlab-ci.yml          # CI/CD pipeline
├── Makefile                # Common development tasks
├── LICENSE                 # MIT License
├── MANIFEST.in             # Distribution manifest
└── README.md               # This file

Installation

Using pip (Development)

# Install in editable mode with dev dependencies
make install-dev

# Or manually:
pip install -r requirements.txt
pip install -r requirements-dev.txt
pip install -e .

Using Docker

# Build and run with docker-compose
docker-compose up -d

# Or build manually
docker build -t tg-sm:latest .
docker run -p 8000:8000 --env-file .env tg-sm:latest

Configuration

Create a .env file in the root directory:

# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0

# Application Configuration
HOST=0.0.0.0
PORT=8000

Usage

Running the Application

# Using make
make run

# Using docker-compose
make docker-up

# Using Python directly
python -m tg_sm.main

API Documentation

Once running, access the interactive API documentation at:

Example API Calls

Create/Update a Bot

curl -X POST http://localhost:8000/bot/bot1 \
  -H 'Content-Type: application/json' \
  -d '{
    "api_id": 12345,
    "api_hash": "your_api_hash",
    "phone": "1234567890"
  }'

Create a Session

# First request (triggers verification code)
curl -X POST http://localhost:8000/session/bot1/master

# Second request (with verification code)
curl -X POST http://localhost:8000/session/bot1/master \
  -H 'Content-Type: application/json' \
  -d '{"code": "12345"}'

Get a Session

curl http://localhost:8000/session/bot1/master

Development

Running Tests

# Run tests with coverage
make test

# Run tests without coverage (faster)
make test-fast

# Run specific test file
pytest tests/test_models.py -v

Code Quality

# Run all linters
make lint

# Format code
make format

# Individual tools
ruff check src/
black --check src/
mypy src/tg_sm/

Available Make Commands

make help              # Show all available commands
make install           # Install production dependencies
make install-dev       # Install development dependencies
make test              # Run tests with coverage
make lint              # Run all linters
make format            # Format code
make clean             # Clean cache and build artifacts
make docker-build      # Build Docker image
make docker-up         # Start services with docker-compose
make docker-down       # Stop services
make docker-logs       # View logs
make run               # Run the application locally

CI/CD Pipeline

The GitLab CI pipeline includes:

  1. Lint Stage: Code quality checks with ruff, black, and mypy
  2. Test Stage: Unit tests with pytest and coverage reporting
  3. Build Stage: Docker image build and push to registry
  4. Scan Stage: Security scanning with Trivy and dependency checks

Architecture

Master/Slave Session Model

  • Master Session: Receives and intercepts verification codes from Telegram
  • Slave Sessions: Derived sessions that use the master for authentication

Session Flow

  1. Create a bot configuration with API credentials
  2. Request a session (master or slave)
  3. For master: Provide verification code manually
  4. For slaves: Master session intercepts and provides code automatically
  5. Session string is stored in Redis for persistence

Security

  • Multi-stage Docker build for smaller attack surface
  • Non-root user in Docker container
  • Security scanning with Trivy in CI/CD
  • Dependency vulnerability checking with Safety
  • Environment-based configuration (no hardcoded secrets)

Dependencies

Production

  • FastAPI (0.112.0): Modern web framework
  • Telethon (1.36.0): Telegram client library
  • Redis (5.0.8): Session storage
  • Uvicorn (0.30.5): ASGI server
  • python-dotenv (1.0.1): Environment configuration

Development

  • pytest: Testing framework
  • pytest-asyncio: Async test support
  • pytest-cov: Coverage reporting
  • httpx: FastAPI testing
  • ruff: Fast Python linter
  • black: Code formatter
  • mypy: Static type checker

Contributing

  1. Install development dependencies: make install-dev
  2. Make your changes
  3. Run tests: make test
  4. Run linters: make lint
  5. Format code: make format
  6. Update CHANGELOG.md if needed
  7. Commit and push

See MIGRATION_GUIDE.md for detailed information about the project structure.

License

This project is licensed under the MIT License with attribution requirement - see the LICENSE file for details.

Copyright (c) 2025 Serhii Nesterenko

Author

Serhii Nesterenko (ser@nesterenko.net)

Troubleshooting

Redis Connection Issues

Ensure Redis is running:

# Using docker-compose
docker-compose up -d redis

# Check Redis logs
docker-compose logs redis

Import Errors

Make sure the package is installed in editable mode:

pip install -e .

Port Already in Use

Change the port in .env or docker-compose.yml:

PORT=8001

Documentation

  • README.md - This file, main documentation
  • LICENSE - MIT License with attribution requirement

Version

Current version: 0.1.0

See CHANGELOG.md for version history.

About

Telegram Session Manager

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published