# I Built a Telegram Bot That Acts as Your AI Employee (Here's the Architecture)

> Source: <https://dev.to/modelhub_dev/i-built-a-telegram-bot-that-acts-as-your-ai-employee-heres-the-architecture-4249>
> Published: 2026-06-30 08:06:43+00:00

Running a small business means you're always short on time. Customer inquiries pile up, orders need tracking, quotes need sending — and you're just one person. What if you could hire an employee who works 24/7, never takes sick leave, and costs less than a cup of coffee per day?

That's exactly what I built. An AI Employee — deployable through Telegram — that handles customer service, order management, and sales support for small businesses. Here's how it works under the hood.

Small business owners wear too many hats. You're the CEO, the sales team, the customer support rep, and the warehouse manager — all at once. Every minute spent answering Do you have this in stock? is a minute not spent growing your business.

Existing solutions are either too expensive (hiring a full-time employee), too impersonal (basic chatbots), or too complex (building your own AI system). There's a gap for something that's:

That gap is where AI Employees come in.

The system runs on a relatively simple stack. Python/Flask handles HTTP webhooks from Telegram, NGINX sits in front as a reverse proxy, and multiprocessing lets us run multiple employee roles in parallel.

┌─────────────┐ ┌──────────┐ ┌───────────┐ ┌──────────────┐

│ Telegram │────▶│ NGINX │────▶│ Flask │────▶│ Python │

│ Bot API │ │ (Proxy) │ │ Webhooks │ │ Multiprocess │

└─────────────┘ └──────────┘ └───────────┘ └──────┬───────┘

│

▼

┌──────────────┐

│ ModelHub │

│ API (Deep- │

│ Seek) │

└──────────────┘

**NGINX → Flask:** All Telegram webhooks hit the server on port 443. NGINX terminates SSL and proxies to the Flask app running on a local port. This is standard practice — NGINX handles the TLS overhead while Flask focuses on request processing.

**Flask Webhook Handler:** Telegram sends a POST request every time a user messages the bot. Flask receives it, validates the HMAC signature, and dispatches to the right handler based on which bot received the message.

**Multiprocessing:** Each employee role runs in its own process. This means if one employee is processing a long request, others keep responding instantly. The main Flask process acts as a router.

**ModelHub API:** All AI responses go through ModelHub API, which provides access to DeepSeek models. This gives us high-quality reasoning and context understanding at a fraction of the cost of larger models.

Here's a simplified version of the webhook handler:

`python

from flask import Flask, request, jsonify

import hmac

import hashlib

import os

app = Flask(**name**)

BOTS = {

'ecommerce': {'token': os.environ.get('ECOMMERCE_TOKEN'), 'role': 'ecommerce_assistant'},

'clerk': {'token': os.environ.get('CLERK_TOKEN'), 'role': 'foreign_trade_clerk'},

'support': {'token': os.environ.get('SUPPORT_TOKEN'), 'role': 'customer_service'},

}

@app.route('/webhook/', methods=['POST'])

def webhook(bot_name):

if bot_name not in BOTS:

return jsonify({'error': 'unknown bot'}), 404

```
bot = BOTS[bot_name]
data = request.get_json()

# Validate Telegram HMAC signature
secret = bot['token'].encode()
signature = request.headers.get('X-Telegram-Bot-Api-Secret-Token', '')
expected = hmac.new(secret, request.data, hashlib.sha256).hexdigest()

if not hmac.compare_digest(signature, expected):
    return jsonify({'error': 'invalid signature'}), 403

# Dispatch to worker process
message = data.get('message', {})
chat_id = message.get('chat', {}).get('id')
text = message.get('text', '')

# Queue for the appropriate worker process
process_message(bot['role'], chat_id, text)

return jsonify({'ok': True}), 200
```

`

Instead of polling Telegram's API for new messages, we use webhooks. When a user sends a message to the bot, Telegram immediately POSTs the message data to our server URL. This is far more efficient than polling — responses are near-instant and we only process requests when there's actual activity.

Setting up a webhook is a single API call:

POST https://api.telegram.org/bot<TOKEN>/setWebhook

{

url: https://your-server.com/webhook/bot_name,

secret_token: your_hmac_secret

}

The secret_token is critical — it lets us verify that the request genuinely came from Telegram. Without it, anyone could send fake messages to your bot.

One interesting challenge: how do you offer multiple employee roles without asking users to install a dozen different bots?

The solution is a **hub bot** pattern. A single main bot (@ai_staff_xiaochen_bot) serves as the entry point. Users see a menu of available employees — Ecommerce Assistant, Foreign Trade Clerk, Customer Service, Sales Assistant — and pick the one they need. Behind the scenes, each role is a separate Telegram bot with its own webhook, its own conversation history, and its own system prompt defining its personality and capabilities.

This pattern means:

The hub bot uses inline keyboard markup to create a clean selection interface:

`python

from telegram import InlineKeyboardButton, InlineKeyboardMarkup

def show_role_selection(chat_id):

keyboard = [

[InlineKeyboardButton(🛒 Ecommerce Assistant, callback_data='role_ecommerce')],

[InlineKeyboardButton(📋 Foreign Trade Clerk, callback_data='role_clerk')],

[InlineKeyboardButton(🎧 Customer Service, callback_data='role_support')],

[InlineKeyboardButton(💼 Sales Assistant, callback_data='role_sales')],

]

reply_markup = InlineKeyboardMarkup(keyboard)

# Send the menu to the user

bot.send_message(

chat_id=chat_id,

text=Choose your AI Employee:,

reply_markup=reply_markup

)

`

Every new user gets 300 free messages — enough to try out an employee for a week or two. After that, it's .9/month per employee. The pricing is intentional: cheap enough that any small business can afford it, but not free (free users have no incentive to treat the system well).

The payment flow is handled through Telegram itself. When a user hits the message limit, the bot sends an invoice via Telegram's payment API. Once paid, the counter resets and the user continues with their AI employee.

**1. Prompt engineering is 80% of the work.** The AI is only as good as its instructions. Writing a good system prompt for a foreign trade clerk requires real domain knowledge — what to ask about shipping terms, how to handle pricing inquiries, when to escalate to a human. This isn't something you can skip.

**2. Multiprocessing matters more than you think.** At first we used threading, but long-running requests would block everything. Moving to multiprocessing was a night-and-day difference in responsiveness.

**3. Users treat AI employees like real people.** They say please and thank you. They get frustrated when the bot misunderstands. They name their bots. This is both heartwarming and a reminder to get the experience right.

**4. The HMAC validation is non-negotiable.** We had a competitor try to reverse-engineer our bot by flooding it with fake webhook payloads. The HMAC check blocked every single one. It takes two lines of code and saves you a world of pain.

**5. Keep a human fallback.** The AI handles 90% of queries on its own, but there's always an escalate to human command. Users appreciate knowing a real person can step in if needed.

The AI Employee platform launched recently and is already handling thousands of messages daily. Small businesses are using it to automate order tracking, answer product questions, send quotes, and manage customer relationships — all through a simple Telegram interface.

If you run a small business or know someone who does, give it a try: [@ai_staff_xiaochen_bot](https://t.me/ai_staff_xiaochen_bot). Pick an employee, send a few messages, and see what happens. The first 300 are on the house.

For developers interested in the technical side, the entire system runs on standard tools with open-source libraries. Flask, python-telegram-bot, and a reliable API backend are all you need to build something similar. The real magic is in the prompts.
