A template for creating a Telegram bot using the Django web framework and pyTelegramBotAPI. This project is designed for a robust, production-ready deployment using Docker and Webhooks.
Why Django? It's a powerful and customizable framework. In this project, Django is used for setting up Webhooks via its admin panel and processing updates from Telegram's servers. It can also be easily extended to store data in a database and create complex user interactions.
Features:
- Django Admin Integration: Manage bot settings and actions directly from the admin panel.
- Webhook Ready: Built from the ground up to work with Telegram Webhooks.
- Dockerized: Comes with a
docker-compose.ymlfor easy and reproducible deployment. - Scalable Handler Architecture: Bot command handlers are split into modules for easy extension.
This guide helps you to set up a local environment for development using polling mode.
-
Preparation:
-
Install Git, Python 3.10+, and venv.
sudo apt install git python3 python3-venv -y -
Get the project:
git clone https://github.com/xinitd/django-telegram-bot.git cd django-telegram-bot
-
-
Environment setup:
-
Set up virtual environment:
python3 -m venv venv source venv/bin/activate -
Install requirements:
pip install -r requirements.txt -
Create your local environment file:
cp .env.template .envOpen the
.envfile and fill in yourSECRET_KEYandTELEGRAM_TOKEN. -
Apply database migrations:
python manage.py migrate
-
-
Run and test:
-
Run the bot:
python manage.py bot -
Send the
/startcommand to your bot in Telegram.
-
This guide provides an automated way to deploy the bot using Docker, PostgreSQL, Nginx, and Let's Encrypt for SSL.
-
Prerequisites:
-
A server (VPS) with a clean OS (e.g., Ubuntu 22.04).
-
A domain name pointing to your server's IP address.
-
-
Installation:
-
Clone the project:
git clone https://github.com/xinitd/django-telegram-bot.git cd django-telegram-bot -
Create and edit your environment file:
cp .env.template .env nano .envFill in all variables: DOMAIN_NAME, ADMIN_EMAIL, SECRET_KEY, etc. Set DEBUG=False.
-
Run the installer:
chmod +x install.sh sudo ./install.sh -
Apply database migrations:
docker compose exec backend python manage.py migrate -
Create a superuser:
docker compose exec backend python manage.py createsuperuser -
Collect static files:
docker compose exec backend python manage.py collectstatic --no-input
-
-
Final setup:
-
Open in browser
https://your-domain.com/admin/and log in. -
Navigate to the Sites section.
-
Click on
example.com, change the Domain name to your actual domain (e.g.,bot.mydomain.com), and save. -
Return to the Sites list, check the box next to your site, and select the Set Telegram webhook action from the dropdown. Click "Go".
-
(Optional) Use the Get webhook info action to verify that everything is working correctly.
-
