Skip to main content

Messaging Guide

This guide covers sending and receiving different types of messages using the WhatsApp SDK.

Prerequisites

Before you start, make sure:
  1. You’ve installed the WhatsApp SDK
  2. You’ve successfully authenticated with WhatsApp
  3. Your client is in the READY state

Sending Text Messages

The most basic operation is sending a text message to a contact:
import { WhatsAppSDK } from '@deco-cx/whatsapp-sdk';

// Create SDK and client instances (authentication steps omitted)
const sdk = new WhatsAppSDK({ /* config */ });
const client = sdk.createClient();

// Wait for client to be ready
client.on('ready', async () => {
  // Send a text message
  const result = await client.sendTextMessage({
    to: '[email protected]', // Phone number with @c.us suffix
    text: 'Hello from WhatsApp SDK!'
  });
  
  console.log('Message sent:', result.id);
});

Message Options

You can include additional options when sending messages:
await client.sendTextMessage({
  to: '[email protected]',
  text: 'Hello with options!',
  options: {
    // Generate link previews for URLs in the message
    linkPreview: true,
    
    // Mark the chat as seen before sending the message
    sendSeen: true,
    
    // Mention specific contacts in the message
    mentions: ['[email protected]', '[email protected]'],
    
    // Quote/reply to another message
    quotedMessageId: 'previous_message_id'
  }
});

Sending Media Messages

The SDK supports sending various types of media messages:

Images

// Send an image from a URL
await client.sendImageMessage({
  to: '[email protected]',
  image: {
    url: 'https://example.com/image.jpg',
    caption: 'Check out this image!'
  }
});

// Or send an image from local file path
await client.sendImageMessage({
  to: '[email protected]',
  image: {
    path: '/path/to/image.jpg',
    caption: 'Image from local file'
  }
});

// Or send from a Buffer
await client.sendImageMessage({
  to: '[email protected]',
  image: {
    buffer: imageBuffer, // Buffer containing image data
    mimetype: 'image/jpeg',
    caption: 'Image from buffer'
  }
});

Videos

await client.sendVideoMessage({
  to: '[email protected]',
  video: {
    url: 'https://example.com/video.mp4',
    caption: 'Watch this video!'
  }
});

Audio

await client.sendAudioMessage({
  to: '[email protected]',
  audio: {
    url: 'https://example.com/audio.mp3'
  }
});

Documents

await client.sendDocumentMessage({
  to: '[email protected]',
  document: {
    url: 'https://example.com/document.pdf',
    filename: 'report.pdf',
    caption: 'Important document'
  }
});

Stickers

await client.sendStickerMessage({
  to: '[email protected]',
  sticker: {
    url: 'https://example.com/sticker.webp'
  }
});

Sending to Groups

Sending messages to groups works the same way, just use the group ID:
await client.sendTextMessage({
  to: '[email protected]', // Group ID with @g.us suffix
  text: 'Hello group!'
});

Receiving Messages

To receive messages, you need to listen for message events:
// Listen for all new messages
client.on('message', (message) => {
  console.log('New message received:', message.body);
  console.log('From:', message.from);
  console.log('Is group message:', message.isGroup);
});

// Listen only for messages created by others (not your own)
client.on('message.create', (message) => {
  if (!message.fromMe) {
    console.log('New message from someone else:', message.body);
  }
});

Message Object Properties

The message object contains various properties:
client.on('message', (message) => {
  console.log('ID:', message.id);
  console.log('Content:', message.body);
  console.log('Sender:', message.from);
  console.log('Chat ID:', message.to);
  console.log('Timestamp:', message.timestamp);
  console.log('Has media:', message.hasMedia);
  console.log('Is group message:', message.isGroup);
  console.log('Is broadcast message:', message.broadcast);
  console.log('Has quoted message:', message.hasQuotedMsg);
});

Replying to Messages

You can reply to specific messages using the message object:
client.on('message', async (message) => {
  if (message.body === '!hello') {
    // Reply to the specific message
    await message.reply('Hello there!');
  }
});

Forwarding Messages

Similarly, you can forward messages to other chats:
client.on('message', async (message) => {
  if (message.body.startsWith('!forward')) {
    // Extract the target chat ID from the command
    const targetChat = message.body.split(' ')[1];
    
    // Forward the message
    await message.forward(targetChat);
  }
});

Handling Media Messages

When receiving media messages, you need to download the media:
client.on('message', async (message) => {
  if (message.hasMedia) {
    // Get media type
    console.log('Media type:', message.type);
    
    // Download the media
    const media = await message.downloadMedia();
    
    console.log('Media data:', media.data); // Base64 encoded data
    console.log('MIME type:', media.mimetype);
    console.log('Filename:', media.filename);
  }
});

Using the REST API for Messaging

If you’re using the REST API, you can send messages using HTTP requests:

Sending Text Messages

curl -X POST http://localhost:3000/api/v1/messages \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-auth-token" \
  -d '{
    "chatId": "[email protected]",
    "content": "Hello from REST API!"
  }'

Sending Media Messages

curl -X POST http://localhost:3000/api/v1/messages \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-auth-token" \
  -d '{
    "chatId": "[email protected]",
    "content": {
      "type": "image",
      "url": "https://example.com/image.jpg",
      "mimetype": "image/jpeg",
      "caption": "Image via REST API"
    }
  }'

Best Practices

  1. Rate Limiting: Don’t send too many messages in a short time to avoid being blocked
  2. Error Handling: Always handle potential errors when sending messages
  3. Message Queuing: For bulk messaging, implement a queue to space out messages
  4. Media Compression: Compress media files before sending to reduce bandwidth usage
  5. Respect Privacy: Only send messages to users who have opted in to receive them

Common Error Scenarios

  • Chat not found: Verify the chat ID is correct and properly formatted
  • Media download failed: Check network connectivity and file availability
  • Permission errors: Ensure you have the right permissions to send messages to groups
  • Message not delivered: Check the ack property to see if the message was delivered