Whatify LogoWhatify
Examples

Basic Usage Examples

Practical examples for common use cases with Whatify

This guide provides practical examples for common use cases with Whatify.

Table of Contents

Connection Management

Connect with QR Code

import { Whatify } from "whatify-whatsapp-client";

const client = new Whatify({
  apiToken: process.env.WHATIFY_API_TOKEN!,
});

async function connectWithQR() {
  const result = await client.connect({
    method: "qrCode",
  });

  if (result.success) {
    console.log("Scan this QR code with WhatsApp:");
    console.log(result.qrCode);
  } else {
    console.error("Connection failed:", result.error);
  }
}

connectWithQR();

Connect with Pairing Code

async function connectWithPairingCode() {
  const result = await client.connect({
    method: "pairingCode",
    phoneNumber: "1234567890",
  });

  if (result.success) {
    console.log("Enter this pairing code in WhatsApp:");
    console.log(result.pairingCode);
  } else {
    console.error("Connection failed:", result.error);
  }
}

connectWithPairingCode();

Check Connection Status

async function checkStatus() {
  const status = await client.status();

  if (status.success) {
    console.log("Status:", status.status);
    console.log("Phone:", status.phone);
    console.log("Name:", status.name);
  } else {
    console.error("Failed to get status:", status.error);
  }
}

checkStatus();

Auto-Reconnect on Disconnect

async function autoConnect() {
  const status = await client.status();

  if (status.status !== "connected") {
    console.log("Not connected, initiating connection...");
    const result = await client.connect();

    if (result.success) {
      console.log("QR Code:", result.qrCode);
    }
  } else {
    console.log("Already connected!");
  }
}

autoConnect();

Sending Messages

Send Simple Text Message

async function sendText() {
  const result = await client.send({
    to: "1234567890",
    text: "Hello from Whatify!",
  });

  if (result.success) {
    console.log("Message sent! ID:", result.messageId);
  } else {
    console.error("Failed to send:", result.error);
  }
}

sendText();

Send to Multiple Recipients

async function sendBulk() {
  const recipients = ["1234567890", "0987654321", "1111111111"];

  const result = await client.send({
    to: recipients,
    text: "This is a bulk message!",
  });

  if (result.success) {
    console.log("Bulk message sent successfully!");
  } else {
    console.error("Failed:", result.error);
  }
}

sendBulk();

Send Message with Retry Logic

async function sendWithRetry(to: string, text: string, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    const result = await client.send({ to, text });

    if (result.success) {
      console.log("Message sent successfully!");
      return result;
    }

    console.log(`Attempt ${i + 1} failed:`, result.error);

    if (i < maxRetries - 1) {
      // Wait before retry (exponential backoff)
      await new Promise((resolve) =>
        setTimeout(resolve, 1000 * Math.pow(2, i))
      );
    }
  }

  console.error("All retry attempts failed");
}

sendWithRetry("1234567890", "Hello!");

Sending Attachments

Send Image from URL

async function sendImage() {
  const result = await client.send({
    to: "1234567890",
    attachment: {
      type: "image",
      url: "https://example.com/photo.jpg",
      caption: "Check out this photo!",
    },
  });

  if (result.success) {
    console.log("Image sent!");
  }
}

sendImage();

Send Document from Base64

import * as fs from "fs";

async function sendDocument() {
  // Read file and convert to base64
  const fileBuffer = fs.readFileSync("./report.pdf");
  const base64Data = fileBuffer.toString("base64");

  const result = await client.send({
    to: "1234567890",
    attachment: {
      type: "document",
      base64: base64Data,
      filename: "monthly-report.pdf",
      mimeType: "application/pdf",
      caption: "Monthly Report - January 2024",
    },
  });

  if (result.success) {
    console.log("Document sent!");
  }
}

sendDocument();

Send Video

async function sendVideo() {
  const result = await client.send({
    to: "1234567890",
    attachment: {
      type: "video",
      url: "https://example.com/video.mp4",
      caption: "Watch this video!",
    },
  });

  if (result.success) {
    console.log("Video sent!");
  }
}

sendVideo();

Send Audio File

async function sendAudio() {
  const result = await client.send({
    to: "1234567890",
    attachment: {
      type: "audio",
      url: "https://example.com/audio.mp3",
    },
  });

  if (result.success) {
    console.log("Audio sent!");
  }
}

sendAudio();

Send Image with Text

async function sendImageWithText() {
  const result = await client.send({
    to: "1234567890",
    text: "Here is the image you requested:",
    attachment: {
      type: "image",
      url: "https://example.com/image.jpg",
      caption: "Product photo",
    },
  });

  if (result.success) {
    console.log("Message with image sent!");
  }
}

sendImageWithText();

Advanced Examples

Send Messages from CSV File

import * as fs from "fs";
import { parse } from "csv-parse/sync";

async function sendFromCSV(csvPath: string) {
  const fileContent = fs.readFileSync(csvPath, "utf-8");
  const records = parse(fileContent, {
    columns: true,
    skip_empty_lines: true,
  });

  for (const record of records) {
    const { phone, message } = record;

    const result = await client.send({
      to: phone,
      text: message,
    });

    if (result.success) {
      console.log(`✓ Sent to ${phone}`);
    } else {
      console.error(`✗ Failed to send to ${phone}:`, result.error);
    }

    // Rate limiting: wait 2 seconds between messages
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
}

sendFromCSV("./contacts.csv");

Template Message Sender

async function sendTemplateMessage(
  recipients: string[],
  template: string,
  variables: Record<string, string>
) {
  for (const recipient of recipients) {
    // Replace template variables
    let message = template;
    for (const [key, value] of Object.entries(variables)) {
      message = message.replace(`{{${key}}}`, value);
    }

    const result = await client.send({
      to: recipient,
      text: message,
    });

    console.log(result.success ? "✓" : "✗", recipient);

    // Wait to avoid rate limiting
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
}

// Usage
sendTemplateMessage(
  ["1234567890", "0987654321"],
  "Hello {{name}}, your order {{orderId}} has been shipped!",
  {
    name: "John",
    orderId: "#12345",
  }
);

Message Queue System

interface QueuedMessage {
  to: string | string[];
  text?: string;
  attachment?: any;
}

class MessageQueue {
  private queue: QueuedMessage[] = [];
  private processing = false;

  constructor(private client: Whatify) {}

  add(message: QueuedMessage) {
    this.queue.push(message);
    if (!this.processing) {
      this.process();
    }
  }

  private async process() {
    this.processing = true;

    while (this.queue.length > 0) {
      const message = this.queue.shift()!;

      try {
        const result = await this.client.send(message);
        console.log(result.success ? "✓ Sent" : "✗ Failed:", result);
      } catch (error) {
        console.error("Error:", error);
      }

      // Wait 2 seconds between messages
      await new Promise((resolve) => setTimeout(resolve, 2000));
    }

    this.processing = false;
  }
}

// Usage
const queue = new MessageQueue(client);

queue.add({ to: "1234567890", text: "Message 1" });
queue.add({ to: "0987654321", text: "Message 2" });
queue.add({ to: "1111111111", text: "Message 3" });

Notification System

class NotificationService {
  constructor(private client: Whatify) {}

  async sendAlert(phone: string, title: string, message: string) {
    return await this.client.send({
      to: phone,
      text: `🚨 *${title}*\n\n${message}`,
    });
  }

  async sendSuccess(phone: string, message: string) {
    return await this.client.send({
      to: phone,
      text: `✅ ${message}`,
    });
  }

  async sendWarning(phone: string, message: string) {
    return await this.client.send({
      to: phone,
      text: `⚠️ ${message}`,
    });
  }

  async sendError(phone: string, message: string) {
    return await this.client.send({
      to: phone,
      text: `❌ ${message}`,
    });
  }
}

// Usage
const notifications = new NotificationService(client);

notifications.sendAlert(
  "1234567890",
  "Server Down",
  "Production server is not responding"
);
notifications.sendSuccess("1234567890", "Deployment completed successfully");

Scheduled Messages

import * as schedule from "node-schedule";

function scheduleMessage(cronExpression: string, to: string, text: string) {
  const job = schedule.scheduleJob(cronExpression, async () => {
    const result = await client.send({ to, text });
    console.log("Scheduled message sent:", result.success);
  });

  return job;
}

// Send message every day at 9 AM
scheduleMessage("0 9 * * *", "1234567890", "Good morning!");

// Send message every Monday at 10 AM
scheduleMessage("0 10 * * 1", "1234567890", "Weekly report");

Error Handling Best Practices

Comprehensive Error Handling

async function sendWithErrorHandling(to: string, text: string) {
  try {
    const result = await client.send({ to, text });

    if (!result.success) {
      if (result.error?.includes("Rate limit")) {
        console.log("Rate limited, waiting...");
        // Wait and retry
        await new Promise((resolve) => setTimeout(resolve, 60000));
        return sendWithErrorHandling(to, text);
      }

      if (result.error?.includes("not connected")) {
        console.log("Not connected, attempting to connect...");
        await client.connect();
        return sendWithErrorHandling(to, text);
      }

      console.error("Send failed:", result.error);
      return result;
    }

    console.log("Message sent successfully!");
    return result;
  } catch (error) {
    console.error("Unexpected error:", error);
    throw error;
  }
}

sendWithErrorHandling("1234567890", "Hello!");