Complete guide to building WhatsApp chatbots with GPT-4 integration. NLP, conversation flows, lead qualification, and best practices for customer support automation.
WhatsApp has 2.0+ billion active users. It's where your customers already are. WhatsApp chatbots automate customer support, qualify leads, book appointments, and drive sales—24/7 without human intervention. This comprehensive guide shows you how to build intelligent WhatsApp chatbots with GPT-4 integration.
User → WhatsApp → Webhook → Your Server → ChatBot Logic → OpenAI GPT-4 → Response → WhatsApp → User
developers.facebook.com
const express = require('express');
const app = express();
app.use(express.json());
// Webhook verification (WhatsApp sends verification request)
app.get('/webhook', (req, res) => {
const verify_token = process.env.WEBHOOK_VERIFY_TOKEN;
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (token === verify_token) {
res.send(challenge);
} else {
res.status(403).send('Forbidden');
}
});
// Receive incoming messages
app.post('/webhook', (req, res) => {
const body = req.body;
if (body.object) {
body.entry.forEach((entry) => {
const changes = entry.changes[0];
const message = changes.value.messages[0];
if (message) {
const userPhone = message.from;
const messageText = message.text.body;
console.log(`Message from ${userPhone}: ${messageText}`);
// Process message and send response
handleMessage(userPhone, messageText);
}
});
res.status(200).send('EVENT_RECEIVED');
} else {
res.sendStatus(404);
}
});
app.listen(3000, () => console.log('Webhook listening on port 3000'));
const axios = require('axios');
async function sendWhatsAppMessage(recipientPhone, messageText) {
const accessToken = process.env.WHATSAPP_ACCESS_TOKEN;
const phoneNumberId = process.env.WHATSAPP_PHONE_ID;
const url = `https://graph.instagram.com/v18.0/${phoneNumberId}/messages`;
const data = {
messaging_product: 'whatsapp',
to: recipientPhone,
type: 'text',
text: {
body: messageText
}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});
console.log('Message sent:', response.data);
} catch (error) {
console.error('Error sending message:', error);
}
}
// Usage
sendWhatsAppMessage('+919876543210', 'Hello! How can I help you today?');
npm install openai
const { OpenAI } = require('openai');
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// Conversation history (store in database for persistence)
const conversationHistory = {};
async function getChatbotResponse(userId, userMessage) {
// Initialize or retrieve conversation history
if (!conversationHistory[userId]) {
conversationHistory[userId] = [];
}
// Add user message to history
conversationHistory[userId].push({
role: 'user',
content: userMessage
});
try {
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [
{
role: 'system',
content: `You are a helpful customer support chatbot for CyberCoderz, a web and mobile app development company.
You help customers with:
- Web app development services
- Mobile app development
- WhatsApp chatbots
- Bulk SMS APIs
- Support and guidance
Be friendly, professional, and concise. If you don't know something, offer to connect them with a human agent.`
},
...conversationHistory[userId]
],
temperature: 0.7,
max_tokens: 500
});
const assistantMessage = response.choices[0].message.content;
// Add response to history
conversationHistory[userId].push({
role: 'assistant',
content: assistantMessage
});
return assistantMessage;
} catch (error) {
console.error('OpenAI API error:', error);
return 'Sorry, I encountered an error. Please try again or contact support.';
}
}
Identify what the user wants to do:
async function detectIntent(userMessage) {
const intents = {
'pricing': ['cost', 'price', 'how much', 'expensive', 'budget'],
'services': ['services', 'what do you offer', 'solutions', 'help'],
'contact': ['contact', 'phone', 'email', 'reach you', 'call me'],
'schedule': ['meeting', 'call', 'consultation', 'demo', 'book']
};
const messageLower = userMessage.toLowerCase();
for (const [intent, keywords] of Object.entries(intents)) {
if (keywords.some(keyword => messageLower.includes(keyword))) {
return intent;
}
}
return 'general'; // Default intent
}
Automatically collect information from leads:
async function sendInteractiveMessage(recipientPhone) {
const data = {
messaging_product: 'whatsapp',
to: recipientPhone,
type: 'interactive',
interactive: {
type: 'button',
body: {
text: 'What service are you interested in?'
},
action: {
buttons: [
{ type: 'reply', reply: { id: '1', title: 'Web App' } },
{ type: 'reply', reply: { id: '2', title: 'Mobile App' } },
{ type: 'reply', reply: { id: '3', title: 'WhatsApp Chatbot' } }
]
}
}
};
// Send via WhatsApp API
await sendWhatsAppMessage(recipientPhone, data);
}
1. Intent Recognition
Identify what the user wants to do:
2. Lead Qualification
Automatically collect information from leads:
What deliverables follow from Building WhatsApp Chatbots: From Concept to Deployment?
Discovery, scoped proposal, sprint plan, and measurable milestones tied to the problem this article describes.
Who should read this AI & Automation article (whatsapp-chatbot-development-guide)?
Owners and teams evaluating AI & Automation who need practical delivery — not a generic brochure. This URL is whatsapp-chatbot-development-guide.
How fast can we start the work outlined in Building WhatsApp Chatbots: From Concept to Deployment?
Discovery calls within 1–2 business days; kickoff after scope sign-off. Slug whatsapp-chatbot-development-guide is enough context for the first call.
Does CyberCoderz support the stack described in Building WhatsApp Chatbots: From Concept to Deployment after launch?
Yes — maintenance, monitoring, SEO iterations, and feature work. Care plans are optional, not a lock-in.
How is whatsapp-chatbot-development-guide different from other CyberCoderz blog FAQs?
Questions on this URL are hashed from the slug whatsapp-chatbot-development-guide and the AI & Automation topic — not a shared four-line block pasted on every post.