(ex)SpenserBot is a Telegram bot that extracts structured expense data from receipt photos and free-text messages using LLM-powered extraction.
- Receipt photo extraction: Send a photo of a receipt — the bot extracts amount, currency, merchant, date, and optional category
- Free-text expense logging: Type "lunch 15.50 eur at Mario's Pizzeria on 2026-07-10" and it's saved automatically
- Correction loop: If the LLM can't extract all required fields, the bot asks for missing info. You can refine up to 3 times before manual intervention is suggested
- Monthly CSV reports:
/reportgenerates a CSV with all your expenses for the current month - User isolation: Each Telegram user sees only their own expenses
- User authorization whitelist: Only Telegram user IDs listed in a JSON config file can interact with the bot; unauthorized attempts are silently ignored and written to
unauthorized.log
- Python 3.12+ (uses
X | Yunions, PEP 695 generics) - uv — package manager and tool runner (install guide)
- Telegram Bot Token — create a bot via @BotFather on Telegram
- LLM API access — any OpenAI-compatible endpoint (see Configuration)
# Clone and install
git clone <repo-url>
cd expense-report-bot
uv sync
# Install pre-commit hooks (gitleaks secret scanning)
uv run pre-commit install
# Set up environment
cp .env.example .env
# Edit .env with your actual credentialsCreate a .env file (or export the variables directly):
# Required
TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
LLM_BASE_URL=https://api.openai.com/v1 # or your own LLM endpoint
LLM_API_KEY=sk-...
LLM_MODEL=gpt-4o # or any model your endpoint supports
# Optional
EXPENSE_DB_PATH=expenses.db # defaults to expenses.db
# Authorization
AUTHORIZED_USERS_CONFIG_PATH=authorized-users.json # JSON whitelist of Telegram user IDs
UNAUTHORIZED_LOG_PATH=unauthorized.log # optional; defaults beside EXPENSE_DB_PATHCreate a whitelist JSON file before using the bot:
{
"authorized_users": ["123456789"]
}Values must be numeric strings. Telegram user IDs that are not listed are silently ignored. Each unauthorized attempt appends one line to the dedicated audit file:
2026-07-19T12:00:00Z user_id=987654321
Failure behavior:
- Missing
AUTHORIZED_USERS_CONFIG_PATH, missing whitelist file, or unreadable whitelist file: the bot starts with no authorized users and logs a warning. - Malformed JSON: startup fails.
- Valid JSON with invalid schema: the bot starts with no authorized users and logs a warning.
- Unwritable unauthorized audit log: startup fails.
uv run expense-botThe bot starts polling Telegram for messages. Send it:
- A receipt photo — it extracts expense data and confirms with you
- Free-form text like
"taxi 25 usd transport"— parsed and saved /report— generates a CSV of current month's expenses/start— welcome message with usage instructions
# From an image
uv run expense-extract --user-id 123 --db test.db extract-from-image receipt.jpg
# From free text
uv run expense-extract extract-from-text "lunch 15.50 eur at Mario's Pizzeria on 2026-07-10"Schema ownership belongs to Liquibase (ADR 0013). The changelog is
db/changelog/db.changelog.xml; applied changesets are recorded in
databasechangelog. Add future schema changes as new changesets rather than
editing existing ones.
To run liquibase or expense-extract by hand, put the project wrapper on your
PATH — it runs the official Liquibase 4.33.0 Docker image, which bundles the
SQLite JDBC driver, so no CLI install and no driver jars are required:
export PATH="$PWD/scripts:$PATH"The test suite does not need that PATH export: it resolves the wrapper by
absolute path, and uv run pytest runs only the hermetic unit tests — add
-o addopts="" to include the Liquibase-dependent integration tests (ADR 0014).
The Docker entrypoint and expense-extract run liquibase update before
opening SQLite.
For instructions on deploying the bot using Docker Compose, see Docker Deployment Guide.
# Hermetic unit tests (no Docker) — the default profile
uv run pytest
# Full suite: unit + integration (needs Docker + liquibase/liquibase:4.33.0)
uv run pytest -o addopts=""
# Integration tests only
uv run pytest -o addopts="" -m integration
# BDD acceptance tests (Behave; needs Docker)
uv run behavePre-commit runs gitleaks on every commit to block accidental secret leaks.
uv run pre-commit install # one-time setup
uv run pre-commit run --all-files # test it on the whole repoConfiguration: .pre-commit-config.yaml (framework), .gitleaks.toml (allowlist).
uv run ruff format # code formatting
uv run ruff check # linting
uv run ty check # type checking
uv run pytest -o addopts="" # full test suite (unit + integration)
uv run behave # BDD scenariosThe project follows a hexagonal (ports & adapters) architecture:
src/expense_report/
├── domain/ # Entities, value objects, domain services
│ ├── models.py # Expense, ExtractionResult (frozen dataclasses)
│ ├── correction_state.py # PendingCorrection, CorrectionStore
│ └── csv_generator.py # Monthly expense CSV generation
├── ports/ # Interface definitions (Protocols/ABCs)
│ ├── extraction.py # ExtractionPort (extract + refine)
│ └── repository.py # ExpenseRepositoryPort (save, get, query)
└── adapters/
├── inbound/ # Driving adapters (entry points)
│ ├── main.py # Telegram bot (python-telegram-bot)
│ ├── telegram_bot.py # Bot handlers
│ └── cli_extraction.py # CLI extraction commands
└── out/ # Driven adapters (external services)
├── dspy_extraction.py # LLM extraction via dSPy
└── sqlite_repository.py # SQLite persistence
- Domain has zero framework/IO imports — frozen dataclasses only
- dSPy backend: Uses
ChainOfThoughtwith anExpenseSignaturefor structured LLM output - SQLite: Zero-config persistence,
Decimalvalues stored as strings for precision - Correction loop: Up to 3 refinement attempts via the same
ExtractionPort.refineinterface - See
docs/adr/for full Architecture Decision Records
MIT
