A simple example of creating an AI-powered WhatsApp bot.
Skip the coding and get a fully-featured WhatsApp AI bot:
👉 Clawdbot Install - Free setup, no coding required
- Node.js 18+
- OpenAI API key
- WhatsApp account
npm install whatsapp-web.js openai qrcode-terminalconst { Client, LocalAuth } = require('whatsapp-web.js');
const OpenAI = require('openai');
const qrcode = require('qrcode-terminal');
// Initialize OpenAI
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// Initialize WhatsApp client
const client = new Client({
authStrategy: new LocalAuth(),
puppeteer: {
headless: true,
args: ['--no-sandbox']
}
});
// Show QR code for authentication
client.on('qr', (qr) => {
qrcode.generate(qr, { small: true });
console.log('Scan the QR code above to login');
});
client.on('ready', () => {
console.log('WhatsApp bot is ready!');
});
// Handle incoming messages
client.on('message', async (message) => {
// Ignore group messages and status updates
if (message.isGroupMsg || message.isStatus) return;
try {
console.log(`Received: ${message.body}`);
// Get AI response
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{
role: 'system',
content: 'You are a helpful AI assistant on WhatsApp. Keep responses concise.'
},
{
role: 'user',
content: message.body
}
],
max_tokens: 500
});
const reply = completion.choices[0].message.content;
await message.reply(reply);
console.log(`Replied: ${reply}`);
} catch (error) {
console.error('Error:', error);
await message.reply('Sorry, I encountered an error. Please try again.');
}
});
// Start the client
client.initialize();OPENAI_API_KEY=your-key node index.jsThis basic example:
- ❌ Cannot execute real tasks
- ❌ No memory/context
- ❌ No multi-user support
- ❌ No error recovery
For a production-ready WhatsApp AI assistant with:
- ✅ Task execution (emails, calendar, etc.)
- ✅ Conversation memory
- ✅ Multi-user support
- ✅ Error handling
- ✅ 24/7 uptime
Get free setup at Clawdbot Install