Telegram Bots for Sales Automation: Building, Deploying, and Scaling
Technical guide to building Telegram bots for B2B sales: bot architecture, message handling, integration with CRM, and scaling considerations.
Telegram Bots for Sales Automation: Building, Deploying, and Scaling
Telegram bots automate conversations at scale. A well-built bot handles 80% of sales interactions, freeing human reps to focus on closing. This guide covers architecture, implementation, and scaling.
Bot Architecture
Components
Telegram Bot API
↓
Message Router
↓
┌─────────────────┐
│ Handler Registry │
├─────────────────┤
│ Command Handler │ /start, /help, /pricing
│ Message Handler │ Free-form text messages
│ Callback Handler │ Inline keyboard presses
│ Media Handler │ Photos, documents, voice
└─────────────────┘
↓
┌─────────────────┐
│ Business Logic │
├─────────────────┤
│ Lead Qualifier │ BANT scoring
│ Response Generator│ AI or template-based
│ CRM Sync │ Lead creation/update
│ Analytics │ Event tracking
└─────────────────┘
↓
Telegram Bot API (send message)
Technology Stack
| Component | Options | Recommendation |
|---|---|---|
| Language | Python, Node.js, Go | Python (Telethon) |
| Framework | python-telegram-bot, Telethon | Telethon (full API access) |
| Database | PostgreSQL, Redis | PostgreSQL + Redis |
| AI | OpenRouter, OpenAI, DeepSeek | OpenRouter (free models) |
| Deployment | Docker, VPS | Docker on VPS |
Implementation
Basic Bot Setup
from telethon import TelegramClient, events
bot = TelegramClient('bot', api_id, api_hash)
@bot.on(events.NewMessage(pattern='/start'))
async def handle_start(event):
await event.respond(
"Welcome! I can help you with:
"
"1. Product demo
"
"2. Pricing info
"
"3. Technical questions
"
"What would you like to know?"
)
@bot.on(events.NewMessage)
async def handle_message(event):
# Route to appropriate handler
response = await generate_response(event.message.text)
await event.respond(response)
Message Classification
Classify incoming messages to route correctly:
async def classify_message(text):
# Classify message intent using keyword matching + AI fallback
# High-intent keywords
pricing_keywords = ['цена', 'pricing', 'стоимость', 'сколько']
demo_keywords = ['демо', 'demo', 'показать', 'попробовать']
support_keywords = ['проблема', 'ошибка', 'не работает', 'help']
text_lower = text.lower()
if any(kw in text_lower for kw in pricing_keywords):
return 'pricing'
if any(kw in text_lower for kw in demo_keywords):
return 'demo'
if any(kw in text_lower for kw in support_keywords):
return 'support'
# Fallback to AI classification
return await ai_classify(text)
Lead Qualification Bot
async def qualify_lead(conversation_history):
# Score lead based on conversation signals
score = 0
signals = []
for message in conversation_history:
text = message.text.lower()
# Budget signals
if any(w in text for w in ['бюджет', 'budget', 'цена', 'invest']):
score += 30
signals.append('budget_mentioned')
# Authority signals
if any(w in text for w in ['решаю', 'команда', 'руководитель']):
score += 25
signals.append('authority_signal')
# Need signals
if any(w in text for w in ['нужно', 'проблема', 'хочу', 'ищу']):
score += 30
signals.append('need_signal')
# Timeline signals
if any(w in text for w in ['сейчас', 'скоро', 'квартал']):
score += 15
signals.append('timeline_signal')
return {
'score': min(score, 100),
'qualified': score >= 70,
'signals': signals
}
CRM Integration
Webhook to AmoCRM
async def create_amocrm_lead(lead_data):
# Create lead in AmoCRM via API
url = "https://www.amocrm.ru/api/v4/leads"
headers = {
"Authorization": f"Bearer {AMOCRM_TOKEN}",
"Content-Type": "application/json"
}
payload = {
"name": lead_data['name'],
"price": lead_data.get('value', 0),
"status_id": 142,
"pipeline_id": lead_data['pipeline_id'],
"custom_fields_values": [
{
"field_code": "TG_USERNAME",
"values": [{"value": lead_data['telegram_username']}]
}
]
}
response = requests.post(url, json=payload, headers=headers)
return response.json()
Event Tracking
async def track_event(event_type, data):
# Track bot events for analytics
await db.execute(
"INSERT INTO bot_events (event_type, data, created_at) VALUES ($1, $2, NOW())",
event_type, json.dumps(data)
)
Scaling Considerations
Vertical Scaling
| Resource | Small (1K users) | Medium (10K users) | Large (100K users) |
|---|---|---|---|
| CPU | 2 cores | 4 cores | 8 cores |
| RAM | 2GB | 4GB | 8GB |
| Database | 10GB | 50GB | 200GB |
| Connections | 100 | 500 | 2000 |
Horizontal Scaling
For 10K+ concurrent users:
- Message queue: Redis/RabbitMQ for message buffering
- Worker pool: Multiple bot instances processing messages
- Database connection pooling: PgBouncer for PostgreSQL
- Load balancer: Distribute across instances
Rate Limits
Telegram Bot API limits:
- 30 messages per second to different users
- 20 messages per minute to same group
- 1 message per second to same user
Mitigation: Implement rate limiting in bot code, use message queues for high-volume scenarios.
Common Bot Mistakes
- No error handling: Bots crash on unexpected input. Add try/except everywhere.
- Synchronous operations: Blocking I/O kills performance. Use async/await.
- No state management: Conversations need context. Use Redis for session state.
- Ignoring rate limits: Telegram bans bots that exceed limits.
- No monitoring: Bots fail silently. Add logging and alerting.
Deployment
Docker Configuration
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "bot.py"]
Environment Variables
TG_API_ID=your_api_id
TG_API_HASH=your_api_hash
BOT_TOKEN=your_bot_token
DATABASE_URL=postgresql://user:pass@host/db
AMOCRM_TOKEN=your_amocrm_token
Conclusion
Telegram bots automate the repetitive parts of sales: initial response, qualification, scheduling, and follow-up. Build with Telethon, integrate with your CRM, deploy on Docker, and scale with message queues. The bot handles 80% of interactions; your team closes the 20% that matter.