Introduction
Customer support is the backbone of any digital service, yet it remains one of the most resource-intensive operations for businesses of all sizes. By mid-2026, the landscape has shifted dramatically: users expect instant, personalized responses without waiting in queues. Traditional support channels—email, phone, even live chat—struggle to keep up with the sheer volume and speed demanded by modern audiences.
Telegram, with its 900 million monthly active users, has become a primary communication platform for businesses globally. Its open Bot API, combined with the rise of accessible Large Language Models (LLMs), makes it the ideal sandbox for building intelligent, cost-effective support systems. In this case study, we walk through a real-world implementation: a fully functional AI-powered customer support bot built with the aiogram 3.x framework, integrated with an LLM backend, payment processing, and a Web App interface.
We’ll cover the architecture, code examples, integration challenges, and measurable outcomes—everything you need to replicate this solution. For a deeper dive into the underlying concepts, the complete course on Telegram bot development using aiogram 3 is available on asibiont.com, covering state machines, keyboards, middleware, and more.
The Problem: Scaling Support Without Bloating Headcount
A mid-sized SaaS company, let’s call it Veridian, was handling roughly 1,200 support tickets per week. Their team of 10 agents could answer about 70% of queries within 24 hours, but the remaining 30%—often repetitive questions about billing, account reset, or feature usage—created a backlog that hurt retention. Customer satisfaction (CSAT) was dropping, and agent burnout was rising.
Key pain points identified:
- 65% of tickets were simple Q&A (pricing, hours, password reset).
- Average first response time: 14 hours.
- Peak hours (evenings, weekends) had zero coverage.
- Cost per ticket: ~$3.50 for human agents.
Veridian decided to build a Telegram bot that could answer common questions autonomously and seamlessly escalate complex issues to humans. The goal: reduce ticket volume by 50% and cut first response time to under 1 minute.
The Solution: Architecture Overview
The bot was designed using a modular, event-driven architecture. Here’s the high-level stack:
| Component | Technology | Purpose |
|---|---|---|
| Bot framework | aiogram 3.15 |
Handles Telegram updates, state machine, keyboards |
| LLM inference | OpenAI GPT-4o-mini (via API) + local fallback with Llama 3.2 | Generates context-aware responses |
| Vector database | Qdrant (self-hosted) | Stores company knowledge base for RAG |
| Payment processing | Telegram Stars API + Stripe | Handles subscription payments in chat |
| Web App | React (hosted on Vercel) | Provides interactive order tracking and FAQ browsing |
| Database | PostgreSQL (via asyncpg) | Stores user sessions, conversation logs, payment history |
| Task queue | Redis + Celery | Manages long-running LLM inference tasks |
Why aiogram 3? It’s the most mature async framework for Telegram bots in Python as of 2026. Its built-in FSM (Finite State Machine) and middleware system allowed us to build complex conversation flows without spaghetti code. The course on asibiont.com dedicates several modules to mastering these exact patterns.
Step 1: Setting Up the Bot Core with aiogram 3
First, we initialized the bot with aiogram 3’s Dispatcher. The key was using a Router for support-specific handlers, keeping the codebase maintainable.
from aiogram import Bot, Dispatcher, Router
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
bot = Bot(token="YOUR_TOKEN", default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dp = Dispatcher()
support_router = Router()
dp.include_router(support_router)
For state management, we used State and StatesGroup from aiogram’s FSM. This handled multi-step flows like “select issue category → describe problem → confirm escalation.”
from aiogram.fsm.state import State, StatesGroup
class SupportStates(StatesGroup):
waiting_for_issue = State()
waiting_for_details = State()
waiting_for_confirmation = State()
Middleware was crucial for logging and rate limiting. We wrote a custom middleware that logged every message to PostgreSQL and checked user’s subscription status before allowing premium features.
Step 2: Integrating AI (LLM) with Context-Aware Responses
Pure LLM responses without context are dangerous—they hallucinate. We implemented Retrieval-Augmented Generation (RAG) using Qdrant.
Pipeline:
1. User sends a question.
2. Bot embeds the query using text-embedding-3-small.
3. Vector search in Qdrant retrieves top 3 relevant chunks from the company’s knowledge base (FAQs, policy docs, troubleshooting guides).
4. LLM receives a prompt with: system instructions + retrieved chunks + user query.
5. Response is returned to the user via Telegram.
async def get_rag_response(query: str) -> str:
query_embedding = await embed_text(query)
results = qdrant_client.search(
collection_name="veridian_kb",
query_vector=query_embedding,
limit=3
)
context = "\n\n".join([r.payload["text"] for r in results])
prompt = f"""You are a Veridian support agent. Answer concisely.
Use only the context below. If unsure, say you need to transfer.
Context: {context}
Question: {query}"""
response = await openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.2
)
return response.choices[0].message.content
Fallback logic: If the LLM confidence score (extracted from logprobs) was below 0.7, the bot automatically triggered an escalation to a human agent.
Step 3: Payment Integration for Premium Support
Monetizing the bot was essential. We used Telegram Stars (Telegram’s internal currency launched in 2025) for microtransactions—e.g., $1.99 for priority response within 5 minutes. For subscription plans, we integrated Stripe via a Web App.
aiogram payment flow:
from aiogram.types import LabeledPrice, PreCheckoutQuery
@support_router.pre_checkout_query()
async def pre_checkout_handler(pre_checkout_q: PreCheckoutQuery):
await pre_checkout_q.answer(ok=True)
@support_router.message(F.successful_payment)
async def successful_payment_handler(message: Message):
await message.answer("✅ Priority access activated for 24 hours!")
# Update user's subscription in PostgreSQL
await update_user_subscription(message.from_user.id, "priority")
For subscription plans, we built a Telegram Web App (an iframe hosted on Vercel) where users could choose monthly or yearly plans, enter card details via Stripe Elements, and get redirected back to the bot. The Web App sent a confirmation via web_app_data to the bot.
// Inside React Web App
const handlePayment = async () => {
const response = await fetch('/api/create-checkout-session', { method: 'POST' });
const { url } = await response.json();
window.location.href = url; // Stripe Checkout
};
ASI Biont supports seamless integration with Stripe and Telegram Stars for handling payments inside your bot—learn more about setting up secure payment flows at asibiont.com.
Step 4: Building the Web App for Self-Service
To offload even more tickets, we created a Web App that provided interactive self-service: order history, product documentation, and a live “chat with AI” interface. The Web App communicated with the bot via Telegram.WebApp.sendData() and the web_app_data handler.
@support_router.message(F.web_app_data)
async def web_app_data_handler(message: Message):
data = json.loads(message.web_app_data.data)
if data["action"] == "get_order_status":
status = await fetch_order_status(data["order_id"])
await message.answer(f"Order #{data['order_id']} status: {status}")
This reduced simple order-status inquiries by 80%—users preferred the visual interface over typing.
Results: Measurable Impact After 3 Months
After deploying the bot to Veridian’s customer base (approx. 15,000 active users), we tracked the following KPIs:
| Metric | Before Bot | After Bot | Change |
|---|---|---|---|
| Tickets per week | 1,200 | 410 | -66% |
| First response time | 14 hours | 45 seconds | -99.9% |
| CSAT score | 3.2/5 | 4.6/5 | +44% |
| Cost per ticket | $3.50 | $0.12 (AI) + $2.50 (human) | -82% blended |
| Agent workload | 90% of tickets | 30% of tickets | -67% |
Key findings:
- The AI resolved 72% of all inquiries without human intervention.
- Only 12% of AI-handled conversations required a follow-up human escalation.
- Users who used the Web App had a 30% higher retention rate over 90 days.
Lessons Learned & Best Practices
- Context window management: LLM responses degrade with too much retrieved text. We limited context to 3 chunks (~2,000 tokens).
- Human handoff must be graceful: We used a middleware that tracked conversation state so that when a human agent joined, they saw the full history without repetition.
- Rate limiting for free tier: Without limits, a single user could drain the LLM budget. We implemented a token bucket per user per day.
- State machine is your friend: aiogram’s FSM made it trivial to handle multi-turn conversations. Avoid using global variables—they break when the bot scales.
- Test with real users early: We ran a beta with 200 users; they uncovered edge cases (e.g., users sending voice messages) that we hadn’t handled.
The complete implementation of state machines, middleware, and Web App integration is covered in-depth in the Telegram bot development course on asibiont.com. It includes ready-to-run code for exactly these patterns.
Conclusion
Building an AI-powered Telegram bot for customer support is not a futuristic dream—it’s a practical, high-ROI project you can deploy today. By combining aiogram 3’s robust framework with an LLM backend, a vector database for context, and a Web App for self-service, we reduced support costs by over 80% while dramatically improving user satisfaction.
The technology stack is mature, well-documented, and accessible to any Python developer willing to invest a few weeks in learning. Whether you’re running a startup or an enterprise, the blueprint in this article can be adapted to your domain.
Ready to build your own? The step-by-step course on asibiont.com walks you through every line of code, from setting up aiogram to deploying a production-ready bot with payment processing and Web Apps. Start your journey today.
Comments