This guide shows you how to build a Telegram bot that calculates each person’s share of a dinner bill, including tax and tip, and sends the result directly in the chat. You’ll need a Telegram account and basic familiarity with Python—no web hosting or credit card required. By the end, you’ll have a working bot that turns a group of itemized costs into clear, fair amounts for everyone.
What You’ll Need
- A Telegram account (free) and the Telegram app on your phone or desktop.
- Python 3.7 or newer installed on your computer.
- A code editor (like VS Code, PyCharm, or even Notepad).
- An internet connection for installing packages and running the bot.
Step-by-Step
- Create a bot on Telegram. Open Telegram, search for BotFather (the official bot that creates bots). Start a chat and send
/newbot. Follow the prompts to choose a name (e.g., “Bill Splitter”) and a username (must end inbot, likedinner_splitter_bot). After that, BotFather will give you a token—a long string like123456:ABC-DEF.... Copy and save it securely; it’s your bot’s password. - Set up your Python environment. Create a new folder on your computer for the bot. Open a terminal in that folder and run
pip install python-telegram-bot(orpip3on some systems). This library lets your Python code talk to Telegram’s API. - Write the bot script. Create a file named
bot.pyin that folder. Start with the basic skeleton: - Add the bill-splitting logic. You’ll need a function that parses the user’s message, extracts the amounts, and calculates the split. For a simple version, assume the user sends a list of item prices (e.g., appetizers, mains, drinks) and the bot splits the total equally among a number of people. Replace the
starthandler with a message handler that does this: - Handle the number of people. Add a command
/splitthat takes the number of people as an argument. It calculates the per-person amount, including a default tip and tax (you can make these adjustable later). Here’s the code: - Register the new handlers. In the
main()function, addapp.add_handler(CommandHandler("split", split))andapp.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, split_bill)). - Run the bot. In your terminal, run
python bot.py. If everything is set up, you’ll see a message like “Application started”. Now open Telegram, find your bot by its username, and pressStart. Send a message like12.50 8.00 15.75, then type/split 3to see the split. - Test with a real scenario. Go out to dinner with friends, collect the itemized amounts, and send them to your bot. Adjust the tax and tip rates in the code to match your local rates if needed.
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
TOKEN = "YOUR_TOKEN_HERE"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hi! Send me a list of amounts like: 12.50 8.00 15.75")
def main():
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.run_polling()
if __name__ == "__main__":
main()
async def split_bill(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = update.message.text
amounts = []
for word in text.split():
try:
amounts.append(float(word))
except ValueError:
pass
if not amounts:
await update.message.reply_text("Please send numbers like: 10 20 30")
return
total = sum(amounts)
# Ask for number of people (simple approach: use /split command with count)
await update.message.reply_text(f"Total: ${total:.2f}. Use /split <number> to divide.")
context.user_data['amounts'] = amounts
async def split(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not context.args:
await update.message.reply_text("Usage: /split 4")
return
try:
num_people = int(context.args[0])
except ValueError:
await update.message.reply_text("Please provide a number.")
return
amounts = context.user_data.get('amounts', [])
if not amounts:
await update.message.reply_text("First send the item amounts.")
return
total = sum(amounts)
tax_rate = 0.08 # 8% default
tip_rate = 0.15 # 15% default
total_with_tax = total * (1 + tax_rate)
total_with_tip = total_with_tax * (1 + tip_rate)
per_person = total_with_tip / num_people
await update.message.reply_text(
f"Total: ${total:.2f}\nTax (8%): ${total*tax_rate:.2f}\nTip (15%): ${total_with_tax*tip_rate:.2f}\n"
f"Grand total: ${total_with_tip:.2f}\nPer person ({num_people}): ${per_person:.2f}"
)
Common Mistakes
- Forgetting to save the token securely. If you share your code publicly, your token will be exposed and anyone can control your bot. Keep it in a separate file or environment variable.
- Not handling non-numeric input. If the user sends letters or symbols, your bot might crash. Always use try/except blocks as shown.
- Mixing up tax and tip order. Some people apply tip on the pre-tax amount, others on post-tax. Decide which is correct for your group and be consistent.
- Assuming everyone pays equally. If someone had no appetizer or skipped drinks, an equal split isn’t fair. Consider adding item-level splitting later.
- Using the wrong Python library version. The
python-telegram-botlibrary has changed significantly over versions. The code above works with version 20.x (the current stable). If you’re using an older version, the syntax will differ.
Tips
- Make tax and tip adjustable. Add commands like
/tax 0.10and/tip 0.20so you can change them without editing code. - Store the amounts per chat. Use
context.chat_datainstead ofuser_dataif you want the bot to handle multiple groups in the same chat. - Add a currency symbol. If you’re not in the US, replace
$with your local currency symbol or use a generic “units”. - Round to 2 decimals. Always format with
.2fto avoid long floating-point numbers like12.300000000001. - Deploy for free. Once your bot works locally, you can deploy it to a free cloud service like Render or PythonAnywhere so it runs 24/7 without your computer being on.
Troubleshooting
- Bot doesn’t respond. Check that your token is correct and that you ran the script without errors. Look at the terminal for any error messages. Also make sure you started a chat with your bot by pressing the Start button.
- “Module not found” error. This means
python-telegram-botisn’t installed. Runpip install python-telegram-botagain, and ensure you’re using the same Python environment (e.g., a virtual environment). - Bot responds but ignores commands. Ensure you’ve added the handlers in
main()beforeapp.run_polling(). Also check that your message handler doesn’t interfere with commands—use~filters.COMMANDas shown. - Numbers are not parsed correctly. If the user sends amounts with commas (e.g., “12,50”), replace commas with periods before converting to float. Add
text = text.replace(',', '.')at the start of the parsing function. - Bot works locally but not after deployment. On cloud services, you need to set the token as an environment variable and ensure the port is configured correctly. Often it’s simpler to use a webhook instead of polling, but polling works on most free tiers.
- Per-person amount is too high or low. Double-check your tax and tip rates. Also verify that you’re dividing by the correct number of people—maybe someone left early or a guest was added.
Frequently Asked Questions
- Can I use this bot without knowing Python? Yes, if you follow the steps exactly and copy the code. But to customize it, you’ll need to learn basic Python. Alternatively, you can use a no-code bot builder like ManyBot, but they have limitations.
- How do I add more features like itemized splitting? You can extend the bot to accept input like “pizza 12.50, salad 8.00” and assign each item to a person. This requires more complex parsing and data storage, but it’s doable with dictionaries in Python.
- Is my bot private? Only people who know your bot’s username can find it, but anyone who finds it can use it. If you want to restrict access, you can add a password or whitelist user IDs.
- Can I run the bot on my phone? Not directly, because Python scripts need a computer or server. But you can deploy it on a cloud service and access it from your phone via Telegram.
- What if my group has uneven splits (e.g., one person pays for the whole bottle)? The simple version splits equally. For uneven splits, you’d need to modify the bot to accept per-person amounts or a custom weight for each person.
- Does the bot work with multiple groups? Yes, if you use
chat_datainstead ofuser_data, the bot can keep separate amounts for each chat. Each group will have its own context.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Fix OEM Activation Error 0xc004c060 in Windows 10
- Why Does My App Run One Query for the List and One per Item?
- Fix Google Chrome Has Stopped Working
- Fix Apps Not Downloading From Play Store
- Secure a Samsung Galaxy After a Zero-Day Disclosure
- What to Check Before Installing Linux Alongside Windows