Skip to content

About

Telegram bot for LLM-powered expense tracking. Whole bunch of features coming up in the pipeline.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation


Logo

Expense Tracking Telegram Bot

A Telegram bot for LLM-powered expense tracking.
Report Bug · Request Feature

Table of Contents
  1. About The Project
  2. Project Directory
  3. Getting Started
  4. Usage
  5. Personal Thoughts
  6. Contributing
  7. License
  8. Acknowledgments

About The Project

Expense Tracking

Expense tracking is something that we all know we should be doing, but unfortunately not enough of us are. The benefits of tracking one's daily expenses are evident – for financial planning and literacy, as well as the cultivation of responsible spending habits.

While I have been recording my expenses on a daily basis for the past 6 years, I must admit that it required a lot of discipline and it was definitely not easy to keep at it consistently, especially at the start. Tracking one's expenses sounds easy, but can actually be a time-consuming process that may require a fair bit of cognitive load to calculate and enter each expense correctly.

Therefore, I created this Telegram bot as a personal project to further automate the process of expense tracking, and to hopefully alleviate some of the pain of doing so.

Why a Telegram Bot?

The obvious idea would be a standalone app, but for reasons mentioned above, plus the fact that there are already many professionally created apps out there, I doubt I'd be able to value-add much in that space.

Telegram is a versatile messaging app that's ubiquitous among my social circle (and indeed, many Singaporeans out there). Thus, instead of yet another nameless app that I'm not going to remember using, why not leverage a platform that I use most frequently? Since we already have a deeply-ingrained habit of using Telegram on a daily – sometimes hourly – basis, I want to use this to leapfrog some of the inertia.

On a side note, Telegram, being largely open-source, has well-established developer tools which alleviates the burden of frontend development and allows me to focus wholly on functionality, so that's a big W :D

How is this different from a regular app?

Typical expense tracking apps require one to manually insert expense details into specified fields (e.g. amount spent, category, etc.), thereby placing the mental load on the user... just not very smart in general.

Thus, I designed this bot to act as a smart "assistant" – the user just needs to enter their expense in plain text, and the relevant details will be parsed automatically. This is possible due to the semantic understanding and natural language inference capabilities of LLMs (for example: gemini-3.1-flash-lite-preview). Therefore, by leveraging LLMs, the previously difficult task of creating a versatile expense tracking assistant has now become much easier.



Screenshot of an expense recording instance. The model is able to parse the category correctly, although it is possible to make changes if need be (for example, if you want Supermarket as a category instead of Groceries).

Agentic Workflow

The key feature of my bot is the ability for a user to leverage an AI agent for dynamic querying of their expenses, enabling smarter insights and even useful advice to improve one's spending habits.

To do so, I utilised LangGraph to create an agentic workflow for this analytics task. My LLM of choice for this agent is gpt-5.4-mini due to general performance, latency, and costs relative to other options out there. The agent uses a ReAct-style architecture with a single analyst node that can call tools (SQL queries) in a loop until it has enough data to answer.


graph TD
    start_node([Start]) --> analyst

    analyst["Analyst (decide, query, or answer)"]
    analyst -->|needs data| tools["Execute SQL query"]
    analyst -->|answer ready| end_node([End])

    tools --> analyst
Loading

Upon receiving a query from the user, the analyst decides if the question warrants querying of the expenses database. If the question can be answered without expense data (general questions, greetings), the agent submits a final answer directly.

Example: {'user_query': 'Please give me some general tips on managing spending habits.'}

If the query requires expense data, the analyst generates and self-checks a SQL query, executes it via db_query_tool, and loops back to evaluate the results. It can make multiple queries to gather all needed data before formulating its final answer.

Example: {'user_query': 'Please summarize my expenditure for this month.'}

... What's Next?

While I've successfully built the bot's basic functions and it works as it should, it's far from perfect. There's no real end goal to this pet project of mine, and I fully intend to keep iterating and adding features/ QoL improvements to enhance the process as a whole.

Some features in the pipeline include:

  • Expanding capabilities of the expense analyser agent (mainly viz generation).
  • Automatically generating a detailed monthly expense report with visualisations (graphs, charts, etc.) included.
  • Expanding beyond purely expense (outflow) tracking – as I've started a full-time job, measuring outflow against income matters just as much. The idea is to parse monthly payslips to track income (gross, take-home, etc.), thereby creating a more comprehensive personal finances tracker.

Stay tuned for more updates! 🎯

Built With

  • Docker
  • FastAPI
  • Google Cloud
  • Google Gemini
  • LangGraph
  • OpenAI
  • PostgreSQL
  • Python
  • Telegram bot API

(back to top)

Project Directory

expense-tracker-tele-bot/
│── main.py                  # Main script
│── config.py                # Config settings
│── database.py              # Database connection and ORM classes
│── utils.py                 # Miscellaneous util functions
│── handlers/                # Folder containing bot handler functions
│   ├── __init__.py
│   ├── misc_handlers.py
│   ├── expenses_handler.py
│   └── export.py
│── services/                # Folder containing key service functions
│   ├── __init__.py          # (e.g. for LLM integration)
│   ├── gemini_svc.py
│   ├── expenses_svc.py
│   ├── sql_agent_svc.py
│   └── whitelist_svc.py
│── deploy.ps1               # PowerShell deployment script
│── requirements.txt         # Dependencies
│── Dockerfile               # For deployment
│── .dockerignore
│── .gitignore
│── images/                  # Folder containing demo screenshots
│── LICENSE                  # MIT license file
│── CHANGELOG.md             # Documentation of changes made to bot
└── README.md                # Project description

(back to top)

Getting Started

To try this bot for yourself, follow these steps. Note: this assumes you want to deploy this using Google Cloud infrastructure. For local deployments, you'll be able to skip quite a few of these steps.

Prerequisites

  • Python 3.11+
  • Supabase account (PostgreSQL)
    • Get started with Supabase here.
    • You may explore other SQL database platforms (e.g. self-hosted via Raspberry Pi, other providers, etc.). As long as SQLAlchemy is still used to access the database, the only file to be changed should be database.py.
  • Google Cloud Project with billing enabled
    • To get started with Google Cloud Projects, this is a good starting point.
  • Google Cloud Secret Manager for storage of secret variables (in prod)
  • Google Gemini API key (used via the google-genai SDK)
  • Telegram Bot API Token
    • This is a comprehensive introduction to using Telegram bots.
  • OpenAI API key (for the expense analysis agent)
  • Docker (for deployment)
  • LangSmith tracing (optional)

Installation


1. Clone this repo

git clone https://github.com/crong12/expense-tracker-tele-bot.git

2. Set up environment variables

Create a .env file in the project root with the following variables:

TELE_BOT_TOKEN=your-telegram-bot-token
GCP_PROJECT_ID=your-gcp-project-id
REGION=your-gcp-region
REGION2=your-cloud-sql-region
DB_USER=your-db-user
DB_PASSWORD=your-db-password
DB_NAME=your-db-name
DB_HOST=your-db-host
DB_PORT=5432
OPENAI_API_KEY=your-openai-api-key
LANGSMITH_API_KEY=your-langsmith-api-key        # optional
LANGSMITH_PROJECT=your-langsmith-project-name    # optional
LANGSMITH_TRACING=true                           # optional
LANGSMITH_ENDPOINT=https://api.smith.langchain.com  # optional

For production deployment, secrets are retrieved from Google Cloud Secret Manager instead (see config.py). You can create them via the CLI or browser console:

gcloud secrets create SECRET_NAME --replication-policy="automatic"
gcloud secrets versions add SECRET_NAME --data-file=<(echo "secret-value")

3. Enable necessary Google Cloud APIs

gcloud services enable run.googleapis.com \
 cloudbuild.googleapis.com \
 secretmanager.googleapis.com

4. Build and deploy bot to Google Cloud Run

A deploy.ps1 PowerShell script is provided that automates the build, push, and deploy steps. It reads from your .env file:

./deploy.ps1

Alternatively, you can deploy manually:

# Authenticate Docker with Google Cloud
gcloud auth configure-docker your-region-docker.pkg.dev

# Build and push Docker image
docker build -t your-region-docker.pkg.dev/your-project-id/your-repo/image-name .
docker push your-region-docker.pkg.dev/your-project-id/your-repo/image-name

# Deploy to Cloud Run
gcloud run deploy service-name \
 --image=your-region-docker.pkg.dev/your-project-id/your-repo/image-name \
 --region your-region \
 --platform=managed \
 --allow-unauthenticated \
 --timeout=600

5. Set up webhook

curl -X POST "https://api.telegram.org/bot<your-bot-token>/setWebhook?url=<your-cloud-run-url>"

6. Change git remote url to avoid accidental pushes to base project

git remote set-url origin github_username/repo_name
git remote -v

(back to top)

Usage

1️⃣ Start the Bot

Send /start to initialize the bot and open the main menu.

2️⃣ Add an Expense

Click 📌 Insert Expense, then either type an expense in plain text (e.g., "Spent $10 on coffee at Starbucks yesterday"), or send an image (e.g., a picture of a receipt).

The bot will extract the following details:

  • Currency
  • Amount
  • Category
  • Description
  • Date


Gif of an expense recording instance with multimodal input. Using gemini-3.1-flash-lite-preview's multimodal capabilities, expenses can easily be parsed from images such as receipts, further easing the expense adding process.

3️⃣ Edit Expense Details

Click 🔧 Edit Expense and reply to a message from the bot with the relevant expense details, stating the edits to be made.


Screenshot of an expense editing instance. The bot is able to find the exact expense in the database using the expense_id associated with every saved expense.

4️⃣ Delete Expenses

Click 🗑️ Delete Expenses and either reply to a message from the bot with the relevant expense details, or tell the bot to delete all expenses.

5️⃣ Analyse Expenses

Click 🔍 Analyse Expenses and ask the bot something about your expenses.


Probably the best feature! Users can simply ask the bot for anything, from a concise overview of their expenditure, to insights into their spending habits, to money-saving tips and tricks.

6️⃣ Export Expenses

Click 📊 Export Expenses to receive a CSV containing this month's expenses, all recorded expenses, or an inclusive custom date range selected from an in-chat calendar.

7️⃣ Quit the Bot

Click ❌ Quit or type /quit at any point in the conversation to exit.

(back to top)

Personal Thoughts

This is a project of many firsts. It's my first time doing dev stuff, working with LLMs, agents, deployment, the cloud, and even async programming. Despite the minimal front-end workload in terms of UI development, having to learn the Telegram Bot API framework from scratch more than made up for it, in my opinion.

It has been a great experience stepping out of my comfort zone, and I relished the challenge of learning so many new tools and frameworks to get this thing to work. As this is a project that I have personal stake in (as I will actually be using this to track my daily expenses), I'm extremely motivated to give it my best shot, and to make a product worth using.

I know it's not perfect – there are definitely loads of things I can improve. However, I do think it's exciting having an imperfect product with room to grow. I'll definitely keep thinking of ways to improve this bot, and by doing so, improve myself as well. 💪

(back to top)

Contributing

As this is my first foray into working with LLMs and dev work, any contributions are greatly appreciated.

See TESTING.md for the local test commands, PostgreSQL setup, markers, and network-isolation policy.

If you have a suggestion to improve the bot, be it functionality or even best practice advice, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".

  1. Fork the repo
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Caveat: I am going to be extremely busy with my 9-5, so unfortunately new features in the pipeline may not materialise anytime soon. I do love working on this project (as I'm using it on a daily basis), and will definitely work on implementing new features whenever I can.

Also, while my bot is currently up and running, testing will only be open to a bunch of close friends as the cost of running this bot is entirely out of pocket 😔 However, I implore you to set the bot up for yourself (first-time Google Cloud users get a bunch of free credits anyway) and give it a try! 🚀

(back to top)

License

Distributed under the MIT license.

(back to top)

Acknowledgments

  • My friends and loved ones for testing my bot and providing invaluable feedback.

  • Huge thanks to this repo for the amazing README template.

  • The 🤗 HuggingFace agents course for being a great resource to get started with agents! If anyone's reading this, I highly recommend the course.

  • Google and ChatGPT (2026 edit: and now Claude Code) for being the best teachers out there, without whom this project would've taken much, much longer to build.

(back to top)

About

Telegram bot for LLM-powered expense tracking. Whole bunch of features coming up in the pipeline.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages