← Back to Home

Code Snippets

Copy-paste ready code examples for common X-Asena operations. All snippets are TypeScript compatible.

Send Text Message

Send a simple text message to a WhatsApp user.

typescript
// Send a text message
await message.sendText("Hello! Welcome to our service.");

// With reply context (replies to the incoming message)
await message.sendText("Thanks for your message!", { reply: true });

// Send to a specific user
await message.sendText("Hi there!", { id: "919876543210" });

Send Media

Send images, videos, documents, or audio files.

typescript
// Send media from URL
await message.sendMedia("https://example.com/image.jpg");

// Send with caption
await message.sendMedia("https://example.com/photo.png", {
  caption: "Check out this image!"
});

// Send from Buffer
const imageBuffer = fs.readFileSync("./path/to/image.jpg");
await message.sendMedia(imageBuffer, { caption: "Local image" });

Send Button Message

Send interactive button messages for quick user responses.

typescript
// Send a message with buttons
await message.sendButtonText({
  text: "How can we help you today?",
  buttons: [
    { id: "btn_support", title: "Get Support", type: "reply" },
    { id: "btn_info", title: "Learn More", type: "reply" },
    { id: "btn_contact", title: "Contact Us", type: "reply" }
  ]
});

Send Button with Media

Combine media with interactive buttons.

typescript
// Send media with buttons
await message.sendButtonMedia({
  text: "Check out our new product!",
  media: "https://example.com/product.jpg",
  footer: "Tap a button to learn more",
  buttons: [
    { id: "buy_now", title: "Buy Now", type: "reply" },
    { id: "details", title: "View Details", type: "reply" }
  ]
});

Send List Message

Send interactive list messages with multiple sections.

typescript
// Send a list message
await message.sendList({
  header: "Our Services",
  body: "Choose a category to explore:",
  footer: "Tap the button to see options",
  button: "View Options",
  sections: [
    {
      title: "Products",
      rows: [
        { id: "prod_1", title: "Electronics", description: "Phones, laptops, accessories" },
        { id: "prod_2", title: "Clothing", description: "Men's and women's fashion" }
      ]
    },
    {
      title: "Support",
      rows: [
        { id: "sup_1", title: "Track Order", description: "Check your order status" },
        { id: "sup_2", title: "Returns", description: "Return or exchange items" }
      ]
    }
  ]
});

Parse Incoming Messages

Extract message details from webhook payloads.

typescript
// The Base class automatically parses incoming messages
// Access parsed data via these properties:

message.id          // Message ID
message.type        // "message" or "status"
message.messageType // "text", "image", "interactive", etc.
message.messageBody // Message content
message.userName    // Sender's WhatsApp profile name
message.userId      // Sender's WhatsApp ID
message.timestamp   // Message timestamp

// For button responses
message.button_id   // ID of the clicked button

// For list responses  
message.button_id   // ID of the selected list item
message.description // Description of selected item

Handle Button & List Responses

Process user selections from interactive messages.

typescript
// In your plugin handler
export default async function handler(message) {
  // Check if this is a button/list response
  if (message.button_id) {
    switch (message.button_id) {
      case "btn_support":
        await message.sendText("Our support team will contact you shortly.");
        break;
      case "btn_info":
        await message.sendText("Visit our website: https://example.com");
        break;
      case "buy_now":
        await message.sendText("Redirecting to checkout...");
        break;
      default:
        await message.sendText("Thanks for your selection!");
    }
  }
}

Upload Media

Upload media files to WhatsApp for later use.

typescript
// Upload media and get the media ID
const { id, mediaType } = await message.uploadMedia(
  "https://example.com/document.pdf"
);

console.log(`Uploaded ${mediaType} with ID: ${id}`);

// You can also upload from Buffer
const buffer = fs.readFileSync("./local-file.png");
const result = await message.uploadMedia(buffer);

Delete Uploaded Media

Remove previously uploaded media from WhatsApp servers.

typescript
// Delete media by ID
const mediaId = "1234567890";
const result = await message.deleteMedia(mediaId);

if (result.success) {
  console.log("Media deleted successfully");
}

Webhook Verification

Handle Meta's webhook verification challenge.

typescript
// Express.js webhook verification endpoint
app.get("/webhook", (req, res) => {
  const mode = req.query["hub.mode"];
  const token = req.query["hub.verify_token"];
  const challenge = req.query["hub.challenge"];

  if (mode === "subscribe" && token === process.env.WEBHOOK_VERIFY_TOKEN) {
    console.log("Webhook verified successfully");
    res.status(200).send(challenge);
  } else {
    res.sendStatus(403);
  }
});

// Handle incoming webhooks
app.post("/webhook", async (req, res) => {
  try {
    const message = new Base(req.body);
    
    if (message.type === "message") {
      // Process the message
      await handleMessage(message);
    }
    
    res.sendStatus(200);
  } catch (error) {
    console.error("Webhook error:", error);
    res.sendStatus(500);
  }
});

Need More Examples?

Check out the source code for more implementation details.

View Source Code