Add an AI Assistant to WhatsApp or Telegram to Qualify Sales Leads Automatically
Automating sales lead qualification on messaging platforms like WhatsApp and Telegram requires three core components: a platform messaging API, an LLM (Large Language Model) processing engine, and a backend webhook script that routes qualified lead data directly into your CRM.
Architecture Overview
- Messaging Gateway: Receives inbound user messages and sends outbound replies via Telegram Bot API or Meta’s WhatsApp Cloud API.
- State Engine & LLM Processing: Processes incoming message context against a structured qualification framework (e.g., BANT: Budget, Authority, Need, Timeline).
- CRM Router: Parses structured responses (JSON) from the AI and creates or updates lead records in your CRM (HubSpot, Salesforce, or custom backend) when qualification criteria are met.
Step 1: Set Up Platform API Credentials
Telegram: Open Telegram, search for @BotFather, and run /newbot. Copy the generated API token. Set your webhook endpoint using a standard HTTP request:
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=https://your-server.com/webhook/telegram
WhatsApp: Create a Meta Developer account, set up a WhatsApp App, and configure the WhatsApp Cloud API. Store your Permanent Access Token, Phone Number ID, and set up your Webhook Callback URL and Verify Token in the Meta Developer Dashboard.
Step 2: System Prompt Engineering
To qualify leads predictably, force the LLM to output structured JSON containing the next message to send and a explicit qualification status flag. Sample system prompt:
You are an automated BDR assistant. Your goal is to collect:
1. Business Need
2. Company Size
3. Implementation Timeline
Ask one clear, conversational question at a time.
You must return ONLY a JSON object matching this schema:
{
"replyMessage": "string",
"isQualified": boolean,
"collectedData": {
"need": "string | null",
"companySize": "string | null",
"timeline": "string | null"
}
}
Step 3: Webhook Implementation (Node.js / Express Example)
The following webhook listener handles incoming Telegram updates, calls the OpenAI API using JSON mode, and triggers a CRM sync when a lead is marked qualified.
const express = require('express');
const { OpenAI } = require('openai');
const app = express();
app.use(express.json());
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
app.post('/webhook/telegram', async (req, res) => {
const { message } = req.body;
if (!message || !message.text) return res.sendStatus(200);
const chatId = message.chat.id;
const userMessage = message.text;
try {
// 1. Process conversation with OpenAI
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
response_format: { type: "json_object" },
messages: [
{ role: "system", content: "You are a sales assistant. Evaluate if lead is qualified based on need, company size, and timeline. Return JSON with key: replyMessage (string), isQualified (boolean), collectedData (object)." },
{ role: "user", content: userMessage }
]
});
const result = JSON.parse(completion.choices[0].message.content);
// 2. Reply to user on Telegram
await fetch(`https://api.telegram.org/bot${process.env.TELEGRAM_TOKEN}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId, text: result.replyMessage })
});
// 3. Send qualified leads to CRM
if (result.isQualified) {
await saveLeadToCRM(chatId, result.collectedData);
}
} catch (error) {
console.error('Processing error:', error);
}
res.sendStatus(200);
});
async function saveLeadToCRM(chatId, data) {
// Push parsed lead attributes to CRM API endpoint
console.log(`Pushing lead ${chatId} to CRM:`, data);
}
app.listen(3000, () => console.log('Webhook runner live on port 3000'));
Production Considerations
- Session State: Maintain dynamic history (using Redis or PostgreSQL) per user ID so the LLM retains multi-turn context.
- Human Handoff: Implement explicit trigger words (e.g., "human", "agent") or confidence thresholds to automatically pause the AI and alert a sales rep.
- Rate Limits & Verification: Implement queueing mechanisms (like BullMQ) for messaging endpoints to avoid hitting API throughput limits during high volume.
Need this done fast? order a RAG assistant on FreelanceHunt.
I take on freelance fixes and builds in this area.