Users Pricing

blog

Home Blogs Build a Telegram Bot in Python in Under an Hour – MindStick
Build a Telegram Bot in Python in Under an Hour

Build a Telegram Bot in Python in Under an Hour

Laura Larsen 43 19 Nov 2026

Telegram bots are one of the quickest ways to put a useful tool in front of people. Customers can check an order status. Your team can get server alerts. Field staff can submit a quick report. There’s no app to build, no app store approval, and the Bot API is free.

In this tutorial we’ll build a small order-status bot with the popular python-telegram-bot library, test it, and look at how to run it in production.

Step 1: Create the bot with BotFather

Every Telegram bot is registered through an official bot called @BotFather.

  1. Open Telegram and search for @BotFather (check for the blue verified tick).
  2. Send /newbot.
  3. Choose a display name, for example “MindStick Orders”.
  4. Choose a username ending in bot, such as mindstick_orders_bot.
  5. BotFather replies with a token that looks like 123456789:AA....

Treat the token like a password. Anyone with it can control your bot. Don’t commit it to Git or paste it in screenshots. If it leaks, use /revoke in BotFather to get a new one.

While you’re there, /setcommands lets you define the command menu users see:

start - Start the bot
status - Check an order, e.g. /status 1042
help - Show help

Step 2: Install the library

pip install python-telegram-bot

The library is fully asynchronous (it uses async/await) in its current versions. Older tutorials written for versions before 20 use a different, synchronous API, so be careful when copying examples from the web.

Step 3: The bot

"""A small Telegram bot: /start, /help, /status <order-id> and echo."""
import logging
import os

from telegram import Update
from telegram.ext import (Application, CommandHandler, ContextTypes,
                          MessageHandler, filters)

logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s",
                    level=logging.INFO)
logging.getLogger("httpx").setLevel(logging.WARNING)  # hide noisy request logs

TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]

# Stand-in for a real database or API lookup
ORDERS = {"1042": "Packed, ships today", "1043": "Delivered on 14 Jan"}


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    name = update.effective_user.first_name
    await update.message.reply_text(
        f"Hi {name}! I can check your order status.\n"
        "Try: /status 1042"
    )


async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("/status <order id> - check an order\n/help - this message")


async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not context.args:
        await update.message.reply_text("Please send the order ID, e.g. /status 1042")
        return
    order_id = context.args[0]
    result = ORDERS.get(order_id)
    if result:
        await update.message.reply_text(f"Order {order_id}: {result}")
    else:
        await update.message.reply_text(f"Sorry, I couldn't find order {order_id}.")


async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "I didn't understand that. Type /help to see what I can do."
    )


async def on_error(update: object, context: ContextTypes.DEFAULT_TYPE):
    logging.exception("Error while handling an update", exc_info=context.error)


def main():
    app = Application.builder().token(TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("help", help_cmd))
    app.add_handler(CommandHandler("status", status))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
    app.add_error_handler(on_error)
    app.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
    main()

Set the token as an environment variable and run it:

export TELEGRAM_BOT_TOKEN="123456789:AA..."     # PowerShell: $env:TELEGRAM_BOT_TOKEN="..."
python telegram_bot.py

Open your bot in Telegram, press Start, and try /status 1042.

How it works

Handlers

The bot is a list of handlers. Each one decides whether it’s interested in an incoming update and, if so, runs a function:

  • CommandHandler("status", status) runs status() when someone sends /status.
  • MessageHandler(filters.TEXT & ~filters.COMMAND, echo) catches any plain text that isn’t a command.

Handlers are checked in the order they were added, and the first match wins. That’s why the catch-all text handler goes last.

Command arguments

For /status 1042, the library splits the text after the command into context.args, so context.args[0] is "1042". Always check that arguments exist; users will send /status on its own.

Replies

await update.message.reply_text(...) sends a reply in the same chat. You can also send photos, documents, locations and buttons.

Errors

app.add_error_handler(on_error) logs any exception instead of letting it disappear silently. In production, send these logs to your monitoring system.

Polling

app.run_polling() repeatedly asks Telegram’s servers for new messages. It’s the simplest way to run a bot: no public URL, no HTTPS certificate, works behind a firewall, and it’s perfect for development and many small bots.

Testing handlers without Telegram

Because each handler is just an async function, you can test it with mock objects:

import asyncio
from unittest.mock import AsyncMock, MagicMock
import telegram_bot as bot

async def check(args):
    update = MagicMock()
    update.message.reply_text = AsyncMock()
    context = MagicMock()
    context.args = args
    await bot.status(update, context)
    return update.message.reply_text.call_args[0][0]

print(asyncio.run(check(["1042"])))  # Order 1042: Packed, ships today
print(asyncio.run(check(["9"])))     # Sorry, I couldn't find order 9.
print(asyncio.run(check([])))        # Please send the order ID, e.g. /status 1042

We ran exactly these three checks, and they returned the expected replies. Set TELEGRAM_BOT_TOKEN to any dummy value before importing, because the module reads it at import time.

Adding buttons

Inline keyboards make bots much easier to use than typing commands:

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler

async def menu(update, context):
    keyboard = [
        [InlineKeyboardButton("Track order", callback_data="track")],
        [InlineKeyboardButton("Talk to support", callback_data="support")],
    ]
    await update.message.reply_text("What would you like to do?",
                                    reply_markup=InlineKeyboardMarkup(keyboard))

async def on_button(update, context):
    query = update.callback_query
    await query.answer()  # stops the loading spinner on the button
    if query.data == "track":
        await query.edit_message_text("Send /status followed by your order ID.")
    else:
        await query.edit_message_text("Our team will contact you shortly.")

# in main():
# app.add_handler(CommandHandler("menu", menu))
# app.add_handler(CallbackQueryHandler(on_button))

Connecting to real data

Replace the ORDERS dictionary with a real lookup: a database query, a call to your own REST API, or a call to your ERP. Keep two things in mind:

  • Use async-friendly libraries (for example httpx.AsyncClient, or async database drivers), or run blocking calls in a thread with asyncio.to_thread, so one slow lookup doesn’t freeze the bot.
  • Verify identity before sharing private data. Anyone can message your bot. For order details, ask for something only the customer knows (like a registered phone number linked through Telegram’s contact-sharing button), or send a one-time code.

Sending messages proactively

Bots can message users who have started a chat with them, for example to send alerts. Save each user’s chat_id when they press Start, then:

await context.bot.send_message(chat_id=saved_chat_id, text="Your order has shipped!")

Bots can’t message people who haven’t started a chat with them first. That’s a Telegram rule to prevent spam. Also respect Telegram’s rate limits: send bulk messages gradually, not all at once.

Running it in production

Option 1: Polling on a server. Run the script as a service on a small Linux VM (with systemd) or a Windows server (with NSSM or a scheduled task at startup). Simple and reliable for most bots.

Option 2: Webhooks. Telegram sends each update to your HTTPS URL as it arrives. This suits serverless platforms and high-traffic bots. python-telegram-bot supports it with app.run_webhook(...), or you can receive updates in your own FastAPI app and pass them to the application. You’ll need a public HTTPS endpoint with a valid certificate, and you should set a secret token so only Telegram can call it.

Either way:

  • keep the token in environment variables or a secret store
  • log errors and restart automatically if the process crashes
  • run only one polling instance per bot, since two instances will compete for updates

Ideas for business bots

  • order and delivery status for customers
  • appointment reminders and confirmations
  • server, website and payment alerts for the IT team
  • daily sales summaries for managers
  • attendance or visit reports from field staff
  • FAQ answers, combined with a document Q&A system

You’re done

In well under an hour you’ve built a Telegram bot that responds to commands, looks up data, handles errors and can be tested without Telegram. From here, add buttons, connect it to your real systems, and choose polling or webhooks for deployment.

Start with one small job your team or customers do repeatedly, and let the bot handle it.


Laura Larsen

Software Developer at Netcompany

Working as Software Developer with Netcompany in Odense. I have 2 years of experience in backend development and cloud platforms. I graduated from the University of Southern Denmark with a BSc in Computer Science and completed an MSc in Computer Science at the same university. In my free time I like baking and winter swimming.


Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md