Skip to content

NadiiaBCN/ops-chatbot

Repository files navigation

Operations ChatBot

Real-time transaction processing bot with Google Cloud Vision OCR

A professional Telegram bot for handling deposit and withdrawal transactions with automatic receipt recognition using Google Cloud Vision API. Designed for operations teams requiring real-time notifications and transaction management.


Features

Core Features

  • Telegram Bot Interface - Client and admin interaction via python-telegram-bot
  • Receipt OCR - Automatic data extraction using Google Cloud Vision
  • Transaction Management - Deposit and withdrawal processing
  • Role-based Access - Separate interfaces for clients and administrators
  • Status Tracking - Real-time transaction status updates
  • Async Processing - Background tasks with Celery

OCR Capabilities

  • Extract receipt number, amount, date, payment method
  • Automatic image preprocessing for better recognition
  • Confidence scoring and validation
  • Manual review fallback for failed extractions

Admin Features

  • Transaction approval/rejection buttons
  • Real-time statistics dashboard
  • Transaction history and details
  • Bulk operations support

Architecture

ops-chatbot/
├── main.py                      # FastAPI REST API
├── telegram_bot.py              # Telegram integration
├── tasks.py                     # Celery tasks
├── config.py                    # Configuration
├── logging_config.py            # Logging configuration
├── requirements.txt             # Dependencies
├── docker-compose.yml           # Dev environment
├── Dockerfile                   # Container build
├── .env.example                 # Environment template
├── .gitignore                   # Git ignore patterns
├── .dockerignore                # Docker ignore patterns
├── alembic.ini                  # Database migrations config
├── LICENSE                      # MIT License
├── README.md                    # This file
├── PREREQUISITES.md             # Prerequisites guide
├── google-cloud-setup.md        # Google Cloud Vision setup guide
│
├── database/
│   ├── __init__.py              # Package initialization
│   ├── models.py                # SQLAlchemy models
│   └── migrations/              # Alembic migrations
│       ├── env.py               # Alembic environment
│       ├── script.py.mako       # Migration template
│       └── versions/            # Migration versions
│
├── services/
│   ├── __init__.py              # Package initialization
│   └── ocr_service.py           # Google Vision OCR
│
└── scripts/
    ├── init_db.py               # DB initialization
    ├── check_services.sh        # Health check script
    ├── backup.sh                # Backup script
    └── deploy.sh                # Deployment script


Prerequisites

Required

  • Python 3.11
  • PostgreSQL 15+
  • Redis 7+
  • Telegram Bot Token (from @BotFather)
  • Google Cloud Account with Vision API enabled

Optional

  • Docker & Docker Compose (for containerized deployment)
  • Sentry account (for error tracking)

Quick Start

New to the project? See PREREQUISITES.md for detailed installation instructions for your OS (macOS, Linux, Windows).

Already have prerequisites? Continue with the setup below.


Local Setup

1. Clone Repository

git clone https://github.com/NadiiaBCN/ops-chatbot.git
cd ops-chatbot

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. Create Environment File

cp .env.example .env
# Edit .env with your values
nano .env

5. Configuration

See PREREQUISITES.md for complete list. Key variables:

Variable Required Description
TELEGRAM_BOT_TOKEN YES Bot token from @BotFather
TELEGRAM_ADMIN_IDS YES Comma-separated admin user IDs
GOOGLE_APPLICATION_CREDENTIALS YES Path to Google Cloud JSON key
GOOGLE_PROJECT_ID YES Google Cloud project ID
DATABASE_URL YES PostgreSQL connection string
REDIS_URL YES Redis connection string
CELERY_BROKER_URL YES Celery broker URL
CELERY_RESULT_BACKEND YES Celery result backend URL

6. Setup PostgreSQL Database

Check if PostgreSQL is installed:

psql --version

If not installed, see PREREQUISITES.md for installation instructions.

Start PostgreSQL service:

macOS:

brew services start postgresql@15

Linux:

sudo systemctl start postgresql

Create database:

# Connect to PostgreSQL
createdb chatbot

# Connect as superuser (without password)
psql -U $(whoami) -d chatbot

# In PostgreSQL console, run:
CREATE USER postgres WITH PASSWORD 'your_secure_password';
CREATE DATABASE chatbot OWNER postgres;
GRANT ALL PRIVILEGES ON DATABASE chatbot TO postgres;
\q

Update .env file:

DATABASE_URL=postgresql+asyncpg://postgres:your_secure_password@localhost:5432/chatbot

7. Initialize Database

# Apply database migrations
alembic upgrade head

# Initialize admin users and seed data
python scripts/init_db.py

8. Start Services

# Terminal 1: Start Redis
redis-server

# Terminal 2: Start Celery worker
celery -A tasks worker --loglevel=info

# Terminal 3: Start Telegram bot
python telegram_bot.py

9. Test Your Bot in Telegram

To test the bot as an admin, open Telegram, find your bot, and send the /start command – you should then see the admin interface.

To test the bot as a client, either log in from another Telegram account (recommended) or temporarily change the TELEGRAM_ADMIN_IDS value in the .env file and restart the bot.

Note: Don't forget to restore the real administrator ID after completing the visitor test.


Usage Guide

For Clients

Making a Deposit:

  1. Send /deposit to the bot
  2. Choose payment method (EUR/USD/CRYPTO)
  3. Send photo of your receipt
  4. Wait for confirmation

Checking Status:

  • Send /mystatus to view recent transactions

Canceling Operation:

  • Send /cancel to cancel current operation

For Administrators

Commands:

  • /admin - Access admin panel
  • /stats - View statistics
  • /transactions - View transactions

Docker Deployment

# Build and start all services
docker-compose up -d

# Apply database migrations (first time only)
docker-compose exec bot alembic upgrade head

# Initialize admin users (first time only)
docker-compose exec bot python scripts/init_db.py

# View logs
docker-compose logs -f

# Stop services
docker-compose down

Health Check

Using Health Check Script

# Make script executable (first time only)
chmod +x scripts/check_services.sh

# Run inside Docker
docker-compose exec bot bash scripts/check_services.sh

Manual Checks

For Docker:

# Check Celery worker
docker-compose exec worker celery -A tasks inspect active

# Check database connection
docker-compose exec bot python -c "from database.models import get_database; print('DB OK')"

# Check Google Cloud Vision
docker-compose exec bot python -c "from google.cloud import vision; print('GCV OK')"

# Check Redis
docker-compose exec redis redis-cli ping

For Local:

# Check Celery worker
celery -A tasks inspect active

# Check database connection
python -c "from database.models import get_database; print('DB OK')"

# Check Google Cloud Vision
python -c "from google.cloud import vision; print('GCV OK')"

# Check Redis
redis-cli ping

Monitoring

Logs

Docker logs:

# View bot logs
docker-compose logs -f bot

# View worker logs
docker-compose logs -f worker

# View all logs
docker-compose logs -f

# View last 100 lines
docker-compose logs --tail=100 bot

File logs:

# Telegram bot logs
tail -f logs/telegram_bot.log

# Celery worker logs
tail -f logs/celery.log

# All logs
tail -f logs/*.log

Flower - Celery Monitoring

Access Flower dashboard at http://localhost:5555

API Health Check

curl http://localhost:8000/health

Troubleshooting

Bot Not Responding

  1. Check if bot token is correct
  2. Check logs: docker-compose logs bot or tail -f logs/telegram_bot.log
  3. Restart bot: docker-compose restart bot

OCR Not Working

  1. Verify Google Cloud credentials path
  2. Check Vision API is enabled
  3. Test credentials:
    docker-compose exec bot python -c "from google.cloud import vision; print('OK')"

Database Connection Failed

  1. Check PostgreSQL is running: docker-compose ps postgres
  2. Verify connection string in .env
  3. Check migrations: docker-compose exec bot alembic current
  4. Apply migrations: docker-compose exec bot alembic upgrade head

Celery Tasks Not Processing

  1. Check Redis is running: docker-compose exec redis redis-cli ping
  2. Verify Celery worker is active: docker-compose exec worker celery -A tasks inspect active
  3. Check Celery logs: docker-compose logs worker

Database Errors ("Failed to save transaction")

  1. Ensure migrations are applied:
    docker-compose exec bot alembic upgrade head
  2. Initialize database:
    docker-compose exec bot python scripts/init_db.py
  3. Check database tables:
    docker-compose exec postgres psql -U postgres -d chatbot -c "\dt"
  4. Restart services:
    docker-compose restart bot worker

Import Errors (ModuleNotFoundError)

If you see errors like ModuleNotFoundError: No module named 'config' or 'database':

  1. Ensure you're in the project root directory:

    cd /path/to/ops-chatbot
  2. Activate virtual environment:

    source venv/bin/activate
  3. Run commands from project root, not from subdirectories


Contributing

Contributions are welcome! Please follow code style:

  • Follow PEP 8
  • Add docstrings to all functions
  • Write tests for new features
  • Update documentation

License

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

About

Telegram bot for handling deposit and withdrawal transactions with automatic receipt recognition using Google Cloud Vision API. Designed for operations teams requiring real-time notifications and transaction management.

Topics

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages