Telegram bot admin notifications in Python — the full aiogram 3 pattern
How to send a Telegram DM to the shop owner every time an order lands, with inline Accept / Shipped / Delivered buttons and proper failure handling. Not the "send_message(ADMIN_ID, text)" one-liner — the version that survives a blocked admin.
Every e-commerce Telegram bot has the same requirement: when a customer places an order, ping the shop owner immediately so they can confirm, arrange delivery, update status. The tutorial version is three lines. The production version — multi-admin, action buttons, retry on failure, status update back to customer — is what you actually ship.
The naive version (don't ship this)
await bot.send_message(ADMIN_ID, f"New order: {order}")
Problems:
- Single admin. In reality a shop has 2-5 people who need to see orders.
- No action buttons — admin has to type status manually, often back in another chat.
- If the admin blocked the bot or the API fails, your handler crashes mid-checkout.
- Customer never learns their order is accepted / shipped / delivered.
Config: a list of admin IDs, not one constant
Start by loading admin IDs from env as a comma-separated list. Easier to add/remove without redeploy.
# config.py
from dataclasses import dataclass, field
import os
def _int_list(raw: str) -> list[int]:
if not raw:
return []
return [int(x.strip()) for x in raw.split(",") if x.strip()]
@dataclass(frozen=True)
class Settings:
admin_ids: list[int] = field(default_factory=list)
def load_settings() -> Settings:
return Settings(admin_ids=_int_list(os.getenv("ADMIN_IDS", "")))
Env: ADMIN_IDS=111111111,222222222,333333333. Get your own ID from @userinfobot on Telegram.
Inline action keyboard the admin sees
Rather than making the admin type /accept 00042, give them inline buttons that update the order status in one tap.
# keyboards.py
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
def admin_order_actions(order_id: str) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup(inline_keyboard=[
[
InlineKeyboardButton(text="✅ Accept", callback_data=f"ord:{order_id}:accepted"),
InlineKeyboardButton(text="🚚 Shipped", callback_data=f"ord:{order_id}:shipped"),
],
[
InlineKeyboardButton(text="🎉 Delivered", callback_data=f"ord:{order_id}:delivered"),
InlineKeyboardButton(text="❌ Reject", callback_data=f"ord:{order_id}:rejected"),
],
])
The callback_data format ord:<id>:<status> is parsed by a single handler — no regex, no routing table.
The notification function — loop, swallow, log
Send to every admin, catch exceptions individually, never let one failure block the others or crash the checkout handler.
# handlers/checkout.py (end of confirm handler)
import logging
from html import escape
logger = logging.getLogger(__name__)
admin_text = (
f"🔔 <b>New order #{order.id}</b>\n\n"
f"{summary}\n\n"
f"💵 <b>Total: ${order.total:.2f}</b>\n\n"
f"👤 {escape(order.name)}\n"
f"📞 {escape(order.phone)}\n"
f"📍 {escape(order.address)}\n"
)
tg_user = f"@{escape(order.username)}" if order.username else f"id:{order.user_id}"
admin_text += f"\nCustomer: {tg_user}"
for aid in admin_ids:
try:
await bot.send_message(
aid,
admin_text,
reply_markup=admin_order_actions(order.id),
)
except Exception as e:
logger.warning("admin notify failed for %s: %s", aid, e)
Three details that matter:
escape()every user-supplied field. A customer named<script>will break HTML parse mode without escape.try/exceptper admin. One admin blocking the bot must not prevent the other admins from being notified.- Log, don't re-raise. If all admins failed, the customer still gets their "Order received" message — payment recovery is a separate concern from notification delivery.
Handling the admin's button taps
# handlers/admin.py
from aiogram import Router, F, Bot
from aiogram.types import CallbackQuery
router = Router(name="admin")
STATUS_LABELS = {
"accepted": "✅ Accepted",
"shipped": "🚚 Shipped",
"delivered": "🎉 Delivered",
"rejected": "❌ Rejected",
}
@router.callback_query(F.data.startswith("ord:"))
async def cb_order_status(
query: CallbackQuery,
bot: Bot,
admin_ids: list[int],
orders, # your OrderStore, injected by middleware
):
if query.from_user.id not in admin_ids:
await query.answer("Not authorized", show_alert=True)
return
_, oid, status = query.data.split(":")
if status not in STATUS_LABELS:
await query.answer("Unknown status", show_alert=True)
return
ok = orders.set_status(oid, status)
if not ok:
await query.answer("Order not found", show_alert=True)
return
order = orders.get(oid)
await query.answer(f"Updated → {status}")
# Edit the original admin message to show status
try:
new_text = (query.message.text or "") + f"\n\n<b>Status: {STATUS_LABELS[status]}</b>"
await query.message.edit_text(new_text, reply_markup=None)
except Exception:
pass
# Notify the customer
if order:
try:
await bot.send_message(
order.user_id,
f"🔔 Your order <b>#{order.id}</b> is now: {STATUS_LABELS[status]}",
)
except Exception as e:
logger.warning("notify customer %s failed: %s", order.user_id, e)
Four gotchas that bite in week 2
- Edit-and-notify race. If you
edit_textthe admin message ANDsend_messagethe customer in the same handler withouttry/except, one API failure tanks both. Wrap each in its owntry/except. - Blocked admin. Telegram returns
Forbidden: bot was blocked by the user. Your retry loop (if any) should back off immediately — this is a permanent condition. Consider logging + flagging the admin in your DB. - Rate limits on broadcast. If you ever
for uid in all_customers: await bot.send_message(...)for a broadcast, sleep 50ms between sends. Telegram's bulk limit is ~30 msg/second to different users; blow through it and you'll getFlood control exceeded. Retry in N seconds. - Markdown vs HTML parse mode. HTML is easier for user-supplied content because
escape()is well-defined. Markdown needs careful escape of_*[]()~`>#+-=|{}.!— one unescaped underscore in a user's name breaks the whole message.
A working reference
The full admin notification pattern — multi-admin, inline actions, customer status updates, logging middleware — ships in the open-source lite template on GitHub (handlers/checkout.py + handlers/admin.py). The paid full version adds a broadcast command with throttling and admin command gates (/orders_recent, /stats).
Related
- aiogram 3 FSM checkout example — the handler that fires right before this notification pattern.
- Logging Telegram bot orders to Google Sheets — same confirm handler, different sink.
- aiogram 3 vs python-telegram-bot — why aiogram's middleware DI makes patterns like this cleaner.
Want the whole order bot?
Catalog + cart + FSM checkout + admin alerts + Google Sheets. $9 (48h flash: $5 with LAUNCH5).