A modular Telegram Bot boilerplate with database integration. This project provides a structured foundation for building Telegram bots with a clean architecture that's easy to extend.
- Modular Architecture: Easily add new commands and features.
- Dual Database Support:
- SQLAlchemy: For relational database operations (PostgreSQL, SQLite, etc.).
- Motor (Asyncio): For non-blocking MongoDB operations.
- Developer Experience:
- CLI Tool: A
manage.pyscript for running the bot, with hot-reloading for development. - Docker Support: Includes a
Dockerfileanddocker-compose.ymlfor easy containerization.
- CLI Tool: A
- Core Functionality:
- User Tracking: Tracks user join dates and last seen times.
- Rate Limiting & Error Handling: Decorators to protect and manage your bot's functions.
- Utility Functions: Helpers for common tasks like parsing and formatting.
- Asynchronous: Built with
asyncioand usesuvloopon non-Windows systems for high performance. - Configuration: Uses a
.envfile for easy and secure configuration management.
- Python 3.7+
- Docker (optional, for containerized deployment)
- Dependencies listed in
requirements.txt:- Pyrogram (Telegram client library)
- SQLAlchemy (ORM for database operations)
- psycopg2-binary (PostgreSQL adapter)
- motor (Asynchronous MongoDB driver)
- tgcrypto (Fast cryptography library for Telegram)
- python-dotenv (Environment variable management)
- watchdog (For file system monitoring and hot-reloading)
- typer (For creating the command-line interface)
- uvloop (Automatically installed on non-Windows platforms for improved performance)
-
Clone the repository
git clone https://github.com/yourusername/Telegram-Bot.git cd Telegram-Bot -
Install dependencies
pip install -r requirements.txt
-
Configure the bot
- Copy the sample environment file and edit it with your credentials:
cp .env.sample .env
- Open
.envand fill in your details (BOT_TOKEN,API_ID,API_HASH, etc.).
- Copy the sample environment file and edit it with your credentials:
The bot is managed through a command-line interface in manage.py.
-
Run normally:
python manage.py
-
Run with hot-reloading for development: This will automatically restart the bot whenever you save a change in the
Bot/directory.python manage.py --reload
This project is fully configured to run with Docker for consistent and isolated deployments.
-
Build and run the container: Make sure your
.envfile is configured. Then, run:docker-compose up --build
-
Run in the background (detached mode):
docker-compose up --build -d
-
To stop the container:
docker-compose down
Telegram-Bot/
├── Bot/ # Main bot package
│ ├── core/ # Core functionality
│ ├── sql/ # SQLAlchemy database models
│ ├── mongo/ # MongoDB models
│ ├── modules/ # Bot command modules
│ ├── config.py # Configuration settings
│ ├── __init__.py # Bot initialization
│ └── __main__.py # Entry point
├── .env.sample # Sample environment variables
├── docker-compose.yml # Docker Compose configuration
├── Dockerfile # Docker image definition
├── manage.py # Command-line interface for management
├── requirements.txt # Dependencies
└── README.md # Documentation
The bot uses environment variables for configuration, which can be set in the .env file. This allows for easier deployment across different environments while keeping sensitive information secure.
Available environment variables:
BOT_TOKEN: Telegram bot token from BotFatherAPI_ID: Telegram API IDAPI_HASH: Telegram API HashDB_URI: Database connection string for SQLAlchemyMONGO_URI: MongoDB connection string (optional)
The bot uses SQLAlchemy ORM for SQL database operations. By default, it's configured to use SQLite, but you can change the DB_URI in config.py to use other database engines like PostgreSQL or MySQL.
The SQLAlchemy database module provides:
- A base model system in
db/__init__.py - User tracking functionality in
db/users.pywith:- User ID and username tracking
- First and last name storage
- Join date and last seen tracking
For more detailed information about the SQLAlchemy database structure and operations, see the Database Documentation.
The bot also supports MongoDB for NoSQL database operations using Motor AsyncIO for asynchronous operations. MongoDB integration is optional and will be enabled only if MONGO_URI is provided in the configuration.
The MongoDB module provides:
- Asynchronous MongoDB connection setup in
mongo/__init__.py - Asynchronous user tracking functionality in
mongo/users.pywith similar features to the SQLAlchemy version - All database operations are non-blocking, using
async/awaitsyntax
For more detailed information about the MongoDB structure and operations, see the MongoDB Documentation.
The bot has a modular design that makes it easy to add new commands and features:
- Create a new Python file in the
Bot/modules/directory - Define your command handlers using the Pyrogram decorator system
- The module will be automatically loaded at startup
/start- Start the bot and get a welcome message/help- Show available commands/info- Show information about yourself/stats- Show bot statistics
For more information about creating and customizing modules, see the Modules Documentation.
The bot includes several decorators in the Bot/core/decorators directory:
rate_limit.py- Rate limit a function to a certain number of calls per time windowtracking.py- Track user activityerror_handler.py- Handle errors in functions
The bot includes utility functions in the Bot/core/utils directory:
parser.py- Parse command arguments from a message textformatting.py- Format user mentions and time intervals
To add new features:
- New commands: Add new modules in the
Bot/modules/directory - Database models: Create new models in the
Bot/db/directory - Configuration: Add new configuration options in
Bot/config.py - Utility functions: Add new utility functions in the appropriate directory
The bot includes a comprehensive logging system configured in Bot/__init__.py. Logs are saved to log.txt and also output to the console.
This project is licensed under the terms included in the LICENSE file.