Bot WA AI dengan ChatGPT: Panduan Integrasi
Tutorial lengkap integrasi ChatGPT dengan WhatsApp Bot. Code example, best practices, dan tips optimasi. Step-by-step!
ChatGPT + WhatsApp = Power combo!
ChatGPT dari OpenAI adalah AI paling populer dan powerful. Dengan integrasi yang tepat, bot WA kamu bisa menjawab hampir semua pertanyaan dengan cerdas.
Persiapan
Yang Dibutuhkan:
1. OpenAI API Key
2. WhatsApp Bot (whatsapp-web.js atau Baileys)
3. Node.js environment
4. Saldo API (~$5 untuk mulai)Biaya OpenAI:
| Model | Input | Output | Best For |
|---|---|---|---|
| GPT-4o | $2.50/1M | $10/1M | Complex tasks |
| GPT-4o-mini | $0.15/1M | $0.60/1M | Recommended! |
| GPT-3.5-turbo | $0.50/1M | $1.50/1M | Budget option |
Rekomendasi: GPT-4o-mini — murah tapi sangat capable!
Step 1: Dapatkan API Key
1. Kunjungi platform.openai.com
2. Sign up / Login
3. Billing > Add payment method
4. API Keys > Create new secret key
5. Copy key (simpan aman!)Step 2: Setup Project
bash
mkdir wa-chatgpt-bot
cd wa-chatgpt-bot
npm init -y
npm install whatsapp-web.js qrcode-terminal openaiStep 3: Code Dasar
javascript
// index.js
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const OpenAI = require('openai');
// Initialize OpenAI
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY || 'your-api-key-here'
});
// Initialize WhatsApp
const client = new Client({
authStrategy: new LocalAuth()
});
// QR Code
client.on('qr', qr => {
qrcode.generate(qr, { small: true });
});
client.on('ready', () => {
console.log('Bot is ready!');
});
// System prompt
const systemPrompt = `Kamu adalah customer service [Nama Toko],
toko online yang menjual produk skincare.
Tugas:
- Jawab pertanyaan tentang produk
- Berikan rekomendasi
- Bantu proses order
Produk:
- Serum Vitamin C (Rp 150.000): Untuk brightening
- Moisturizer (Rp 100.000): Untuk hidrasi
- Sunscreen (Rp 125.000): Perlindungan UV
Jawab dengan ramah dalam Bahasa Indonesia.
Gunakan emoji secukupnya.`;
// Handle messages
client.on('message', async msg => {
// Ignore group messages (optional)
if (msg.from.includes('@g.us')) return;
// Ignore own messages
if (msg.fromMe) return;
try {
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: msg.body }
],
max_tokens: 500,
temperature: 0.7
});
const reply = response.choices[0].message.content;
await msg.reply(reply);
} catch (error) {
console.error('Error:', error);
await msg.reply('Maaf, terjadi kendala. Silakan chat admin.');
}
});
client.initialize();Step 4: Jalankan Bot
bash
# Set API key (Linux/Mac)
export OPENAI_API_KEY='your-key-here'
# Atau buat .env file
echo "OPENAI_API_KEY=your-key-here" > .env
# Install dotenv
npm install dotenv
# Jalankan
node index.jsAdvanced: Conversation Memory
Supaya bot ingat konteks percakapan:
javascript
const conversationHistory = new Map();
client.on('message', async msg => {
const sender = msg.from;
// Get or create conversation history
if (!conversationHistory.has(sender)) {
conversationHistory.set(sender, [
{ role: 'system', content: systemPrompt }
]);
}
const history = conversationHistory.get(sender);
// Add user message
history.push({ role: 'user', content: msg.body });
// Keep only last 10 messages (to manage tokens)
if (history.length > 12) {
history.splice(1, 2); // Remove oldest (keep system prompt)
}
try {
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: history,
max_tokens: 500
});
const reply = response.choices[0].message.content;
// Add assistant reply to history
history.push({ role: 'assistant', content: reply });
await msg.reply(reply);
} catch (error) {
console.error('Error:', error);
}
});
// Clear old conversations periodically
setInterval(() => {
const oneHourAgo = Date.now() - 60 * 60 * 1000;
// Clear logic based on last activity timestamp
}, 30 * 60 * 1000); // Every 30 minutesAdvanced: Function Calling
Buat ChatGPT bisa trigger actions:
javascript
const functions = [
{
name: 'check_stock',
description: 'Check product stock availability',
parameters: {
type: 'object',
properties: {
product_name: {
type: 'string',
description: 'Name of the product'
}
},
required: ['product_name']
}
},
{
name: 'create_order',
description: 'Create a new order',
parameters: {
type: 'object',
properties: {
product: { type: 'string' },
quantity: { type: 'integer' },
customer_name: { type: 'string' }
},
required: ['product', 'quantity']
}
}
];
// Handle function calls
async function handleFunctionCall(functionName, args) {
switch (functionName) {
case 'check_stock':
return checkStock(args.product_name);
case 'create_order':
return createOrder(args);
default:
return 'Function not found';
}
}
client.on('message', async msg => {
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: msg.body }
],
functions: functions,
function_call: 'auto'
});
const choice = response.choices[0];
if (choice.finish_reason === 'function_call') {
const functionCall = choice.message.function_call;
const result = await handleFunctionCall(
functionCall.name,
JSON.parse(functionCall.arguments)
);
// Send function result back to GPT
const followUp = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: msg.body },
choice.message,
{ role: 'function', name: functionCall.name, content: result }
]
});
await msg.reply(followUp.choices[0].message.content);
} else {
await msg.reply(choice.message.content);
}
});Best Practices
1. Rate Limiting
javascript
const rateLimiter = new Map();
function isRateLimited(sender) {
const now = Date.now();
const lastRequest = rateLimiter.get(sender) || 0;
if (now - lastRequest < 1000) { // 1 second cooldown
return true;
}
rateLimiter.set(sender, now);
return false;
}
client.on('message', async msg => {
if (isRateLimited(msg.from)) {
return; // Ignore rapid messages
}
// ... continue
});2. Error Handling
javascript
async function getAIResponse(message, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: message }
]
});
return response.choices[0].message.content;
} catch (error) {
if (i === retries - 1) throw error;
await delay(1000 * (i + 1)); // Exponential backoff
}
}
}3. Content Moderation
javascript
async function moderateContent(text) {
const moderation = await openai.moderations.create({
input: text
});
return moderation.results[0].flagged;
}
client.on('message', async msg => {
// Check if content is inappropriate
const flagged = await moderateContent(msg.body);
if (flagged) {
return msg.reply('Maaf, pesan tidak dapat diproses.');
}
// ... continue
});Tips Optimasi Biaya
1. Gunakan Model yang Tepat
GPT-4o-mini untuk kebanyakan task
GPT-4o hanya untuk yang kompleks2. Batasi Token
javascript
max_tokens: 500 // Cukup untuk WA3. Cache Common Responses
javascript
const responseCache = new Map();
async function getCachedResponse(key, generator) {
if (responseCache.has(key)) {
return responseCache.get(key);
}
const response = await generator();
responseCache.set(key, response);
return response;
}4. Hybrid dengan Keyword
javascript
const keywords = {
'harga': 'Daftar harga: ...',
'alamat': 'Alamat: ...'
};
client.on('message', async msg => {
// Check keyword first (free)
for (const [kw, resp] of Object.entries(keywords)) {
if (msg.body.toLowerCase().includes(kw)) {
return msg.reply(resp);
}
}
// Only use AI if no keyword match
const aiResp = await getAIResponse(msg.body);
await msg.reply(aiResp);
});FAQ
Berapa biaya per bulan?
Dengan GPT-4o-mini dan 1000 chat/bulan: ~500 tokens per chat × 1000 = 500K tokens = ~Rp 15.000/bulan. Sangat terjangkau!
Apakah API key aman?
Simpan di environment variable, jangan hardcode. Jangan share atau commit ke Git.
Model mana yang paling bagus?
GPT-4o-mini adalah sweet spot untuk bot WA. Murah, cepat, dan sangat capable.
Kesimpulan
ChatGPT + WhatsApp = Bot yang sangat cerdas!
Quick Start:
1. Dapatkan API key
2. Setup project Node.js
3. Copy code di atas
4. Customize system prompt
5. Run & test!Selamat mencoba!