Architecture Overview

System Architecture

BitMshauri is built with a modular, scalable architecture designed for reliability and maintainability:

Presentation Layer

  • Telegram Bot Interface
  • Web Dashboard (Future)
  • API Endpoints

Application Layer

  • Bot Command Handlers
  • Business Logic Services
  • AI Integration

Data Layer

  • SQLite Database
  • External APIs
  • File Storage

Technology Stack

Python 3.8+

Core programming language

SQLite

Lightweight database

Telegram Bot API

Messaging platform

OpenAI GPT

AI-powered Q&A

Development Setup

Prerequisites

  • Python 3.8 or higher
  • Git
  • Telegram Bot Token (from @BotFather)
  • OpenAI API Key (optional, for AI features)

Installation Steps

1. Clone the Repository

git clone https://github.com/MWANGAZA-LAB/bitmshauri-bot.git cd bitmshauri-bot-3

2. Create Virtual Environment

python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate

3. Install Dependencies

pip install -r requirements.txt

4. Configure Environment

cp .env.example .env # Edit .env with your bot token and API keys

5. Initialize Database

python setup.py

6. Run the Bot

python app/enhanced_telegram_bot.py

Development Tips

Use the --debug flag when running the bot for detailed logging and development features.

Project Structure

Directory Layout

bitmshauri-bot-3/
├── app/
│   ├── __init__.py
│   ├── enhanced_telegram_bot.py    # Main bot entry point
│   ├── database.py                 # Database models
│   ├── enhanced_database.py        # Enhanced database operations
│   ├── routes.py                   # Web routes (future)
│   └── bot/
│       ├── __init__.py
│       ├── telegram_bot.py         # Core bot functionality
│       ├── price_api.py            # Price fetching
│       ├── content_swahili.py      # Swahili content
│       └── audio_tts.py            # Text-to-speech
├── app/services/
│   ├── calculator.py               # Price calculator
│   ├── community.py                # Group features
│   ├── content_manager.py          # Content management
│   ├── enhanced_audio.py           # Audio processing
│   ├── multi_language.py           # Language handling
│   ├── price_service.py            # Price services
│   └── progress_tracker.py         # User progress
├── app/utils/
│   ├── logger.py                   # Logging utilities
│   └── rate_limiter.py             # Rate limiting
├── docs/                           # Documentation
├── tests/                          # Test suite
├── requirements.txt                # Python dependencies
├── config.py                       # Configuration
├── main.py                         # Alternative entry point
└── setup.py                        # Setup script

Core Components

Bot Handler

The main bot handler manages incoming messages and routes them to appropriate services:

enhanced_telegram_bot.py

  • Message routing and command handling
  • User session management
  • Error handling and logging
  • Rate limiting implementation

Service Layer

Calculator Service

Handles currency conversions and price calculations

app/services/calculator.py

Community Service

Manages study groups and community features

app/services/community.py

Content Manager

Handles educational content and lessons

app/services/content_manager.py

Multi-language

Language detection and translation

app/services/multi_language.py

Database Layer

The database layer provides data persistence and user management:

  • User Management: User profiles, preferences, and progress
  • Content Storage: Lessons, quizzes, and educational materials
  • Community Data: Study groups and group interactions
  • Analytics: Usage statistics and learning metrics

Database Schema

Core Tables

Users Table

CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    telegram_id INTEGER UNIQUE NOT NULL,
    username TEXT,
    first_name TEXT,
    last_name TEXT,
    language TEXT DEFAULT 'en',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_active TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    progress_data TEXT,  -- JSON string
    preferences TEXT     -- JSON string
);

Lessons Table

CREATE TABLE lessons (
    id INTEGER PRIMARY KEY,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    language TEXT NOT NULL,
    difficulty INTEGER DEFAULT 1,
    category TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

User Progress Table

CREATE TABLE user_progress (
    id INTEGER PRIMARY KEY,
    user_id INTEGER,
    lesson_id INTEGER,
    completed BOOLEAN DEFAULT FALSE,
    score INTEGER,
    completed_at TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (lesson_id) REFERENCES lessons(id)
);

Study Groups Table

CREATE TABLE study_groups (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT,
    creator_id INTEGER,
    max_members INTEGER DEFAULT 50,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (creator_id) REFERENCES users(id)
);

API Integrations

External APIs

Telegram Bot API

Primary messaging platform

  • Message handling
  • Inline keyboards
  • File uploads
  • Webhook support

CoinGecko API

Cryptocurrency price data

  • Real-time prices
  • Historical data
  • Market statistics
  • Currency conversion

OpenAI GPT API

AI-powered Q&A system

  • Natural language processing
  • Context-aware responses
  • Multi-language support
  • Educational content generation

Rate Limiting

The bot implements intelligent rate limiting to prevent abuse:

  • User-based limits: Maximum requests per user per time window
  • Action-specific limits: Different limits for different commands
  • Progressive penalties: Increasing delays for repeated violations
  • Whitelist support: Exempt trusted users from limits

Testing

Test Suite

Comprehensive testing ensures reliability and quality:

Unit Tests

Test individual components and functions

python -m pytest tests/unit/

Integration Tests

Test component interactions

python -m pytest tests/integration/

End-to-End Tests

Test complete user workflows

python -m pytest tests/e2e/

Running Tests

Run all tests: python -m pytest
Run with coverage: python -m pytest --cov=app
Run specific test file: python -m pytest tests/test_calculator.py

Deployment

Production Deployment

Deploy the bot to production using various platforms:

Heroku

Easy deployment with Procfile support

git push heroku main

Railway

Modern deployment platform

railway up

VPS/Dedicated Server

Full control over deployment

systemctl start bitmshauri-bot

Environment Variables

TELEGRAM_BOT_TOKEN

Your Telegram bot token from @BotFather

OPENAI_API_KEY

OpenAI API key for AI features

DATABASE_PATH

Path to SQLite database file

LOG_LEVEL

Logging level (DEBUG, INFO, WARNING, ERROR)

Contributing

How to Contribute

We welcome contributions from the community! Here's how to get started:

1. Fork the Repository

Create your own fork of the project on GitHub

2. Create a Feature Branch

git checkout -b feature/your-feature-name

3. Make Your Changes

Implement your feature or fix with proper testing

4. Run Tests

python -m pytest

5. Submit a Pull Request

Create a PR with a clear description of your changes

Development Guidelines

  • Code Style: Follow PEP 8 Python style guidelines
  • Documentation: Add docstrings and update README if needed
  • Testing: Write tests for new features
  • Commits: Use clear, descriptive commit messages
  • Branch Naming: Use descriptive branch names (feature/, bugfix/, etc.)

Areas for Contribution

New Features

  • Additional language support
  • New educational content
  • Enhanced AI capabilities
  • Mobile app integration

Bug Fixes

  • Report and fix bugs
  • Improve error handling
  • Performance optimizations
  • Security enhancements

Documentation

  • Improve code documentation
  • Update user guides
  • Create tutorials
  • Translate documentation