Tutorial · Nov 19, 2026

Telegram bot product catalog in Python — inline buttons + categories (aiogram 3)

Categories → product list → product detail → add to cart. All with inline keyboards, zero webapp. One JSON file is your whole store. Code below runs end-to-end.

A shop bot's catalog is 70% of the UX. If it works the customer buys; if it's confusing they leave to WhatsApp. aiogram 3's InlineKeyboardMarkup + callback data gives you a clean three-screen pattern: categories, products in a category, and product detail with quantity + Add-to-cart. Code below.

The data — one JSON file per shop

For bots with <100 products, keep the catalog in products.json. Shop owner edits one file, redeploy (or hot-reload in admin command — see end).

// products.json
[
  { "id": "coffee-espresso", "name": "Espresso", "description": "Double shot, 60ml", "price": 3.50, "category": "coffee", "in_stock": true },
  { "id": "coffee-latte",    "name": "Vanilla Latte", "description": "Whole milk, 12oz", "price": 5.00, "category": "coffee", "in_stock": true },
  { "id": "pastry-croissant","name": "Butter Croissant", "description": "Flaky, baked this morning", "price": 3.25, "category": "pastry", "in_stock": true }
]

No server, no database, no admin panel. A single file version-controlled with your bot.

Catalog class with category helpers

# catalog.py
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from threading import Lock

@dataclass
class Product:
    id: str
    name: str
    description: str
    price: float
    category: str = "general"
    in_stock: bool = True

class ProductCatalog:
    def __init__(self, path: Path):
        self._path = path
        self._lock = Lock()
        self._products: dict[str, Product] = {}
        self.reload()

    def reload(self) -> None:
        raw = json.loads(self._path.read_text(encoding="utf-8"))
        with self._lock:
            self._products = {p["id"]: Product(**p) for p in raw}

    def all(self) -> list[Product]:
        with self._lock:
            return [p for p in self._products.values() if p.in_stock]

    def by_category(self, category: str) -> list[Product]:
        return [p for p in self.all() if p.category == category]

    def categories(self) -> list[str]:
        return sorted({p.category for p in self.all()})

    def get(self, pid: str) -> Product | None:
        with self._lock:
            return self._products.get(pid)

The three keyboards

# keyboards.py
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from catalog import Product

def categories_kb(categories: list[str]) -> InlineKeyboardMarkup:
    rows = [
        [InlineKeyboardButton(text=f"📂 {c.title()}", callback_data=f"cat:{c}")]
        for c in categories
    ]
    rows.append([InlineKeyboardButton(text="🛒 View cart", callback_data="cart:view")])
    return InlineKeyboardMarkup(inline_keyboard=rows)

def product_list_kb(products: list[Product], category: str) -> InlineKeyboardMarkup:
    rows = [
        [InlineKeyboardButton(text=f"{p.name} — ${p.price:.2f}", callback_data=f"prod:{p.id}")]
        for p in products
    ]
    rows.append([InlineKeyboardButton(text="◀️ Categories", callback_data="catalog")])
    return InlineKeyboardMarkup(inline_keyboard=rows)

def product_detail_kb(product: Product, qty_in_cart: int) -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text="➖", callback_data=f"qty:{product.id}:-1"),
            InlineKeyboardButton(text=f"In cart: {qty_in_cart}", callback_data="noop"),
            InlineKeyboardButton(text="➕", callback_data=f"qty:{product.id}:+1"),
        ],
        [InlineKeyboardButton(text="🛒 Add to cart", callback_data=f"add:{product.id}")],
        [InlineKeyboardButton(text="◀️ Back", callback_data=f"cat:{product.category}")],
    ])

Callback data format <verb>:<id>[:<arg>] — one handler can route every button with a single split(":").

Handlers — three screens, one router

# handlers/catalog.py
from aiogram import Router, F
from aiogram.filters import Command
from aiogram.types import CallbackQuery, Message

from catalog import ProductCatalog
from keyboards import categories_kb, product_list_kb, product_detail_kb
from html import escape

router = Router(name="catalog")

@router.message(Command("catalog"))
@router.message(F.text == "🛍 Catalog")
async def show_catalog(message: Message, catalog: ProductCatalog):
    cats = catalog.categories()
    if not cats:
        await message.answer("The catalog is empty right now.")
        return
    await message.answer("🛍 <b>Pick a category:</b>", reply_markup=categories_kb(cats))

@router.callback_query(F.data == "catalog")
async def cb_catalog(query: CallbackQuery, catalog: ProductCatalog):
    try:
        await query.message.edit_text(
            "🛍 <b>Pick a category:</b>",
            reply_markup=categories_kb(catalog.categories()),
        )
    except Exception:
        pass
    await query.answer()

@router.callback_query(F.data.startswith("cat:"))
async def cb_category(query: CallbackQuery, catalog: ProductCatalog):
    category = query.data.split(":", 1)[1]
    items = catalog.by_category(category)
    if not items:
        await query.answer("No products in this category", show_alert=True)
        return
    try:
        await query.message.edit_text(
            f"📂 <b>{escape(category.title())}</b> — {len(items)} item(s):",
            reply_markup=product_list_kb(items, category),
        )
    except Exception:
        pass
    await query.answer()

@router.callback_query(F.data.startswith("prod:"))
async def cb_product(query: CallbackQuery, catalog: ProductCatalog, carts):
    pid = query.data.split(":", 1)[1]
    product = catalog.get(pid)
    if not product:
        await query.answer("Product not found", show_alert=True)
        return
    in_cart = sum(1 for i in carts.get(query.from_user.id) if i.product_id == pid)
    text = (
        f"<b>{escape(product.name)}</b>\n"
        f"<i>{escape(product.category.title())}</i>\n\n"
        f"{escape(product.description)}\n\n"
        f"💵 <b>${product.price:.2f}</b>"
    )
    try:
        await query.message.edit_text(text, reply_markup=product_detail_kb(product, in_cart))
    except Exception:
        await query.message.answer(text, reply_markup=product_detail_kb(product, in_cart))
    await query.answer()

@router.callback_query(F.data == "noop")
async def cb_noop(q: CallbackQuery):
    await q.answer()

Four details that matter

  1. Always try/except around edit_text. Telegram raises TelegramBadRequest: message is not modified when the user taps the same button twice. Silent catch keeps the handler alive.
  2. Single callback_query handler per verb, not per button. F.data.startswith("cat:") handles every category tap. You never register "one handler per product."
  3. Escape user-ish data in HTML. Even catalog names are safer wrapped in escape(). One accidental < in a product name breaks parse.
  4. noop callback for display-only buttons. The "In cart: 3" button needs to answer the callback (Telegram shows a spinner otherwise), but do nothing. Send callback_data="noop" and a one-liner handler.

Admin hot-reload (no redeploy to change the catalog)

@router.message(Command("reload"))
async def cmd_reload(message: Message, admin_ids: list[int], catalog: ProductCatalog):
    if message.from_user.id not in admin_ids:
        return
    try:
        catalog.reload()
        await message.answer(f"✅ Reloaded. {len(catalog.all())} active product(s).")
    except Exception as e:
        await message.answer(f"❌ Reload failed: {e}")

Edit products.json (SSH in, or git push + auto-redeploy, or edit in Railway's Shell), then message /reload. Catalog refreshes in-process without dropping active sessions.

Scaling notes (if you grow)

A working reference

The code above is simplified from the open-source lite template — single file, 324 LOC, catalog + cart + checkout end-to-end. The full version splits it into 11 modules + adds admin notifications, Google Sheets logger, and Railway deploy.

Related

Want the whole shop bot?

Catalog + cart + checkout + admin + Sheets, in one Railway-deployable Python project. $9 (48h flash: $5 with LAUNCH5).

← Back to blog