Astreus - Docs

WhatsApp Plugin

WhatsApp Plugin

WhatsApp Plugin enables agents to interact with WhatsApp messaging using the official WhatsApp Cloud API, providing comprehensive messaging capabilities including text, media, templates, and interactive messages.

Features

  • Official WhatsApp Cloud API: Uses Meta's official WhatsApp Cloud API for reliable messaging
  • Easy Authentication: Simple token-based authentication with no QR code needed
  • Business Account Integration: Full integration with WhatsApp Business features
  • Comprehensive WhatsApp Integration: Send/receive messages, use templates, and more
  • Media Support: Send images, documents, audio, and other media types
  • Interactive Messages: Create rich interactions with buttons and list messages
  • Enhanced Logging: Detailed logging of WhatsApp operations for improved debugging
  • Integration with Astreus Logger: Consistent logging patterns with the core framework

Installation

Install the WhatsApp Plugin along with Astreus:

npm install @astreus-ai/astreus @astreus-ai/whatsapp-plugin

Configuration

To use the WhatsApp Plugin, you'll need WhatsApp Cloud API credentials:

  1. Create a Meta Developer account at developers.facebook.com
  2. Create a WhatsApp Business app
  3. Set up the WhatsApp Business API
  4. Obtain the necessary credentials from the Meta Developer Dashboard

Required environment variables:

# WhatsApp Cloud API configuration
WHATSAPP_API_VERSION=v17.0
WHATSAPP_API_TOKEN=your_api_access_token_here
WHATSAPP_PHONE_NUMBER_ID=your_phone_number_id_here
WHATSAPP_BUSINESS_ACCOUNT_ID=your_business_account_id_here

# Cache configuration (in seconds)
CACHE_MESSAGE_SECONDS=300
CACHE_CONTACT_SECONDS=3600

# Default response timeout in milliseconds
DEFAULT_REQUEST_TIMEOUT=30000

# Logging options
LOG_LEVEL=info  # Options: error, warn, info, debug

Basic Usage

Create an agent with the WhatsApp Plugin:

import { createAgent, createMemory, createProvider, createDatabase, PluginManager } from '@astreus-ai/astreus';
import WhatsAppPlugin from '@astreus-ai/whatsapp-plugin';

async function main() {
  // Initialize Astreus components
  const db = await createDatabase();
  const memory = await createMemory({ database: db, tableName: 'memories' });
  const provider = createProvider({ type: 'openai', model: 'gpt-4o-mini' });
  
  // Initialize WhatsApp Plugin
  const whatsAppPlugin = new WhatsAppPlugin();
  await whatsAppPlugin.init();
  
  // Create a plugin manager and add the WhatsApp plugin
  const pluginManager = new PluginManager({
    name: 'messaging-plugins',
    tools: whatsAppPlugin.getTools()
  });
  
  // Create an agent
  const agent = await createAgent({
    name: 'WhatsApp Agent',
    description: 'An assistant that can interact with WhatsApp',
    provider: provider,
    memory: memory,
    database: db,
    plugins: [pluginManager],
    systemPrompt: `You are a helpful assistant that can interact with WhatsApp.
Help the user send messages, media, and manage WhatsApp communications.`
  });
  
  // Your agent is now ready to interact with WhatsApp
  const response = await agent.chat('Send a WhatsApp message to +1234567890 saying "Hello, how are you?"');
  console.log(response);
}

main();

Custom Configuration

You can also configure the plugin with custom settings:

import WhatsAppPlugin from '@astreus-ai/whatsapp-plugin';

// Create a plugin with custom configuration
const whatsAppPlugin = new WhatsAppPlugin({
  apiVersion: 'v17.0',
  apiToken: 'your_api_token',
  phoneNumberId: 'your_phone_number_id',
  businessAccountId: 'your_business_account_id',
  cacheMessageSeconds: 600,
  logLevel: 'debug'  // Set logging verbosity
});

// Initialize the plugin
await whatsAppPlugin.init();

Available Tools

The WhatsApp Plugin provides comprehensive tools for WhatsApp messaging:

Send Message

Send a text message to a contact:

const response = await agent.execute('whatsapp_send_message', {
  to: '+1234567890',
  message: 'Hello! This is a message from Astreus WhatsApp Plugin.'
});

console.log(`Message sent with ID: ${response.messageId}`);

Send Template

Send a template message to a contact:

const response = await agent.execute('whatsapp_send_template', {
  to: '+1234567890',
  templateName: 'welcome_message',
  templateLanguage: 'en',
  templateParameters: [
    { type: 'text', text: 'John Doe' },
    { type: 'text', text: 'Welcome to our service!' }
  ]
});

console.log(`Template message sent with ID: ${response.messageId}`);

Send Media

Send media (image, document, etc.) to a contact:

const response = await agent.execute('whatsapp_send_media', {
  to: '+1234567890',
  mediaType: 'image',
  mediaUrl: 'https://example.com/image.jpg',
  caption: 'Check out this image!'
});

console.log(`Media message sent with ID: ${response.messageId}`);

Send Interactive Message

Send interactive messages with buttons or lists:

// Button message
const response = await agent.execute('whatsapp_send_interactive', {
  to: '+1234567890',
  interactiveType: 'button',
  bodyText: 'Please choose an option:',
  buttons: [
    { id: 'option1', title: 'Option 1' },
    { id: 'option2', title: 'Option 2' },
    { id: 'option3', title: 'Option 3' }
  ]
});

// List message
const listResponse = await agent.execute('whatsapp_send_interactive', {
  to: '+1234567890',
  interactiveType: 'list',
  bodyText: 'Please select from the menu:',
  buttonText: 'View Menu',
  sections: [
    {
      title: 'Main Dishes',
      rows: [
        { id: 'dish1', title: 'Pasta', description: 'Delicious pasta dish' },
        { id: 'dish2', title: 'Pizza', description: 'Fresh pizza' }
      ]
    }
  ]
});

Send Location

Send a location message:

const response = await agent.execute('whatsapp_send_location', {
  to: '+1234567890',
  latitude: 37.7749,
  longitude: -122.4194,
  name: 'San Francisco',
  address: 'San Francisco, CA, USA'
});

console.log(`Location message sent with ID: ${response.messageId}`);

Mark as Read

Mark a message as read:

const response = await agent.execute('whatsapp_mark_as_read', {
  messageId: 'message_id_to_mark_as_read'
});

console.log('Message marked as read');

Get Contact Info

Get contact information:

const response = await agent.execute('whatsapp_get_contact_info', {
  phoneNumber: '+1234567890'
});

console.log('Contact info:', response.contact);

Business Profile Management

Get and update your WhatsApp Business profile:

// Get business profile
const profile = await agent.execute('whatsapp_get_business_profile');
console.log('Business profile:', profile);

// Update business profile
const updateResponse = await agent.execute('whatsapp_update_business_profile', {
  about: 'We are a customer service company powered by AI',
  description: '24/7 AI-powered customer support',
  email: 'support@example.com',
  websites: ['https://example.com']
});

Error Handling

The plugin methods throw descriptive errors when something goes wrong. Always wrap the calls in try/catch blocks:

try {
  const response = await agent.execute('whatsapp_send_message', {
    to: '+1234567890',
    message: 'Hello World!'
  });
  console.log(`Message sent with ID: ${response.messageId}`);
} catch (error) {
  console.error('Failed to send WhatsApp message:', error.message);
}

Advanced Usage

Automated Customer Support

Create a WhatsApp customer support bot:

import { createAgent, createMemory, createProvider, createDatabase } from '@astreus-ai/astreus';
import WhatsAppPlugin from '@astreus-ai/whatsapp-plugin';

async function createSupportBot() {
  const db = await createDatabase();
  const memory = await createMemory({ database: db, tableName: 'memories' });
  const provider = createProvider({ type: 'openai', model: 'gpt-4o-mini' });
  
  const whatsAppPlugin = new WhatsAppPlugin();
  await whatsAppPlugin.init();
  
  const agent = await createAgent({
    name: 'WhatsApp Support Bot',
    description: 'Provides customer support via WhatsApp',
    provider: provider,
    memory: memory,
    database: db,
    systemPrompt: `You are a helpful customer support assistant on WhatsApp.
    Help customers with their questions and provide quick, friendly responses.
    If you can't help with something, offer to connect them with a human agent.`
  });
  
  // Add plugin tools to agent
  whatsAppPlugin.getTools().forEach(tool => agent.addTool(tool));
  
  return agent;
}

// Handle incoming messages
async function handleIncomingMessage(phoneNumber: string, message: string) {
  const agent = await createSupportBot();
  
  try {
    // Process the message and generate a response
    const response = await agent.chat(`Customer ${phoneNumber} says: "${message}". Please respond appropriately.`);
    
    // Send the response back via WhatsApp
    await agent.execute('whatsapp_send_message', {
      to: phoneNumber,
      message: response
    });
    
    console.log(`Responded to ${phoneNumber}: ${response}`);
  } catch (error) {
    console.error('Error handling message:', error.message);
    
    // Send error message to customer
    await agent.execute('whatsapp_send_message', {
      to: phoneNumber,
      message: 'Sorry, I encountered an error. Please try again or contact our support team.'
    });
  }
}

Broadcast Messages

Send messages to multiple contacts:

async function sendBroadcast(contacts: string[], message: string) {
  const agent = await createSupportBot();
  
  const promises = contacts.map(async (phoneNumber) => {
    try {
      const response = await agent.execute('whatsapp_send_message', {
        to: phoneNumber,
        message: message
      });
      return { phoneNumber, success: true, messageId: response.messageId };
    } catch (error) {
      return { phoneNumber, success: false, error: error.message };
    }
  });
  
  const results = await Promise.all(promises);
  return results;
}

// Usage
const contacts = ['+1234567890', '+0987654321', '+1122334455'];
const message = 'Hello! This is a broadcast message from our service.';
const results = await sendBroadcast(contacts, message);
console.log('Broadcast results:', results);

Interactive Menu System

Create an interactive menu system:

async function sendMainMenu(phoneNumber: string) {
  const agent = await createSupportBot();
  
  await agent.execute('whatsapp_send_interactive', {
    to: phoneNumber,
    interactiveType: 'button',
    bodyText: 'Welcome! How can I help you today?',
    buttons: [
      { id: 'support', title: '🛠️ Support' },
      { id: 'info', title: 'ℹ️ Information' },
      { id: 'contact', title: '📞 Contact Us' }
    ]
  });
}

async function handleMenuSelection(phoneNumber: string, selection: string) {
  const agent = await createSupportBot();
  
  switch (selection) {
    case 'support':
      await agent.execute('whatsapp_send_message', {
        to: phoneNumber,
        message: 'Please describe your issue and I\'ll help you resolve it.'
      });
      break;
    case 'info':
      await sendInfoMenu(phoneNumber);
      break;
    case 'contact':
      await agent.execute('whatsapp_send_message', {
        to: phoneNumber,
        message: 'You can reach us at:\n📧 support@example.com\n📞 +1-800-123-4567\n🌐 https://example.com'
      });
      break;
  }
}

Debugging

The plugin includes logging capabilities to help troubleshoot issues. You can adjust the logging level using the LOG_LEVEL environment variable or by setting the logLevel option when creating the plugin instance.

Available log levels:

  • error: Only error messages
  • warn: Warning and error messages
  • info: Informational, warning, and error messages (default)
  • debug: All messages including detailed debugging information

WhatsApp Cloud API Documentation

For more details on the WhatsApp Cloud API, refer to Meta's official documentation: WhatsApp Cloud API Documentation

Best Practices

  1. Verify Your Business: Complete WhatsApp Business verification for better features and trust
  2. Use Templates Wisely: Use approved message templates for notifications and broadcasts
  3. Handle Rate Limits: Respect WhatsApp's rate limits to avoid account restrictions
  4. Provide Opt-out Options: Always provide users with a way to opt out of messages
  5. Monitor Message Status: Track message delivery and read receipts for better user experience
  6. Use Interactive Messages: Leverage buttons and lists for better user engagement

Webhook Integration

To receive incoming messages, you'll need to set up webhooks in your Meta Developer Dashboard. The webhook should handle incoming message events and process them accordingly.

Support

For issues specific to the WhatsApp Plugin, please visit the GitHub repository.

For WhatsApp Cloud API issues, consult the Meta Developer Documentation or contact Meta support.

How is this guide?