An intelligent personal finance assistant Telegram bot powered by AI
Track expenses and income, generate reports, set reminders - all through natural language conversations in your preferred language
π Table of Contents
- Overview
- Key Features
- Technology Stack
- Prerequisites
- Installation
- Configuration
- Usage Guide
- Architecture
- Project Structure
- API Documentation
- Troubleshooting
- Contributing
- License
- Author & Support
π― Overview
SmartExpenseBot is a sophisticated Telegram bot designed to help users manage their personal finances effortlessly. Leveraging the power of DeepSeek AI and advanced natural language processing, it transforms expense tracking from a tedious task into an intuitive conversation.
Core Philosophy
The bot understands that managing finances shouldn't be complicated. Whether you're on-the-go, prefer voice messages, or speak different languages, SmartExpenseBot adapts to your needs and helps you maintain better financial awareness.
Key Highlights
- π€ AI-Powered Intelligence: Four specialized AI instances handle different aspects of financial management
- π Universal Language Support: Full support for English, Russian, and Uzbek with intelligent country detection
- π€ Voice-First Design: Record expenses and income via voice messages with automatic transcription
- β° Smart Automation: Automated daily reminders at personalized times
- π Intelligent Reporting: Natural language queries for instant financial insights with income/expense balance
- π° Income Tracking: Track monthly and daily income alongside expenses
- π³ Unified Currency System: Single currency preference for all financial operations
- π Privacy-Focused: Local database storage with optional PostgreSQL support
- β€οΈ Support the Project: Multiple donation options including Telegram Stars
β¨ Key Features
πΈ Intelligent Expense Management
Multi-Modal Input
- Text messages:
"Spent 50 yuan on lunch" - Voice messages: Speak naturally about your expenses
- Support for multiple expenses in a single message
AI-Powered Categorization
- Automatic expense extraction (amount, currency, description)
- Smart category assignment (Food, Transport, Entertainment, etc.)
- Currency detection and normalization
- Intelligent fallback for edge cases
Unified Currency System
- Single currency preference per user (stored in User table)
- Automatic currency detection (USD, EUR, CNY, RUB, UZS, etc.)
- Currency selection on first expense/income entry
- All expenses and income displayed in user's selected currency
- Change currency anytime from settings
Confirmation Workflow
- Review AI-extracted information before saving
- Batch confirmation for multiple expenses
- Easy cancellation and modification
π° Income Tracking
Income Management
- Track monthly and daily income
- Text and voice input support
- AI-powered income extraction
- Income type classification (monthly/daily)
Income Features
- Natural language input:
"I earned 5000 yuan this month" - Voice message support for income entry
- Income confirmation workflow
- Income included in financial reports
π Advanced Reporting & Analytics
Natural Language Queries
- Ask questions in plain language:
"Show my food expenses this month" - Conversational report generation in your preferred language
- Context-aware responses based on your expense and income history
- Income vs expense balance calculations
Flexible Time Filtering
- Daily, weekly, monthly reports
- Custom date range selection
- Historical data analysis
Comprehensive Insights
- Category-based expense breakdowns
- Income and expense summaries
- Balance calculations (income - expenses)
- Spending trends and patterns
- All amounts displayed in your selected currency
β° Smart Reminder System
Intelligent Time Parsing
- Natural language time expressions:
"Remind me tomorrow at 3 PM" - Relative time handling:
"Remind me in 2 hours" - Timezone-aware scheduling
Dual Notification System
- Warning notification 10 minutes before scheduled time
- Exact time reminder notification
- Automatic reminder tracking
Daily Expense Reminders
- Personalized daily notifications at 20:00 (user's local time)
- Automatic scheduling based on user timezone
- Multi-language reminder messages
π Internationalization & Localization
Language Support
- English: Full feature support
- Russian (Π ΡΡΡΠΊΠΈΠΉ): Complete localization
- Uzbek (O'zbek): Full native language support
Smart Country Detection
- AI-powered country name recognition in any supported language
- Automatic timezone detection from country input
- Location-based timezone detection via GPS coordinates
- Manual timezone configuration option
Localized User Experience
- Language-specific date/time formatting
- Cultural context awareness
- Native currency suggestions
π€ Voice Transcription
Multi-Language Voice Support
- Voice message transcription using Vosk
- Support for Uzbek, Russian, and English
- Automatic language detection and model selection
Optimized Performance
- Shared model cache (loads once, used by all instances)
- Thread-safe model initialization
- Efficient memory management
Audio Processing
- Automatic format conversion (OGG, MP3 β WAV)
- Sample rate normalization (16kHz mono)
- Clean temporary file management
π‘οΈ Robust Architecture
Thread-Safe Operations
- Concurrent user request handling
- Safe database session management
- Atomic operations for data integrity
Database Flexibility
- SQLite for development and small deployments
- PostgreSQL for production scalability
- Automatic schema migration
- Connection pooling
Error Handling
- Comprehensive exception catching
- Graceful degradation
- Detailed logging for debugging
- User-friendly error messages
π Technology Stack
| Component | Technology | Version |
|---|---|---|
| Language | Python | 3.8+ |
| Bot Framework | pyTelegramBotAPI | 4.14.0 |
| ORM & Database | SQLAlchemy | β₯2.0.36 |
| Database Drivers | SQLite3 (built-in), psycopg2-binary | 2.9.10 |
| AI Integration | DeepSeek API | Latest |
| Speech Recognition | Vosk | 0.3.45 |
| Task Scheduling | APScheduler | 3.10.4 |
| Audio Processing | FFmpeg, pydub | 0.25.1 |
| Timezone Handling | pytz, timezonefinderL | 2024.1 |
| HTTP Requests | requests | 2.32.4 |
| Date Parsing | python-dateutil | 2.8.2 |
| Configuration | python-dotenv | 1.0.0 |
π¦ Prerequisites
Before installing SmartExpenseBot, ensure you have:
- Python 3.8 or higher (Python 3.10+ recommended)
- FFmpeg installed and accessible in PATH
- Telegram Bot Token (obtain from @BotFather)
- DeepSeek API Key (obtain from DeepSeek Platform)
- Vosk Models (optional, for voice transcription)
System Dependencies
Ubuntu/Debian:
sudo apt-get update sudo apt-get install ffmpeg python3-pip python3-venv
macOS:
brew install ffmpeg python3
Windows:
- Download Python from python.org
- Download FFmpeg from ffmpeg.org and add to PATH
π Installation
Step 1: Clone the Repository
git clone https://github.com/botirbakhtiyarov/SmartExpenseBot.git
cd SmartExpenseBotStep 2: Create Virtual Environment
# Create virtual environment python3 -m venv venv # Activate virtual environment # On Linux/macOS: source venv/bin/activate # On Windows: venv\Scripts\activate
Step 3: Install Python Dependencies
pip install --upgrade pip pip install -r requirements.txt
Step 4: Download Vosk Models (Optional but Recommended)
For voice transcription support, download language models from Vosk Models:
Recommended Models:
vosk-model-small-uz-0.22(Uzbek - ~45MB)vosk-model-small-ru-0.22(Russian - ~45MB)vosk-model-small-en-us-0.22(English - ~45MB)
Installation Steps:
- Download the models:
# Create models directory mkdir -p models # Download and extract (example for Uzbek) cd models wget https://alphacephei.com/vosk/models/vosk-model-small-uz-0.22.zip unzip vosk-model-small-uz-0.22.zip mv vosk-model-small-uz-0.22 vosk-model-uz # Repeat for other languages cd ..
- Verify structure:
models/
βββ vosk-model-uz/
β βββ am/
β βββ conf/
β βββ ...
βββ vosk-model-ru/
β βββ ...
βββ vosk-model-en/
βββ ...
βοΈ Configuration
Step 1: Create Environment File
Create a .env file in the project root:
cp .env.example .env # If example exists # Or create manually touch .env
Step 2: Configure Environment Variables
Edit .env with your configuration:
# ============================================ # REQUIRED CONFIGURATION # ============================================ # Telegram Bot Token (from @BotFather) BOT_TOKEN=your_telegram_bot_token_here # DeepSeek API Configuration DEEPSEEK_API_KEY=your_deepseek_api_key_here DEEPSEEK_API_URL=https://api.deepseek.com/v1/chat/completions # ============================================ # OPTIONAL CONFIGURATION # ============================================ # Developer ID (for receiving feedback) DEVELOPER_ID=your_telegram_user_id # Database Configuration # Options: 'sqlite' or 'postgresql' DB_TYPE=sqlite # SQLite Configuration (if DB_TYPE=sqlite) SQLITE_DB_PATH=smart_expense_bot.db # PostgreSQL Configuration (if DB_TYPE=postgresql) POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_DB=smart_expense_bot POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres # Vosk Model Paths (optional) VOSK_MODEL_PATH_UZ=./models/vosk-model-uz VOSK_MODEL_PATH_RU=./models/vosk-model-ru VOSK_MODEL_PATH_EN=./models/vosk-model-en # Proxy Configuration (optional) # PROXY_URL=socks5://127.0.0.1:10808 # PROXY_URL=http://proxy.example.com:8080
Step 3: Verify Configuration
Test your configuration:
You should see:
- Configuration validation messages
- Database initialization confirmation
- Scheduler startup notification
- Bot polling status
If errors occur, check:
- Environment variables are set correctly
- API keys are valid
- Database connection (if using PostgreSQL)
- Required dependencies are installed
π Usage Guide
Starting the Bot
The bot will:
- Validate configuration
- Initialize database (create tables if needed)
- Load Vosk models (if available)
- Start the reminder scheduler
- Begin polling for Telegram messages
First-Time Setup
When a user first interacts with the bot:
- Language Selection: User chooses their preferred language (English, Russian, or Uzbek)
- Timezone Setup:
- Option A: Share location (GPS coordinates)
- Option B: Enter country name in any language
- Option C: Skip (defaults to UTC)
- Currency Selection: Choose default currency preference
- Ready to Use: Main menu appears
Using Expense Tracking
Adding Single Expense
Via Text:
User: "I spent 25 dollars on lunch at McDonald's"
Bot: [Shows categorized expense for confirmation]
Amount: $25.00
Category: Food
Description: lunch at McDonald's
[Yes] [No]
Via Voice:
- Tap microphone icon
- Speak: "Spent 50 yuan on taxi ride"
- Bot transcribes and categorizes
- Confirm to save
Adding Multiple Expenses
Example:
User: "I spent 30 dollars on groceries, 15 on gas, and 20 on movie tickets"
Bot: [Shows 3 separate expenses]
1. $30 - Food - groceries
2. $15 - Transport - gas
3. $20 - Entertainment - movie tickets
[Save All] [Cancel]
Generating Reports
Natural Language Queries
Time-Based Queries:
"Show my expenses this month"
"What did I spend last week?"
"Total expenses in December"
Category-Based Queries:
"Show my food expenses"
"How much did I spend on transport?"
"Entertainment expenses this year"
Complex Queries:
"Compare my spending this month vs last month"
"Show my top spending categories"
"What's my average daily expense?"
Setting Reminders
Simple Reminders
"Remind me to pay bills tomorrow at 3 PM"
"Remind me in 2 hours to call mom"
"Set reminder for next Friday at 10 AM"
Reminder Notifications
- Warning Notification: Sent 10 minutes before scheduled time
- Exact Time Notification: Sent at the scheduled time
Managing Settings
Access settings via the βοΈ Settings button:
- Change Language: Switch between English, Russian, Uzbek
- Edit Profile: Update your display name
- Change Timezone: Update timezone (location or country name)
- Change Currency: Update your default currency preference
- Delete Account: Permanently delete your account and all data (with confirmation)
Tracking Income
Adding Income
Via Text:
User: "I earned 5000 yuan this month"
Bot: [Shows income for confirmation]
Amount: 5000.00 CNY
Type: Monthly
Description: (if provided)
[Yes] [No]
Via Voice:
- Tap Income button
- Speak: "Earned 3000 dollars today"
- Bot transcribes and extracts income
- Confirm to save
Income Types
- Monthly Income: Regular monthly earnings
- Daily Income: Daily earnings or one-time income
Daily Expense Reminders
Every day at 20:00 (8 PM) in your local timezone, you'll automatically receive:
English:
π° Daily Reminder: Don't forget to input your expenses today! Recording your expenses helps you control your financial situation.
Russian:
π° ΠΠΆΠ΅Π΄Π½Π΅Π²Π½ΠΎΠ΅ Π½Π°ΠΏΠΎΠΌΠΈΠ½Π°Π½ΠΈΠ΅: ΠΠ΅ Π·Π°Π±ΡΠ΄ΡΡΠ΅ Π²Π½Π΅ΡΡΠΈ ΡΠ΅Π³ΠΎΠ΄Π½ΡΡΠ½ΠΈΠ΅ ΡΠ°ΡΡ ΠΎΠ΄Ρ! ΠΠ°ΠΏΠΈΡΡ Π²Π°ΡΠΈΡ ΡΠ°ΡΡ ΠΎΠ΄ΠΎΠ² ΠΏΠΎΠΌΠΎΠΆΠ΅Ρ Π²Π°ΠΌ ΠΊΠΎΠ½ΡΡΠΎΠ»ΠΈΡΠΎΠ²Π°ΡΡ ΡΠ²ΠΎΠ΅ ΡΠΈΠ½Π°Π½ΡΠΎΠ²ΠΎΠ΅ ΠΏΠΎΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅.
Uzbek:
π° Kunlik eslatma: Bugungi xarajatlaringizni kiritishni unutmang! Xarajatlaringizni yozib olish sizga moliyaviy holatingizni nazorat qilishda yordam beradi.
Supporting the Project
SmartExpenseBot is free to use, but your support helps maintain and improve the project!
Donation Options:
- β Telegram Stars: Quick and easy donations via Telegram
- Preset amounts: 10, 50, 100 stars
- Custom amount option
- πΊπΏ Tirikchilik.uz: For users in Uzbekistan
- π Patreon: Monthly subscription support
- π GitHub Sponsors: For developers
Access donations via the "About Us" β "Donate" menu. All donations are greatly appreciated! π
π Architecture
System Design
βββββββββββββββββββ
β Telegram API β
ββββββββββ¬βββββββββ
β
βΌ
βββββββββββββββββββ
β bot.py β β Main Entry Point
β (Message Loop) β
ββββββββββ¬βββββββββ
β
ββββββ΄βββββ¬βββββββββββββ¬βββββββββββββ¬ββββββββββββββ
β β β β β
βΌ βΌ βΌ βΌ βΌ
ββββββββββ ββββββββββ βββββββββββ ββββββββββββ βββββββββββ
βExpense β βReport β βReminder β βSettings β β About β
βHandler β βHandler β β Handler β β Handler β β Handler β
βββββ¬βββββ βββββ¬βββββ ββββββ¬βββββ ββββββ¬ββββββ ββββββ¬βββββ
β β β β β
ββββββββββββ΄ββββββββββββ΄ββββββββββββ΄βββββββββββββ
β
βββββββββββββΌββββββββββββ¬βββββββββββββββ
β β β β
βΌ βΌ βΌ βΌ
βββββββββββ βββββββββββ ββββββββββββ ββββββββββββ
β AI β βDatabase β βScheduler β β Vosk β
βFunctionsβ β (ORM) β β(APSched) β β Models β
βββββββββββ βββββββββββ ββββββββββββ ββββββββββββ
AI Architecture
The bot uses three specialized AI instances from DeepSeek:
1. DeepSeek_AI_1: Expense Extraction
- Purpose: Extract expense information from natural language
- Input: User's expense description (text or transcribed voice)
- Output: Structured expense data (amount, currency, category, description)
- Specialization: Currency detection, category assignment
2. DeepSeek_AI_2: Time Parsing
- Purpose: Extract time/date information from reminder messages
- Input: User's reminder text with time reference
- Output: ISO format datetime string
- Specialization: Relative time parsing, timezone awareness
3. DeepSeek_AI_Country: Country Detection
- Purpose: Detect country names in any language and return timezone
- Input: Country name in any language
- Output: IANA timezone name
- Specialization: Multi-language country recognition
4. DeepSeek_AI_Income: Income Extraction
- Purpose: Extract income information from natural language
- Input: User's income description (text or transcribed voice)
- Output: Structured income data (amount, currency, type, description)
- Specialization: Income type detection (monthly/daily), currency detection
5. DeepSeek_AI_data: Report Generation
- Purpose: Generate comprehensive financial reports with income and expenses
- Input: User's report query + expense/income data from database + user currency
- Output: Natural language report with insights in user's language
- Specialization: Data analysis, pattern recognition, balance calculations
Database Schema
User βββ id (PK) βββ telegram_id (Unique, Indexed) βββ name βββ language (default: 'en') βββ timezone (default: 'UTC') βββ currency (default: 'USD') # Single currency for all financial operations βββ created_at βββ expenses (1-to-Many) βββ incomes (1-to-Many) βββ reminders (1-to-Many) Expense βββ id (PK) βββ user_id (FK β User.id) βββ amount βββ category βββ description βββ date (Indexed) βββ created_at Note: Expenses use currency from User table (not stored separately) Income βββ id (PK) βββ user_id (FK β User.id) βββ amount βββ currency (stored for compatibility, but always matches User.currency) βββ description βββ income_type ('monthly' or 'daily') βββ date (Indexed) βββ created_at Reminder βββ id (PK) βββ user_id (FK β User.id) βββ message βββ reminder_time (Indexed) βββ created_at βββ sent (0 or 1)
Thread Safety
- Database Sessions: Uses SQLAlchemy
scoped_sessionfor thread-local sessions - Model Loading: Singleton pattern for Vosk models (shared cache)
- Scheduler: Thread-safe APScheduler with UTC timezone
- Concurrent Users: Each request handled in isolated context
π Project Structure
SmartExpenseBot/
β
βββ handlers/ # Command handlers (MVC pattern)
β βββ __init__.py
β βββ expense_handler.py # Expense tracking logic
β β βββ ExpenseHandler class
β βββ income_handler.py # Income tracking logic
β β βββ IncomeHandler class
β βββ report_handler.py # Report generation logic
β β βββ ReportHandler class
β βββ reminder_handler.py # Reminder management
β β βββ ReminderHandler class
β β βββ Helper functions (timezone detection)
β βββ settings_handler.py # User settings management
β β βββ SettingsHandler class
β βββ about_handler.py # About page, feedback & donations
β βββ AboutHandler class
β
βββ ai_functions.py # DeepSeek AI integration
β βββ deepseek_ai_expense() # Expense extraction
β βββ deepseek_ai_expense_multiple() # Multiple expense extraction
β βββ deepseek_ai_income() # Income extraction
β βββ deepseek_ai_reminder() # Time parsing
β βββ deepseek_ai_country() # Country detection
β βββ deepseek_ai_report() # Report generation (with income/expense)
β βββ _extract_expense_manually() # Fallback extraction
β
βββ bot.py # Main application entry point
β βββ Message handlers
β βββ Callback handlers
β βββ Bot initialization
β
βββ config.py # Configuration management
β βββ Config class (environment variables)
β
βββ database.py # Database layer
β βββ User model
β βββ Expense model
β βββ Income model
β βββ Reminder model
β βββ Database class (CRUD operations)
β
βββ keyboards.py # UI keyboard utilities
β βββ create_main_keyboard()
β βββ create_language_keyboard()
β βββ create_currency_keyboard()
β βββ create_report_keyboard()
β
βββ translations.py # Internationalization
β βββ TRANSLATIONS dict
β βββ get_translation()
β βββ get_language_name()
β
βββ voice_transcriber.py # Voice transcription
β βββ VoiceTranscriber class (singleton pattern)
β
βββ scheduler.py # Task scheduling
β βββ ReminderScheduler class
β βββ Reminder scheduling
β βββ Daily expense reminders
β
βββ models/ # Vosk model files (git-ignored)
β βββ vosk-model-uz/
β βββ vosk-model-ru/
β βββ vosk-model-en/
β
βββ requirements.txt # Python dependencies
βββ .env # Environment variables (git-ignored)
βββ .env.example # Environment template
βββ LICENSE # MIT License
βββ README.md # This file
π API Documentation
Environment Variables
| Variable | Description | Required | Default | Example |
|---|---|---|---|---|
BOT_TOKEN |
Telegram bot token from @BotFather | β Yes | - | 123456789:ABCdef... |
DEEPSEEK_API_KEY |
DeepSeek API authentication key | β Yes | - | sk-... |
DEEPSEEK_API_URL |
DeepSeek API endpoint URL | β Yes | https://api.deepseek.com/v1/chat/completions |
- |
DEVELOPER_ID |
Telegram user ID for receiving feedback | β No | 0 |
123456789 |
DB_TYPE |
Database type: sqlite or postgresql |
β Yes | sqlite |
postgresql |
SQLITE_DB_PATH |
SQLite database file path | If SQLite | smart_expense_bot.db |
./data/bot.db |
POSTGRES_HOST |
PostgreSQL server host | If PostgreSQL | localhost |
db.example.com |
POSTGRES_PORT |
PostgreSQL server port | If PostgreSQL | 5432 |
5432 |
POSTGRES_DB |
PostgreSQL database name | If PostgreSQL | smart_expense_bot |
expense_bot |
POSTGRES_USER |
PostgreSQL username | If PostgreSQL | postgres |
bot_user |
POSTGRES_PASSWORD |
PostgreSQL password | If PostgreSQL | postgres |
secure_password |
PROXY_URL |
Proxy server URL (optional) | β No | - | socks5://127.0.0.1:10808 |
VOSK_MODEL_PATH_UZ |
Path to Uzbek Vosk model | β No | ./models/vosk-model-uz |
/path/to/model |
VOSK_MODEL_PATH_RU |
Path to Russian Vosk model | β No | ./models/vosk-model-ru |
/path/to/model |
VOSK_MODEL_PATH_EN |
Path to English Vosk model | β No | ./models/vosk-model-en |
/path/to/model |
Database Methods
User Management
# Get or create user user = db.get_or_create_user(telegram_id: int, name: str) -> User # Update user settings db.update_user_language(telegram_id: int, language: str) db.update_user_name(telegram_id: int, name: str) db.update_user_timezone(telegram_id: int, timezone: str) db.update_user_currency(telegram_id: int, currency: str) # Get all users with timezone set users = db.get_all_users_with_timezone() -> List[User] # Check if user exists exists = db.user_exists(telegram_id: int) -> bool # Delete user and all related data success = db.delete_user(telegram_id: int) -> bool
Expense Management
# Add expense expense = db.add_expense( telegram_id: int, amount: float, currency: str, category: str, description: str = None ) -> Expense # Get expenses with filters expenses = db.get_expenses( telegram_id: int, start_date: datetime = None, end_date: datetime = None, category: str = None, limit: int = 100 ) -> List[Expense]
Income Management
# Add income (uses user's currency from User table) income = db.add_income( telegram_id: int, amount: float, currency: str = None, # Optional, uses User.currency if not provided description: str = None, income_type: str = 'monthly' # 'monthly' or 'daily' ) -> Income # Get incomes with filters incomes = db.get_incomes( telegram_id: int, start_date: datetime = None, end_date: datetime = None, limit: int = 100 ) -> List[Income]
Reminder Management
# Add reminder reminder = db.add_reminder( telegram_id: int, message: str, reminder_time: datetime ) -> Reminder # Get pending reminders reminders = db.get_pending_reminders(before_time: datetime) -> List[Reminder] # Mark reminder as sent db.mark_reminder_sent(reminder_id: int)
AI Functions
Expense Extraction
from ai_functions import deepseek_ai_expense, deepseek_ai_expense_multiple # Single expense result = deepseek_ai_expense( text: str, lang: str = "en" ) -> Dict[str, Any] # Returns: {"amount": float, "currency": str, "category": str, # "description": str, "advice": str} # Multiple expenses expenses = deepseek_ai_expense_multiple( text: str, lang: str = "en", default_currency: str = "USD" ) -> List[Dict[str, Any]]
Time Parsing
from ai_functions import deepseek_ai_reminder time_str = deepseek_ai_reminder( text: str, lang: str = "en", user_timezone: str = "UTC", current_time: datetime = None ) -> Optional[str] # ISO format datetime string
Country Detection
from ai_functions import deepseek_ai_country timezone = deepseek_ai_country( country_text: str, lang: str = "en" ) -> Optional[str] # IANA timezone name
Income Extraction
from ai_functions import deepseek_ai_income result = deepseek_ai_income( text: str, lang: str = "en", default_currency: str = "USD" ) -> Dict[str, Any] # Returns: {"amount": float, "currency": str, "description": str, # "income_type": str} # 'monthly' or 'daily'
Report Generation
from ai_functions import deepseek_ai_report report = deepseek_ai_report( text: str, lang: str = "en", expenses_data: List[Union[Expense, Income]] = None, user_currency: str = "USD" # User's currency from User table ) -> str # Natural language report in user's language
π§ Troubleshooting
Common Issues
Bot Not Responding
Symptoms: Bot doesn't respond to any messages
Diagnosis Steps:
- Check if bot process is running:
ps aux | grep bot.py - Review application logs for errors
- Verify bot token is correct: Check
.envfile
Solutions:
- Verify
BOT_TOKENis correct and active - Ensure bot has necessary permissions in Telegram
- Check network connectivity
- Review logs for specific error messages
- Restart the bot process
Database Connection Errors
Symptoms: Database-related errors in logs
Solutions:
For SQLite:
- Verify write permissions in database directory
- Check disk space availability
- Ensure database file path is correct
For PostgreSQL:
- Verify connection credentials
- Check PostgreSQL service is running:
sudo systemctl status postgresql - Test connection:
psql -h host -U user -d database - Verify network connectivity
- Check firewall rules
Voice Transcription Not Working
Symptoms: Voice messages not transcribed
Diagnosis:
- Check if Vosk models are downloaded
- Verify model paths in environment variables
- Check FFmpeg installation:
ffmpeg -version - Review logs for transcription errors
Solutions:
- Download missing Vosk models
- Verify model paths match actual directories
- Install FFmpeg:
sudo apt-get install ffmpeg(Ubuntu) orbrew install ffmpeg(macOS) - Check available disk space for temporary files
- Verify audio format is supported (OGG, MP3, WAV)
AI Categorization Errors
Symptoms: Expenses not categorized correctly or API errors
Solutions:
- Verify
DEEPSEEK_API_KEYis valid and active - Check API endpoint URL is correct
- Review API rate limits and quotas
- Check network connectivity to DeepSeek API
- Review API response logs for detailed errors
- Check API account balance/credits
Timezone Detection Issues
Symptoms: Reminders scheduled at wrong times or timezone not detected
Solutions:
- For location-based: Ensure user shared GPS location
- For country-based: Try different country name formats
- Verify
timezonefinderLis installed:pip install timezonefinderL - Manually set timezone in settings
- Check timezone string format (must be valid IANA timezone)
Concurrent User Errors
Symptoms: Errors when multiple users use bot simultaneously
Solutions:
- Ensure using latest version with thread-safe session management
- For SQLite: Bot configured with proper thread settings
- For PostgreSQL: Connection pooling enabled automatically
- Check database connection limits
- Review error logs for specific thread-safety issues
Model Loading Issues
Symptoms: Vosk models loading multiple times or memory errors
Solutions:
- Models use singleton pattern (should load once)
- Check available system memory
- Verify model files are complete (not corrupted)
- Review logs for model loading errors
Debug Mode
Enable detailed logging:
# In bot.py, change log level: logging.basicConfig( level=logging.DEBUG, # Change from INFO to DEBUG format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
Getting Help
If issues persist:
- Check GitHub Issues
- Enable debug logging and review logs
- Create detailed issue report with:
- Error messages
- Steps to reproduce
- System information
- Relevant log excerpts
π€ Contributing
We welcome contributions! Here's how you can help:
Contribution Guidelines
-
Fork the Repository
git clone https://github.com/botirbakhtiyarov/SmartExpenseBot.git
-
Create Feature Branch
git checkout -b feature/AmazingFeature
-
Make Changes
- Follow PEP 8 style guidelines
- Add comments for complex logic
- Update documentation as needed
- Write/update tests if applicable
-
Commit Changes
git commit -m 'Add some AmazingFeature' -
Push to Branch
git push origin feature/AmazingFeature
-
Open Pull Request
- Provide clear description of changes
- Reference any related issues
- Ensure all tests pass
Code Style
- Follow PEP 8 Python style guide
- Use type hints for function signatures
- Add docstrings for all functions and classes
- Keep functions focused and modular
- Use descriptive variable names
Testing
- Test your changes thoroughly
- Test with multiple languages
- Test edge cases
- Ensure backward compatibility
π License
This project is licensed under the MIT License - see the LICENSE file for details.
License Summary
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files, to deal in the software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software.
π€ Author & Support
Version
Current Version: v1.2.0
See CHANGELOG.md for detailed version history and upgrade notes.
Author
Botir Bakhtiyarov
- π GitHub: @botirbakhtiyarov
- π¬ Telegram: @bakhtiyarovbotir
- π§ Email: botirbakhtiyarovb@gmail.com
Support Channels
- GitHub Issues: Report Bugs or Request Features
- Telegram: Use the bot's "About Us" β "Feedback" feature
- Email: botirbakhtiyarovb@gmail.com
Support the Project
If you find SmartExpenseBot useful, please consider supporting its development:
- β Telegram Stars: Quick donations via Telegram
- πΊπΏ Tirikchilik.uz: Support via Tirikchilik
- π Patreon: Monthly Support
- π GitHub Sponsors: Sponsor on GitHub
Every contribution helps improve the bot! π
Acknowledgments
This project uses the following excellent libraries and services:
- pyTelegramBotAPI - Elegant Telegram Bot API wrapper
- DeepSeek - Powerful AI API for natural language processing
- Vosk - Offline speech recognition toolkit
- SQLAlchemy - Python SQL toolkit and ORM
- APScheduler - Advanced Python Scheduler
- TimezoneFinderL - Fast timezone lookup library