Skip to content

interlumpen/Telegram-shop-Physical

Repository files navigation

πŸ›’ Telegram Physical Goods Shop Bot

A production-ready Telegram bot for selling physical goods with comprehensive inventory management, Bitcoin/cash payments, referral system, and advanced order tracking capabilities.

Python Aiogram PostgreSQL Docker License


πŸ”€ Looking for Digital Goods Shop?

πŸ“¦ This version is for PHYSICAL GOODS (inventory, shipping, delivery addresses, etc.)

πŸ’Ύ Need to sell DIGITAL GOODS instead? (accounts, keys, licenses, etc.) πŸ‘‰ Use this version: Telegram Digital Goods Shop

The digital goods version features instant delivery, ItemValues storage, and automatic content distribution without inventory management.


πŸ“‹ Table of Contents

🎯 Overview

This bot is specifically designed for physical goods (not digital products) with:

  • Inventory management with stock tracking and reservation system
  • Dual payment methods: Bitcoin (address pool) and Cash on Delivery
  • Shopping cart with checkout flow
  • Reference codes for controlled user registration
  • Referral bonuses for customer acquisition
  • Order tracking with delivery time management
  • CLI tool for comprehensive shop administration

What Makes This Different

This is NOT a typical digital goods Telegram shop. Key differences:

  • βœ… Physical inventory with stock levels
  • βœ… Reservation system with timeouts
  • βœ… Delivery address & phone collection
  • βœ… Dual payment methods (Bitcoin + Cash on Delivery)
  • βœ… Reference code requirement for registration
  • βœ… Multi-stage order lifecycle (pending β†’ reserved β†’ confirmed β†’ delivered)
  • βœ… Admin CLI for order & inventory management

✨ Key Features

πŸͺ Shop Management

  • Categories & Products: Organize items by categories
  • Stock Tracking: Real-time inventory with stock_quantity and reserved_quantity
  • Reservation System: Items reserved for 24 hours (configurable) during checkout
  • Shopping Cart: Add multiple items before checkout
  • Lazy Loading: Efficient pagination for large catalogs

πŸ’° Payment System

Two Payment Methods:

1. Bitcoin Payments

  • Address Pool: Load Bitcoin addresses from btc_addresses.txt
  • One-Time Use: Each address used only once per order
  • Auto-Reload: File watcher automatically loads new addresses when file changes
  • Usage Tracking: Complete address usage audit trail in database
  • Critical: Must add addresses to btc_addresses.txt before accepting Bitcoin orders

2. Cash on Delivery (COD)

  • Manual Confirmation: Admin confirms cash receipt via CLI
  • No Prepayment: Customer pays upon delivery
  • Flexible: No cryptocurrency wallet required

πŸ‘₯ User Management

  • Reference Code Required: Users must enter valid code on first /start
  • User Types: Regular users and admins (with different code creation privileges)
  • User Banning: Ban/unban users via admin panel or CLI with optional reason tracking
  • Referral System: Track who referred whom with configurable bonus percentage
  • Bonus Balance: Accumulated referral bonuses can be applied to orders
  • Customer Profiles: Saved delivery address, phone, order history

πŸ“¦ Order Management

  • Order Codes: 6-character unique codes (e.g., ECBDJI) for easy reference
  • Order Status: pending β†’ reserved β†’ confirmed β†’ delivered β†’ cancelled/expired
  • Delivery Information: Address, phone number, optional delivery note
  • Delivery Time: Admin-set planned delivery time
  • Reservation Timeout: Configurable timeout (default 24h) with automatic cleanup
  • Order Modifications: Add/remove items, update delivery time via CLI

πŸ”§ Administration

  • Role-Based Access: USER, ADMIN, OWNER roles with granular permissions
  • CLI Tool (bot_cli.py): Comprehensive command-line interface for shop management
  • Statistics: Real-time shop statistics and analytics
  • Broadcast: Send messages to all users or specific groups
  • Export: CSV export for customers, orders, reference codes

πŸ“Š Monitoring & Logging

  • Web Dashboard: Real-time metrics at http://localhost:9090/dashboard
  • Health Checks: System status monitoring
  • Structured Logging: Separate logs for orders, reference codes, customer changes
  • Timezone Support: Configurable timezone for all logs
  • Inventory Audit: Complete audit trail of all inventory changes

πŸ”’ Security

  • Rate Limiting: Configurable limits per action
  • Security Middleware: SQL injection, XSS, CSRF protection
  • Cryptographic Codes: Secure reference code generation
  • Bot Detection: Automatic blocking of bot accounts
  • Transaction Safety: Row-level locking prevents overselling

πŸ—οΈ Architecture

πŸ“ Project Structure

Project Structure Schema (click to expand)
telegram_shop/
β”œβ”€β”€ run.py                          # Entry point
β”œβ”€β”€ bot_cli.py                      # CLI admin tool
β”œβ”€β”€ btc_addresses.txt               # Bitcoin address pool
β”œβ”€β”€ requirements.txt                # Python dependencies
β”œβ”€β”€ Dockerfile                      # Docker image definition
β”œβ”€β”€ docker-compose.yml              # Multi-container setup
β”œβ”€β”€ .env.example                    # Environment template
β”‚
β”œβ”€β”€ bot/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ main.py                     # Bot initialization & startup
β”‚   β”œβ”€β”€ logger_mesh.py              # Logging configuration
β”‚   β”‚
β”‚   β”œβ”€β”€ config/                     # Configuration management
β”‚   β”‚   β”œβ”€β”€ env.py                  # Environment variables
β”‚   β”‚   β”œβ”€β”€ storage.py              # Redis/Memory storage
β”‚   β”‚   └── timezone.py             # Timezone handling
β”‚   β”‚
β”‚   β”œβ”€β”€ database/                   # Database layer
β”‚   β”‚   β”œβ”€β”€ main.py                 # Database engine & session
β”‚   β”‚   β”œβ”€β”€ dsn.py                  # Connection string builder
β”‚   β”‚   β”œβ”€β”€ models/                 # SQLAlchemy models
β”‚   β”‚   β”‚   └── main.py             # All model definitions
β”‚   β”‚   └── methods/                # Database operations
β”‚   β”‚       β”œβ”€β”€ create.py           # INSERT operations
β”‚   β”‚       β”œβ”€β”€ read.py             # SELECT operations
β”‚   β”‚       β”œβ”€β”€ update.py           # UPDATE operations
β”‚   β”‚       β”œβ”€β”€ delete.py           # DELETE operations
β”‚   β”‚       β”œβ”€β”€ inventory.py        # Inventory management
β”‚   β”‚       β”œβ”€β”€ cache_utils.py      # Cache invalidation
β”‚   β”‚       └── lazy_queries.py     # Pagination queries
β”‚   β”‚
β”‚   β”œβ”€β”€ handlers/                   # Request handlers
β”‚   β”‚   β”œβ”€β”€ main.py                 # Handler registration
β”‚   β”‚   β”œβ”€β”€ other.py                # Misc handlers
β”‚   β”‚   β”œβ”€β”€ user/                   # User-facing handlers
β”‚   β”‚   β”‚   β”œβ”€β”€ main.py             # /start, /help
β”‚   β”‚   β”‚   β”œβ”€β”€ shop_and_goods.py   # Browse catalog
β”‚   β”‚   β”‚   β”œβ”€β”€ cart_handler.py     # Shopping cart
β”‚   β”‚   β”‚   β”œβ”€β”€ order_handler.py    # Checkout & orders
β”‚   β”‚   β”‚   β”œβ”€β”€ orders_view_handler.py  # Order history
β”‚   β”‚   β”‚   β”œβ”€β”€ reference_code_handler.py  # Code entry
β”‚   β”‚   β”‚   └── referral_system.py  # Referral bonuses
β”‚   β”‚   └── admin/                  # Admin-only handlers
β”‚   β”‚       β”œβ”€β”€ main.py             # Admin menu
β”‚   β”‚       β”œβ”€β”€ broadcast.py        # Mass messaging
β”‚   β”‚       β”œβ”€β”€ shop_management_states.py      # Shop stats
β”‚   β”‚       β”œβ”€β”€ goods_management_states.py     # Product CRUD
β”‚   β”‚       β”œβ”€β”€ categories_management_states.py # Category CRUD
β”‚   β”‚       β”œβ”€β”€ adding_position_states.py      # Add products
β”‚   β”‚       β”œβ”€β”€ update_position_states.py      # Edit products
β”‚   β”‚       β”œβ”€β”€ user_management_states.py      # User admin
β”‚   β”‚       β”œβ”€β”€ reference_code_management.py   # Code admin
β”‚   β”‚       └── settings_management.py         # Bot settings
β”‚   β”‚
β”‚   β”œβ”€β”€ states/                     # FSM states
β”‚   β”‚   β”œβ”€β”€ user_state.py           # User flow states
β”‚   β”‚   β”œβ”€β”€ shop_state.py           # Shopping states
β”‚   β”‚   β”œβ”€β”€ payment_state.py        # Payment flow
β”‚   β”‚   β”œβ”€β”€ goods_state.py          # Product management
β”‚   β”‚   β”œβ”€β”€ category_state.py       # Category management
β”‚   β”‚   └── broadcast_state.py      # Broadcast states
β”‚   β”‚
β”‚   β”œβ”€β”€ keyboards/                  # Inline keyboards
β”‚   β”‚   └── inline.py               # Keyboard builders
β”‚   β”‚
β”‚   β”œβ”€β”€ middleware/                 # Request middleware
β”‚   β”‚   β”œβ”€β”€ security.py             # CSRF, injection detection
β”‚   β”‚   └── rate_limit.py           # Rate limiting
β”‚   β”‚
β”‚   β”œβ”€β”€ filters/                    # Custom filters
β”‚   β”‚   └── main.py                 # Role filters, etc.
β”‚   β”‚
β”‚   β”œβ”€β”€ i18n/                       # Internationalization
β”‚   β”‚   β”œβ”€β”€ main.py                 # Locale manager
β”‚   β”‚   └── strings.py              # Translations
β”‚   β”‚
β”‚   β”œβ”€β”€ payments/                   # Payment processing
β”‚   β”‚   β”œβ”€β”€ bitcoin.py              # BTC address management
β”‚   β”‚   └── notifications.py        # Payment notifications
β”‚   β”‚
β”‚   β”œβ”€β”€ referrals/                  # Referral system
β”‚   β”‚   └── codes.py                # Code generation & validation
β”‚   β”‚
β”‚   β”œβ”€β”€ tasks/                      # Background tasks
β”‚   β”‚   β”œβ”€β”€ reservation_cleaner.py  # Expire old reservations
β”‚   β”‚   └── file_watcher.py         # Watch btc_addresses.txt
β”‚   β”‚
β”‚   β”œβ”€β”€ caching/                    # Caching layer
β”‚   β”‚   β”œβ”€β”€ cache.py                # CacheManager & decorators
β”‚   β”‚   β”œβ”€β”€ scheduler.py            # Cache maintenance scheduler
β”‚   β”‚   └── stats_cache.py          # Statistics caching
β”‚   β”‚
β”‚   β”œβ”€β”€ monitoring/                 # Observability
β”‚   β”‚   β”œβ”€β”€ metrics.py              # MetricsCollector
β”‚   β”‚   β”œβ”€β”€ dashboard.py            # Web dashboard
β”‚   β”‚   └── recovery.py             # Error recovery
β”‚   β”‚
β”‚   β”œβ”€β”€ communication/              # User communication
β”‚   β”‚   └── broadcast_system.py     # Mass messaging
β”‚   β”‚
β”‚   └── export/                     # Data export
β”‚       β”œβ”€β”€ customer_csv.py         # Customer data export
β”‚       └── custom_logging.py       # Structured logging
β”‚
β”œβ”€β”€ logs/                           # Log files
β”‚   β”œβ”€β”€ bot.log                     # Main log
β”‚   β”œβ”€β”€ audit.log                   # Security events
β”‚   β”œβ”€β”€ orders.log                  # Order lifecycle
β”‚   β”œβ”€β”€ reference_code.log          # Code operations
β”‚   └── changes.log                 # Customer changes
β”‚
β”œβ”€β”€ data/                           # Runtime data
    └── final_metrics.json          # Shutdown metrics

System Components

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     Telegram Bot API                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚
                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   Aiogram Bot (main.py)                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚   Handlers     β”‚  Middleware  β”‚   Background Tasks     β”‚ β”‚
β”‚  β”‚  (user/admin)  β”‚ (security/   β”‚  (reservation cleanup, β”‚ β”‚
β”‚  β”‚                β”‚  rate limit) β”‚   file watcher)        β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β–Ό              β–Ό              β–Ό              β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ PostgreSQL   β”‚ β”‚  Redis   β”‚ β”‚ Bot CLI   β”‚ β”‚  Monitoring  β”‚
β”‚  Database    β”‚ β”‚  Cache   β”‚ β”‚ (bot_cli. β”‚ β”‚   Server     β”‚
β”‚ (inventory,  β”‚ β”‚  & FSM   β”‚ β”‚  py)      β”‚ β”‚  (port 9090) β”‚
β”‚  orders,     β”‚ β”‚ Storage  β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚  users, etc.)β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Database Models

Core Models:

  • User: Telegram users with role and referral tracking
  • Role: Permission-based access control (USER/ADMIN/OWNER)
  • Goods: Products with stock_quantity, reserved_quantity, price
  • Categories: Product categories
  • ShoppingCart: User cart items

Order System:

  • Order: Orders with status, delivery info, payment method, reservation timeout
  • OrderItem: Individual items in orders with quantity
  • CustomerInfo: Customer delivery preferences, spending history, bonus balance

Inventory System:

  • InventoryLog: Complete audit trail of all inventory changes

Reference Code System:

  • ReferenceCode: Reference codes with expiry, usage limits, notes
  • ReferenceCodeUsage: Tracking who used which code

Payment System:

  • BitcoinAddress: Pool of Bitcoin addresses with usage tracking

Referral System:

  • ReferralEarnings: Referral bonus transactions

Configuration:

  • BotSettings: Dynamic bot settings (timezone, bonus percentage, etc.)

πŸ“‹ Requirements

  • Python 3.11+
  • PostgreSQL 16+
  • Redis 7+
  • Docker & Docker Compose (recommended)

βš™οΈ Environment Variables

The application requires the following environment variables:

πŸ€– Telegram
Variable Description Required
TOKEN Bot Token from @BotFather βœ…
OWNER_ID Your Telegram ID βœ…
πŸ’³ Payments
Variable Description Default
PAY_CURRENCY Display currency (RUB, USD, EUR, etc.) RUB
MIN_AMOUNT Minimum payment amount 20
MAX_AMOUNT Maximum payment amount 10000
πŸ”— Links / UI
Variable Description Default
CHANNEL_URL News channel link (public channels only) -
HELPER_ID Support user Telegram ID -
RULES Bot usage rules text -
🌐 Locale & Logs
Variable Description Default
BOT_LOCALE Localization language (ru/en) ru
LOG_TO_STDOUT Console logging (1/0) 1
LOG_TO_FILE File logging (1/0) 1
DEBUG Debug mode (1/0) 0
πŸ“Š Monitoring
Variable Description Default
MONITORING_HOST Monitoring server bind address localhost
MONITORING_PORT Monitoring server port 9090

Note: When running in Docker, set MONITORING_HOST=0.0.0.0 to allow external access.

πŸ“¦ Redis Storage
Variable Description Default
REDIS_HOST Redis server address redis
REDIS_PORT Redis server port 6379
REDIS_DB Redis database number 0
REDIS_PASSWORD Redis password (if enabled) -
πŸ—„οΈ Database (Docker)
Variable Description Default
POSTGRES_DB PostgreSQL database name Required
POSTGRES_USER PostgreSQL username postgres
POSTGRES_PASSWORD PostgreSQL password Required
DB_PORT PostgreSQL port 5432
DB_DRIVER Database driver postgresql+psycopg2
πŸ—„οΈ Database (Manual Deploy)

For manual deployment, configure DATABASE_URL in bot/config/env.py:

DATABASE_URL = "postgresql+psycopg2://user:password@localhost:5432/db_name"

SQLAlchemy Documentation

πŸš€ Installation

Option 1: Docker (Recommended)

  1. Clone the repository

    git clone https://github.com/yourusername/telegram_shop.git
    cd telegram_shop
  2. Configure environment

    cp .env.example .env
    nano .env  # Edit with your values
  3. Add Bitcoin addresses (Required ONLY if accepting Bitcoin payments)

    nano btc_addresses.txt
    # Add your Bitcoin addresses, one per line:
    # bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
    # bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4
    # Note: Skip this step if using cash on delivery only
  4. Start services

    docker compose up -d --build bot
  5. View logs

    docker compose logs -f bot

Option 2: Manual Installation

  1. Clone repository

    git clone https://github.com/yourusername/telegram_shop.git
    cd telegram_shop
  2. Create virtual environment

    python3.11 -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies

    pip install --upgrade pip
    pip install -r requirements.txt
  4. Set up PostgreSQL

    createdb telegram_shop
    createuser shop_user -P
  5. Configure environment

    export TOKEN="your_bot_token"
    export OWNER_ID="your_telegram_id"
    # Set other required variables from .env.example
  6. Add Bitcoin addresses (optional - only if accepting Bitcoin)

    nano btc_addresses.txt
    # Add addresses as shown above
    # Skip if using cash on delivery only
  7. Run the bot

    python run.py

Bot Settings (Dynamic)

These can be changed at runtime via CLI:

# Enable/disable reference codes
python bot_cli.py settings set reference_codes_enabled true

# Set referral bonus percentage (0-100)
python bot_cli.py settings set reference_bonus_percent 5

# Set timezone for logs
python bot_cli.py settings set timezone "America/New_York"

# Set order timeout (hours)
python bot_cli.py settings set cash_order_timeout_hours 24

# Set help auto-response
python bot_cli.py settings set help_auto_message "We'll respond within 24 hours"

πŸ”§ Bot CLI Commands

The bot_cli.py script provides comprehensive shop management while the bot is running.

Order Management

Complete Order Flow (Recommended)

# 1. User places order β†’ order is 'pending', inventory reserved
# 2. Confirm order with delivery time
python bot_cli.py order --order-code ABCDEF --status-confirmed --delivery-time "2025-11-20 14:30"

# 3. Mark as delivered (deducts inventory from stock)
python bot_cli.py order --order-code ABCDEF --status-delivered

Cancel Order

# Cancel order (releases reserved inventory, refunds bonus if applied)
python bot_cli.py order --order-code ABCDEF --cancel

Modify Order

# Add item to order
python bot_cli.py order --order-code ABCDEF --add-item "Product Name" --quantity 2 --notify

# Remove item from order
python bot_cli.py order --order-code ABCDEF --remove-item "Product Name" --quantity 1 --notify

# Update delivery time
python bot_cli.py order --order-code ABCDEF --update-delivery-time --delivery-time "2025-11-21 16:00" --notify

Inventory Management

# Set inventory to specific value
python bot_cli.py inventory "Product Name" --set 100

# Add to current inventory
python bot_cli.py inventory "Product Name" --add 50

# Remove from inventory
python bot_cli.py inventory "Product Name" --remove 25

Reference Code Management

# Create admin reference code
python bot_cli.py refcode create --expires-hours 48 --max-uses 10 --note "VIP customers"

# Create unlimited code (no expiry, unlimited uses)
python bot_cli.py refcode create --expires-hours 0 --max-uses 0 --note "Permanent invite"

# Disable code
python bot_cli.py refcode disable CODE123 --reason "No longer valid"

# List all codes
python bot_cli.py refcode list

# List only active codes
python bot_cli.py refcode list --active-only

Bitcoin Address Management

# Add single address
python bot_cli.py btc add --address bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh

# Add addresses from file
python bot_cli.py btc add --file new_addresses.txt

# Check address pool status
python bot_cli.py btc list

# Show all addresses with details
python bot_cli.py btc list --show-all

# Sync addresses (cleanup)
python bot_cli.py btc sync

Data Export

# Export all data
python bot_cli.py export --all --output-dir backups/

# Export only customers
python bot_cli.py export --customers --output-dir backups/

# Export only reference codes
python bot_cli.py export --refcodes --output-dir backups/

# Export only orders
python bot_cli.py export --orders --output-dir backups/

Settings Management

# Set a setting
python bot_cli.py settings set reference_codes_enabled true
python bot_cli.py settings set reference_bonus_percent 5
python bot_cli.py settings set timezone "UTC"

# Get a setting value
python bot_cli.py settings get reference_codes_enabled

# List all settings
python bot_cli.py settings list

User Ban Management

# Ban a user
python bot_cli.py ban 123456789 --reason "Violating terms of service" --notify

# Ban a user without notification
python bot_cli.py ban 123456789 --reason "Spam"

# Unban a user
python bot_cli.py unban 123456789 --notify

# Unban a user without notification
python bot_cli.py unban 123456789

πŸ“¦ Order Lifecycle

Complete Order Flow

1. User browses shop
   ↓
2. User adds items to cart
   ↓
3. User clicks "Proceed to Checkout"
   ↓
4. System asks for delivery info:
   - Delivery address
   - Phone number
   - Delivery note (optional)
   ↓
5. System asks about applying referral bonus (if available)
   ↓
6. User selects payment method:
   - Bitcoin: System assigns address from pool, user receives payment instructions
   - Cash on Delivery: Order proceeds directly to confirmation
   ↓
7. Order created with status: pending β†’ reserved
   - Inventory RESERVED for 24 hours (configurable)
   - reserved_until timestamp set
   ↓
8. Admin receives order notification
   ↓
9. Customer pays (Bitcoin) or prepares cash (COD)
   ↓
10. Admin confirms order via CLI:
    python bot_cli.py order --order-code XXXXX --status-confirmed --delivery-time "YYYY-MM-DD HH:MM"
    - Order status: reserved β†’ confirmed
    - Delivery time set
    - Customer notified
    - For Bitcoin: After payment is verified
    - For COD: After reviewing order details
    ↓
11. Admin delivers order and marks as delivered via CLI:
    python bot_cli.py order --order-code XXXXX --status-delivered
    - Order status: confirmed β†’ delivered
    - Inventory DEDUCTED from stock (actual reduction)
    - reserved_quantity reduced
    - stock_quantity reduced
    - Customer spending updated
    - Referral bonus credited (if applicable)
    - Customer notified
    - For COD: Cash collected at this point

Order Status States

  • pending: Order just created, waiting for reservation
  • reserved: Inventory reserved, waiting for payment/confirmation
  • confirmed: Payment confirmed, delivery time set, awaiting delivery
  • delivered: Order completed, inventory deducted, customer updated
  • cancelled: Manually cancelled by admin, inventory released
  • expired: Reservation timeout exceeded, inventory automatically released

Inventory Flow

Reserve (on order creation)

stock_quantity: 100
reserved_quantity: 0 β†’ 5
available_quantity: 100 β†’ 95

Deduct (on order delivery)

stock_quantity: 100 β†’ 95
reserved_quantity: 5 β†’ 0
available_quantity: 95 (unchanged)

Release (on cancel/expire)

stock_quantity: 100 (unchanged)
reserved_quantity: 5 β†’ 0
available_quantity: 95 β†’ 100

πŸ”„ Background Tasks

1. Reservation Cleaner

File: bot/tasks/reservation_cleaner.py

Runs every 60 seconds to:

  • Find orders with order_status='reserved' and reserved_until < now()
  • Release reserved inventory back to available stock
  • Mark orders as expired
  • Refund referral bonus if applied
  • Notify customers about expired orders
  • Log all actions to inventory_log

2. Bitcoin Address File Watcher

File: bot/tasks/file_watcher.py

Monitors btc_addresses.txt for changes:

  • Watches file for modifications
  • Debounces rapid changes (2-second default)
  • Automatically loads new addresses into database
  • Logs all operations
  • Thread-safe with locking

πŸ”’ Security Features

Middleware Chain

The bot implements a layered middleware architecture for security, performance, and observability:

Request Flow:
User β†’ Telegram API β†’ aiogram Dispatcher
         ↓
    AnalyticsMiddleware (tracks all events)
         ↓
    AuthenticationMiddleware (verifies user identity, caches roles)
         ↓
    SecurityMiddleware (CSRF protection, suspicious pattern detection)
         ↓
    RateLimitMiddleware (prevents spam, configurable limits)
         ↓
    Handler (business logic)

Middleware Details:

  1. AnalyticsMiddleware (bot/monitoring/metrics.py)

    • Tracks every event (messages, callbacks)
    • Measures handler execution time
    • Records errors and conversion funnels
    • Sends metrics to Prometheus
  2. AuthenticationMiddleware (bot/middleware/security.py)

    • Verifies user identity
    • Caches user roles (5-minute TTL)
    • Blocks bot accounts automatically
    • Prevents unauthorized admin access
  3. SecurityMiddleware (bot/middleware/security.py)

    • Generates CSRF tokens for critical actions
    • Detects SQL injection, XSS, command injection patterns
    • Validates callback data age (1-hour max)
    • Logs all security events to audit log
  4. RateLimitMiddleware (bot/middleware/rate_limit.py)

    • Global limit: 30 requests/60 seconds (configurable)
    • Action-specific limits:
      • Broadcast: 1/hour
      • Shop views: 60/minute
      • Purchases: 5/minute
    • Temporary bans: 5 minutes after limit exceeded
    • Admin bypass support

πŸ“Š Monitoring & Logging

Web Dashboard

Access at http://localhost:9090/dashboard (or your configured host/port):

  • Real-time metrics
  • Event tracking
  • Performance analysis
  • Error tracking
  • System health

MetricsCollector (bot/monitoring/metrics.py) tracks:

1. Events:

  • Order lifecycle: created, reserved, confirmed, delivered, cancelled, expired
  • Cart operations: add, remove, view, clear, checkout
  • Payment events: initiated, bonus applied, completed
  • Referral actions: code created/used, bonus paid
  • Inventory changes: reserved, released, deducted
  • Security alerts: suspicious patterns, rate limits, unauthorized access

2. Timings:

  • Handler execution duration
  • Database query latency
  • Cache operation speed
  • External API calls

3. Errors:

  • Error type categorization
  • Error frequency tracking
  • Stack trace logging

4. Conversions:

# Customer journey funnel
shop β†’ category β†’ item β†’ cart β†’ checkout β†’ payment β†’ order

# Referral funnel
code_created β†’ code_used β†’ bonus_paid

Log Files

Log Levels:

  • DEBUG: Development debugging (disabled in production)
  • INFO: Normal operations, startup/shutdown
  • WARNING: Recoverable issues, rate limits
  • ERROR: Errors that need attention
  • CRITICAL: System failures

Specialized Logs:

  1. bot.log - Main application log

    • Bot startup/shutdown
    • Handler execution
    • Database operations
    • Background tasks
  2. audit.log - Security events

    • Critical action attempts
    • Failed authorization
    • Suspicious patterns
    • Rate limit violations
  3. orders.log - Order operations

    • Order creation
    • Status changes
    • Delivery updates
    • Completions/cancellations
  4. reference_code.log - Code lifecycle

    • Code generation
    • Code usage
    • Code deactivation
  5. changes.log - Customer data modifications

    • Profile updates
    • Spending changes
    • Bonus adjustments

Log Format:

[2025-11-19 14:30:45] [INFO] [bot.main:239] Starting bot: @shopbot (ID: 123456789)
[2025-11-19 14:30:46] [INFO] [bot.tasks.reservation_cleaner:14] Reservation cleaner started

CSV Exports

Automatic CSV generation in logs/:

  • customer_list.csv: Customer database with all details
  • Updated in real-time as customer data changes

Prometheus Metrics

Metrics available at http://localhost:9090/metrics/prometheus for Grafana integration.

Health Check

System health at http://localhost:9090/health for uptime monitoring.

Test Suite Documentation

Comprehensive test suite for the Telegram Physical Goods Shop Bot.

Overview

This test suite provides comprehensive coverage for all major components of the bot:

  • Database models and relationships
  • CRUD operations
  • Inventory management system
  • Order lifecycle
  • Shopping cart
  • Referral system
  • Reference code system
  • Bitcoin payment system
  • Validators and utilities

Test Structure

tests/
β”œβ”€β”€ conftest.py              # Shared fixtures and pytest configuration
β”œβ”€β”€ unit/                    # Unit tests
β”‚   β”œβ”€β”€ database/           # Database-related tests
β”‚   β”‚   β”œβ”€β”€ test_models.py       # Model tests
β”‚   β”‚   β”œβ”€β”€ test_crud.py         # CRUD operation tests
β”‚   β”‚   β”œβ”€β”€ test_inventory.py   # Inventory management tests
β”‚   β”‚   └── test_cart.py         # Shopping cart tests
β”‚   β”œβ”€β”€ utils/              # Utility tests
β”‚   β”‚   β”œβ”€β”€ test_validators.py  # Validator tests
β”‚   β”‚   └── test_order_codes.py # Order code generation tests
β”‚   β”œβ”€β”€ payments/           # Payment system tests
β”‚   β”‚   └── test_bitcoin.py     # Bitcoin address tests
β”‚   └── referrals/          # Referral system tests
β”‚       └── test_reference_codes.py  # Reference code tests
└── integration/            # Integration tests
    └── test_order_lifecycle.py  # Complete order flow tests

πŸ§ͺ Testing

Run All Tests

pytest

Run with Coverage Report

pytest --cov=bot --cov-report=html --cov-report=term-missing

Coverage report will be generated in htmlcov/ directory.

Run Specific Test Categories

Run only unit tests:

pytest -m unit

Run only integration tests:

pytest -m integration

Run only database tests:

pytest -m database

Run only model tests:

pytest -m models

Run Specific Test Files

# Run model tests
pytest tests/unit/database/test_models.py

# Run CRUD tests
pytest tests/unit/database/test_crud.py

# Run inventory tests
pytest tests/unit/database/test_inventory.py

# Run order lifecycle tests
pytest tests/integration/test_order_lifecycle.py

Run Specific Test Classes or Functions

# Run specific test class
pytest tests/unit/database/test_models.py::TestRoleModel

# Run specific test function
pytest tests/unit/database/test_models.py::TestRoleModel::test_create_role

Verbose Output

pytest -v

Show Print Statements

pytest -s

Stop on First Failure

pytest -x

Run Failed Tests Only

pytest --lf

Test Markers

Tests are organized with markers for easy filtering:

  • unit - Unit tests
  • integration - Integration tests
  • database - Tests requiring database
  • slow - Slow running tests
  • models - Database model tests
  • crud - CRUD operation tests
  • inventory - Inventory management tests
  • orders - Order management tests
  • cart - Shopping cart tests
  • referrals - Referral system tests
  • bitcoin - Bitcoin payment tests
  • validators - Validator tests

Fixtures

Database Fixtures

  • db_engine - Test database engine (in-memory SQLite)
  • db_session - Test database session
  • db_with_roles - Database session with roles initialized

Model Fixtures

  • test_user - Sample user
  • test_admin - Sample admin user
  • test_category - Sample category
  • test_goods - Sample goods with stock
  • test_goods_low_stock - Sample goods with low stock
  • test_order - Sample order with items
  • test_customer_info - Sample customer information
  • test_bitcoin_address - Sample Bitcoin address
  • test_reference_code - Sample reference code
  • test_shopping_cart - Sample cart item
  • test_bot_settings - Sample bot settings

Complex Fixtures

  • populated_database - Database with all test data
  • multiple_products - List of multiple products
  • multiple_categories - List of multiple categories

Test Coverage

Current Coverage Areas

  1. Database Models (100%)

    • All model creation and validation
    • Relationships between models
    • Property calculations (e.g., available_quantity)
    • Permission system
  2. CRUD Operations (95%)

    • Create operations for all models
    • Read operations with caching
    • Update operations with validation
    • Proper error handling
  3. Inventory Management (100%)

    • Reservation system
    • Release mechanism
    • Deduction on order completion
    • Stock tracking and logging
    • Concurrent access handling
  4. Order System (100%)

    • Order creation
    • Status transitions
    • Order cancellation
    • Multi-item orders
    • Order code generation
  5. Shopping Cart (100%)

    • Adding items
    • Quantity updates
    • Stock validation
    • Total calculation
  6. Referral System (100%)

    • Reference code generation
    • Code validation
    • Usage tracking
    • Expiration handling
    • Usage limits
  7. Bitcoin System (95%)

    • Address loading
    • Address assignment
    • Usage tracking
    • File synchronization
  8. Validators (100%)

    • Input validation
    • Data sanitization
    • Error handling

πŸ“„ License

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

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ™ Acknowledgments

πŸ“ž Support

  • Issues: Report bugs via GitHub Issues
  • Logs: Check logs/ directory for detailed error information

πŸ“š Additional Documentation

  • .env.example - Environment variable reference
  • bot_cli.py --help - CLI usage help

About

This telegram bot is a template for a shop πŸͺ where users can purchase goods and have them delivered.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages