A fast, reliable Telegram store bot that allows users to browse products, top up balances using TON cryptocurrency, and purchase items — all from Telegram.
Django is used only for the admin panel and ORM models; the bot runs as a standalone async application (bot.py).
- Features ✨
- Highlights 🚀
- Setup & Installation 🛠️
- Bot Commands 📋
- TON Polling Overview 🧭
- Database Notes ⚙️
- Best Practices ✅
- Architecture Diagram 🧩
- Security & Privacy 🔐
- Testing & Development 🧪
- License 📜
- Disclaimer 🤖
- Tutorials
- Product browsing by categories 🏷️
- Purchase products using TON cryptocurrency 💰
- Generate TON payment links 🔗
- Track user transactions and purchase history 📝
- Background tasks: TON price updater, transaction processor ⏱️
- Multi-language support 🌐
- Timezone handling ⏰
- TON Center API v3 integration with pagination — ensures no on-chain transactions are missed.
- Thread-safe async usage of Django ORM (
sync_to_async(thread_sensitive=True)). - Atomic, idempotent transaction processing — prevents double-crediting.
- Purchases lock only one
ProductDetailrow at a time. - LRUCache for recent TX deduplication; TTL caches for settings and price.
- Clean separation: Django for admin & ORM; bot runs independently.
- Clone repository:
git clone --branch TON-payment https://github.com/RezaTaheri01/telegram-store-bot.git
cd telegram-store-bot/telegram_store- Install dependencies (use virtualenv recommended):
pip install --upgrade pip
pip install -r req.txt- Collect static files:
python manage.py collectstatic --noinput- Create a
.envfile:
# Bot Token(@BotFather)
TOKEN=your-telegram-api-token
BOT_LINK=https://t.me/giftShop2025Bot
# Command to clear BotSetting cache via bot(Change it on deployment and keep it private)
UPDATE_SETTING_COMMAND=update
# Django secret key
SECRET_KEY=CHANGE_ME_IN_PRODUCTION
# Set to False when deploying!
DEBUG=True
# No slash at the end
ALLOWED_HOSTS=localhost,127.0.0.1,your-domain.com,www.your-domain.com
ADMIN_URL=adminadmin
# No slash at the end
# Local Storage Image Domain(Site Domain)
# SITE_DOMAIN=https://your-domain.com
# Database
#DB_ENGINE=postgresql
#DB_NAME=mydb
#DB_USER=postgres
#DB_PASS=secret123
#DB_HOST=localhost
#DB_PORT=5432- Run migrations & create superuser:
python manage.py makemigrations users payment products
python manage.py migrate
python manage.py createsuperuser- Start Django backend:
python manage.py runserverProduction: use Gunicorn or Uvicorn:
gunicorn telegram_store.asgi:application -k uvicorn.workers.UvicornWorker -w 1 -b 0.0.0.0:8000- Configure Bot Settings in Django Admin:
- Wallet Currency: 3-letter code (USD)
- TON Price Delay: 120s
- TON Fetch Limit: 250
- TON Network Delay: 10s
- Optional: Disable Product Images for faster UI
- Start the bot:
python bot.pyProduction: run as a background service, via nohup, systemd, or Docker, so it stays alive and automatically restarts if it crashes.
/start– Start the bot and show main menu/menu– Show main menu/balance– Check balance/pay– Generate TON payment link/set_timezone– Set timezone based on locationUpdate Settings– Refresh bot settings
Note: For
/set_timezoneto work, uncomment the relevant command handlers inbot.py.
-
Read
TonCursor(last_lt,last_hash) from DB. -
Request transactions via TON v3 API.
-
Process results oldest → newest for idempotency.
-
Each transaction:
- Normalize
hash(lowercase) - Skip if already in cache/DB
- Ensure user exists
- Update balance inside
transaction.atomic()withselect_for_update() - Record transaction
- Add hash to cache after successful processing
- Normalize
-
Update
TonCursoronly after processing completes.
This ensures no transactions are skipped and no double-processing occurs.
TonCursor→last_lt(BigInteger) &last_hash(char 128)Transaction.tx_idshould be uniqueProductDetail→ inventory rows; lock one row per purchase withselect_for_update(skip_locked=True)
- Use PostgreSQL in production (SQLite is fragile for locking).
- Keep
TON Fetch Limitmoderate (100–500) based on load. - Monitor LRU cache size (default: 10,000 entries).
- Run
bot.pyas a background worker/service. - Separate web (Django) and bot (worker) processes.
- Ensure PostgreSQL is properly monitored and backed up.
- Set DEBUG=False and configure ALLOWED_HOSTS properly.
- Secure sensitive environment variables (SECRET_KEY, TOKEN, REDIS_URL).
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)]
- Keep
SECRET_KEYand API keys out of source control. - Use HTTPS for webhooks (if switching to webhook mode).
- Validate and sanitize user input.
-
Manual testing for payment flows recommended.
-
Unit tests suggested for:
apply_transaction()atomic behaviorTonCursorupdates- Polling 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.