@akson/chatsuite-sdk
Version:
Production-ready TypeScript SDK for ChatSuite - WhatsApp automation with built-in session management, message queuing, webhook server, and database sync
219 lines (191 loc) • 6.23 kB
text/typescript
import { WhatsAppClient, WebhookEvent } from '@whatsapp-baileys/sdk';
import * as fs from 'fs';
import * as path from 'path';
async function advancedExample() {
const client = new WhatsAppClient({
apiToken: process.env.WHATSAPP_API_TOKEN!,
retryConfig: {
retries: 3,
retryDelay: 2000,
retryCondition: (error: any) => {
return !error.response || error.response.status >= 500;
}
}
});
const phoneNumber = '+1234567890'; // Your WhatsApp number
try {
// 1. Interactive Messages Example
console.log('Sending interactive button message...');
await client.messages.sendInteractive(phoneNumber, 'recipient@c.us', {
type: 'button',
header: {
type: 'text',
text: 'Order Confirmation'
},
body: {
text: 'Would you like to confirm your order of 2 items for $29.99?'
},
footer: {
text: 'This offer expires in 24 hours'
},
action: {
buttons: [
{
type: 'reply',
reply: {
id: 'confirm_order',
title: 'Confirm Order'
}
},
{
type: 'reply',
reply: {
id: 'cancel_order',
title: 'Cancel'
}
},
{
type: 'url',
url: {
displayText: 'View Details',
url: 'https://example.com/order/12345'
}
}
]
}
});
// 2. Send Poll
console.log('Sending poll...');
await client.messages.sendPoll(phoneNumber, 'group@g.us', {
name: 'What time works best for our meeting?',
options: ['9:00 AM', '2:00 PM', '4:00 PM', 'None of these'],
selectableCount: 1
});
// 3. Group Management
console.log('Creating group...');
const group = await client.groups.create({
tel: phoneNumber,
name: 'Project Alpha Team',
participants: ['participant1@c.us', 'participant2@c.us']
});
// Update group description
await client.groups.update(phoneNumber, group.id, {
desc: 'Official group for Project Alpha discussions'
});
// Get invite link
const { url: inviteLink } = await client.groups.getInviteLink(phoneNumber, group.id);
console.log('Group invite link:', inviteLink);
// 4. Status/Story Updates
console.log('Posting status update...');
await client.status.postText(
phoneNumber,
'🎉 Excited to announce our new WhatsApp integration!',
'#4267B2',
1
);
// Post image status (load image as base64)
const imagePath = path.join(__dirname, 'status-image.jpg');
if (fs.existsSync(imagePath)) {
const imageBuffer = fs.readFileSync(imagePath);
const base64Image = imageBuffer.toString('base64');
await client.status.postImage(
phoneNumber,
base64Image,
'Check out our new features! 🚀'
);
}
// 5. Advanced Message Features
const sentMessage = await client.messages.sendText(
phoneNumber,
'recipient@c.us',
'This message has advanced features!'
);
// React to the message
await client.messages.react(phoneNumber, sentMessage.id.id, '👍');
// Edit the message
await client.messages.edit(
phoneNumber,
sentMessage.id.id,
'This message has been edited! ✏️'
);
// Pin the message for 7 days
await client.messages.pin(phoneNumber, sentMessage.id.id, 604800);
// Star the message
await client.messages.star(phoneNumber, sentMessage.id.id);
// 6. Contact Management
console.log('Checking contacts...');
const numbersToCheck = ['+1234567890', '+0987654321'];
const registered = await client.contacts.checkRegistered(phoneNumber, numbersToCheck);
for (const [number, isRegistered] of Object.entries(registered)) {
console.log(`${number}: ${isRegistered ? 'On WhatsApp' : 'Not on WhatsApp'}`);
}
// 7. Webhook Setup
console.log('Setting up webhook...');
const webhook = await client.setupWebhook(
'https://your-app.com/webhook/whatsapp',
[
WebhookEvent.MESSAGE_RECEIVED,
WebhookEvent.MESSAGE_SENT,
WebhookEvent.MESSAGE_DELIVERED,
WebhookEvent.MESSAGE_READ,
WebhookEvent.SESSION_CONNECTED,
WebhookEvent.SESSION_DISCONNECTED
],
'your_webhook_secret'
);
console.log('Webhook configured:', webhook.id);
// 8. Bulk Messaging with Rate Limiting
console.log('Sending bulk messages...');
const recipients = [
'1234567890@c.us',
'0987654321@c.us',
'1122334455@c.us'
];
for (const recipient of recipients) {
try {
await client.messages.sendText(
phoneNumber,
recipient,
'Hello! This is a personalized message for you.'
);
console.log(`Message sent to ${recipient}`);
// Add delay to respect rate limits
await new Promise(resolve => setTimeout(resolve, 1000));
} catch (error) {
console.error(`Failed to send to ${recipient}:`, error);
}
}
// 9. Media Download and Forward
const messages = await client.messages.list({
tel: phoneNumber,
hasMedia: true,
limit: 10
});
if (messages.messages.length > 0) {
const mediaMessage = messages.messages[0];
// Download media
const media = await client.messages.downloadMedia(mediaMessage._id!);
console.log('Downloaded media:', media.filename);
// Forward to another chat
await client.messages.sendMedia(
phoneNumber,
'another-recipient@c.us',
media.data,
media.mimetype,
media.filename,
'Forwarding this media to you!'
);
}
// 10. Usage Statistics
console.log('Getting usage stats...');
const stats = await client.getUsageStats(
new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(), // 7 days ago
new Date().toISOString()
);
console.log('Usage stats:', stats);
} catch (error) {
console.error('Error in advanced example:', error);
}
}
// Run the example
advancedExample();