A Python-based Telegram store bot integrated with a Django backend, featuring webhook support, Redis queueing, and async background tasks. Users can browse products, top up balances using TON cryptocurrency, and purchase items β all from Telegram.
This code is based on telegram-store-bot but adapted for webhook architecture.
- Features β¨
- Highlights π
- Setup & Installation π οΈ
- Bot Commands π
- Webhook & Redis Overview π§
- Database Notes βοΈ
- Best Practices β
- Architecture Diagram π§©
- Security & Privacy π
- Testing & Development π§ͺ
- License π
- Disclaimer π€
- Product browsing by categories π·οΈ
- Purchase products using TON cryptocurrency π°
- Generate TON payment links π
- Track user transactions and purchase history π
- Background tasks:
- TON price updater
- TON transaction processor
- Redis consumer for webhook queue
- Multi-language support π
- Timezone handling β°
- Webhook Integration: Efficient Telegram update handling with Uvicorn. π
- Redis Queue: Django receives webhooks β pushes to Redis β async bot consumes. β‘
- Async Background Tasks: Runs safely alongside update processing.
- TON Center API v3 integration ensures no on-chain transactions are skipped.
- Atomic, idempotent transaction processing prevents double-crediting.
- LRUCache for recent TX deduplication; TTL caches for settings and price.
- Clear separation: Django for admin & ORM; bot runs independently.
- Clone repository:
git clone --branch TON-payment https://github.com/RezaTaheri01/telegram-store-bot-web-hook.git
cd telegram-store-bot-web-hook/telegram_store- Install dependencies:
pip install --upgrade pip
pip install -r req.txt- Configure
.envfile:
# Bot Token (@BotFather)
TOKEN=your-telegram-api-token
BOT_LINK=https://t.me/giftShop2025Bot
# Command to refresh bot cache
UPDATE_SETTING_COMMAND=update
# Django secret key
SECRET_KEY=CHANGE_ME_IN_PRODUCTION
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1,your-domain.com,www.your-domain.com
ADMIN_URL=adminadmin
# Redis URL (used by bot and Django)
REDIS_URL=redis://localhost:6379/0
TELEGRAM_WEBHOOK_SECRET=telegram
# Optional: Site domain
# SITE_DOMAIN=https://your-domain.com
# Database (example)
#DB_ENGINE=postgresql
#DB_NAME=mydb
#DB_USER=postgres
#DB_PASS=secret123
#DB_HOST=localhost
#DB_PORT=5432Note: For local testing, use a tunnel (e.g., Ngrok or Cloudflare Tunnel) to expose HTTPS for webhooks.
- Run migrations & create superuser:
python manage.py makemigrations users payment products
python manage.py migrate
python manage.py createsuperuser- Start Django web server:
uvicorn telegram_store.asgi:application --host 0.0.0.0 --port 8000Production: use Gunicorn or Uvicorn with multiple workers for webhook handling
- Create BotSettings in Django admin (mandatory before starting the bot):
- Open Django admin:
https://your-domain.com/adminadmin - Create a new
BotSettingentry with at least:- Wallet Currency (e.g., USD)
- TON Price Delay (seconds, e.g., 120)
- TON Fetch Limit (e.g., 250)
- TON Network Delay (seconds, e.g., 10)
- Optional: Disable product images for faster UI
- Start Redis server / connect to Redis
Redis is used as a message queue between the Django webhook and the async bot worker.
Flow:
Telegram β Django webhook β Redis β Bot worker
You can also run Redis via Docker (cross-platform, recommended).
sudo apt update
sudo apt install redis-serverStart Redis and enable it on boot:
sudo systemctl start redis
sudo systemctl enable redisVerify Redis is running:
redis-cli ping
# PONGSet Redis connection in .env:
REDIS_URL=redis://localhost:6379/0Use a managed Redis service or a dedicated Redis instance.
Ensure the REDIS_URL in .env matches your Redis instance and is reachable by both Django and the bot worker.
- Set Telegram webhook (one-time):
curl -F "url=https://your-domain.com/webhook/TELEGRAM_WEBHOOK_SECRET/" https://api.telegram.org/bot<TOKEN>/setWebhook- Start bot worker:
python bot.pyProduction: run as a background service, via nohup, systemd, or Docker, so it stays alive and automatically restarts if it crashes.
The bot will now consume updates from Redis and process background tasks.
/startβ Start bot and show main menu/menuβ Show main menu/balanceβ Check balance/payβ Generate TON payment link/set_timezoneβ Set timezone (requires location)Update Settingsβ Refresh bot settings
- Telegram β Django webhook: Updates arrive at Django endpoint.
- Django β Redis: Update JSON is pushed to
telegram_updateslist. - Bot worker: Async consumer pops updates from Redis and processes them.
- Background tasks:
- TON price updater
- TON transaction processor
- Any other periodic tasks run alongside update processing
This ensures reliable async processing and avoids blocking webhook requests.
TonCursor: tracks last processed transaction (last_lt,last_hash)Transaction.tx_id: unique for each paymentProductDetail: inventory rows; lock one row per purchase withselect_for_update(skip_locked=True)
- Use PostgreSQL in production for safe row-level locking.
- Keep
TON Fetch Limitmoderate (100β500). - Monitor LRU cache size (default: 10,000 entries).
- Run bot as a separate background worker.
- Separate web (Django) and bot (worker) processes.
flowchart LR
User[Telegram User] -->|uses| Bot(bot.py - Async)
Bot -->|reads/writes| DjangoORM[Django ORM]
DjangoORM -->|admin UI| DjangoAdmin[Admin Panel]
Bot -->|polls transactions| TONAPI[TON API v3]
TONAPI --> Bot
DjangoORM --> Database[(PostgreSQL / SQLite)]
DjangoORM -->|Redis queue| Redis[(Redis)]
Django -->|push updates| Redis
Bot -->|consume updates| Redis
- Keep
SECRET_KEYand API keys out of source control - Use HTTPS for webhooks
- Validate and sanitize user input
- Limit access to Redis for internal services only
- Manual testing for payments recommended
- Unit tests suggested for:
apply_transaction()atomic behaviorTonCursorupdates- Polling & webhook edge cases
GPL-3.0 β see LICENSE file.
Parts of this README were assisted by AI. All final code and implementation decisions were made manually by the author.