An intelligent personal finance assistant Telegram bot powered by AI
Track expenses, generate reports, set reminders - all through natural language conversations in your preferred language
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.
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.
Multi-Modal Input
"Spent 50 yuan on lunch"AI-Powered Categorization
Multiple Currency Support
Confirmation Workflow
Natural Language Queries
"Show my food expenses this month"Flexible Time Filtering
Comprehensive Insights
Intelligent Time Parsing
"Remind me tomorrow at 3 PM""Remind me in 2 hours"Dual Notification System
Daily Expense Reminders
Language Support
Smart Country Detection
Localized User Experience
Multi-Language Voice Support
Optimized Performance
Audio Processing
Thread-Safe Operations
Database Flexibility
Error Handling
| 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, 0.1.0 |
| HTTP Requests | requests | 2.32.4 |
| Date Parsing | python-dateutil | 2.8.2 |
| Configuration | python-dotenv | 1.0.0 |
Before installing SmartExpenseBot, ensure you have:
Ubuntu/Debian:
sudo apt-get update sudo apt-get install ffmpeg python3-pip python3-venv
macOS:
brew install ffmpeg python3
Windows:
git clone https://github.com/botirbakhtiyarov/SmartExpenseBot.git cd SmartExpenseBot
# Create virtual environment python3 -m venv venv # Activate virtual environment # On Linux/macOS: source venv/bin/activate # On Windows: venv\Scripts\activate
pip install --upgrade pip pip install -r requirements.txt
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:
# 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 ..
models/
├── vosk-model-uz/
│ ├── am/
│ ├── conf/
│ └── ...
├── vosk-model-ru/
│ └── ...
└── vosk-model-en/
└── ...
Create a .env file in the project root:
cp .env.example .env # If example exists # Or create manually touch .env
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
Test your configuration:
python bot.py
You should see:
If errors occur, check:
python bot.py
The bot will:
When a user first interacts with the bot:
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:
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]
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?"
"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"
Access settings via the ⚙️ Settings button:
Every day at 20
(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.
┌─────────────────┐
│ 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 │
└─────────┘ └─────────┘ └──────────┘ └──────────┘
The bot uses three specialized AI instances from DeepSeek:
User ├── id (PK) ├── telegram_id (Unique, Indexed) ├── name ├── language (default: 'en') ├── timezone (default: 'UTC') ├── currency (default: 'USD') ├── created_at ├── expenses (1-to-Many) └── reminders (1-to-Many) Expense ├── id (PK) ├── user_id (FK → User.id) ├── amount ├── currency ├── category ├── description ├── date (Indexed) └── created_at Reminder ├── id (PK) ├── user_id (FK → User.id) ├── message ├── reminder_time (Indexed) ├── created_at └── sent (0 or 1)
scoped_session for thread-local sessionsSmartExpenseBot/
│
├── handlers/ # Command handlers (MVC pattern)
│ ├── __init__.py
│ ├── expense_handler.py # Expense tracking logic
│ │ └── ExpenseHandler 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
│ └── AboutHandler class
│
├── ai_functions.py # DeepSeek AI integration
│ ├── deepseek_ai_expense() # Expense extraction
│ ├── deepseek_ai_expense_multiple() # Multiple expense extraction
│ ├── deepseek_ai_reminder() # Time parsing
│ ├── deepseek_ai_country() # Country detection
│ ├── deepseek_ai_report() # Report generation
│ └── _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
│ ├── 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
| 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 |
# 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]
# 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]
# 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)
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]]
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
from ai_functions import deepseek_ai_country timezone = deepseek_ai_country( country_text: str, lang: str = "en" ) -> Optional[str] # IANA timezone name
from ai_functions import deepseek_ai_report report = deepseek_ai_report( text: str, lang: str = "en", expenses_data: List[Expense] = None ) -> str # Natural language report
Symptoms: Bot doesn't respond to any messages
Diagnosis Steps:
ps aux | grep bot.py.env fileSolutions:
BOT_TOKEN is correct and activeSymptoms: Database-related errors in logs
Solutions:
For SQLite:
For PostgreSQL:
sudo systemctl status postgresqlpsql -h host -U user -d databaseSymptoms: Voice messages not transcribed
Diagnosis:
ffmpeg -versionSolutions:
sudo apt-get install ffmpeg (Ubuntu) or brew install ffmpeg (macOS)Symptoms: Expenses not categorized correctly or API errors
Solutions:
DEEPSEEK_API_KEY is valid and activeSymptoms: Reminders scheduled at wrong times or timezone not detected
Solutions:
timezonefinderL is installed: pip install timezonefinderLSymptoms: Errors when multiple users use bot simultaneously
Solutions:
Symptoms: Vosk models loading multiple times or memory errors
Solutions:
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' )
If issues persist:
We welcome contributions! Here's how you can help:
Fork the Repository
git clone https://github.com/botirbakhtiyarov/SmartExpenseBot.git
Create Feature Branch
git checkout -b feature/AmazingFeature
Make Changes
Commit Changes
git commit -m 'Add some AmazingFeature'
Push to Branch
git push origin feature/AmazingFeature
Open Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
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.
Botir Bakhtiyarov
This project uses the following excellent libraries and services: