npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node-whatsapp-bot-api

v1.5.0

Published

WhatsApp Bot that can be used as middleware to emit events to listeners. Listeners can react to incoming messages. Additionally, the WhatsApp bot can send messages if a WhatsApp Cloud API token is provided.

Downloads

65

Readme

Checks npm type definitions stable

# WhatsappBot

The `WhatsappBot` class is a JavaScript class that represents a WhatsApp bot. It provides functions for sending text and list messages using the WhatsApp API and extends the `EventEmitter` class to handle event-based communication.

## Installation

To use the `WhatsappBot` class, you need to have Node.js installed. You can install the package using npm or yarn:

```shell
npm install whatsapp-bot

or

yarn add whatsapp-bot

Usage

To use the WhatsappBot class in your JavaScript or TypeScript code, follow these steps:

  1. Import the WhatsappBot class:

    import WhatsappBot from "whatsapp-bot";
  2. Create an instance of the WhatsappBot class:

    const whatsappBot = new WhatsappBot(
      process.env.USER_ACCESS_TOKEN,
      process.env.PHONE_NUMBER_ID
    );
    • process.env.USER_ACCESS_TOKEN (string): The user access token for authentication.
    • process.env.PHONE_NUMBER_ID (string): The phone number ID associated with the bot.
  3. Send a text message using the sendTextMessage method:

    whatsappBot.sendTextMessage(textMessage, to);
    • textMessage (string): The text message to send.
    • to (string): The recipient of the message.

    This method sends a text message using the WhatsApp API. If sending the message fails, an error will be logged.

  4. Send a text list message using the sendTextListMessage method:

    whatsappBot.sendTextListMessage(
      ctaText,
      sections,
      body,
      to,
      header,
      footer
    );
    • ctaText (string): The text to be displayed on the list button.
    • sections (Array): An array of section items that make up the list message.
    • body (IMessageBody): The main body text of the list message.
    • to (string): The recipient of the message (WhatsApp phone number).
    • header (Optional) (IMessageHeader): The header section of the list message.
    • footer (Optional) (IMessageFooter): The footer section of the list message.

    This method sends a WhatsApp text list message with interactive sections to the specified recipient. If there's an issue with sending the message, an error will be thrown.

  5. Subscribe to events using the on method:

    whatsappBot.on(eventName, listener);
    • eventName (string): The name of the event you want to listen to.
    • listener (function): The listener function to be called when the event is triggered.

    You can register event listeners to handle specific events emitted by the WhatsappBot instance.

Middleware

To handle events and messages received by the WhatsappBot, you can use the provided middleware function. Here's an example implementation with Express:

import express from "express";
import whatsappBot from "./path/to/whatsappBot"; // Import your WhatsappBot instance

const router = express.Router();

router.post("/", (req, res, next) => {
  whatsappBot.middlewareHandlerForWebhookMessagesPayload(req, res, next);
});

// Next middleware if there is one.

export default router;

Make sure to bind the whatsappBot.middlewareHandlerForWebhookMessagesPayload method to the whatsappBot instance.

Error Handling

The WhatsappBot class emits an "error" event when an error occurs. You can subscribe to this event to handle errors:

whatsappBot.on("error", (error) => {
  console.log(error);
});

This allows you to handle errors gracefully and take appropriate actions.

Custom Logging

The WhatsappBot class uses the Winston logging library for logging. By default, it uses a default logger configuration provided by the package. However, you can specify a custom Winston logger during instantiation to customize the logging behavior:

import WhatsappBot from "whatsapp-bot";
import winston from "winston";

const customLogger = winston.createLogger({
  // Your custom logger configuration
});

const whatsappBot = new WhatsappBot(
  process.env.USER_ACCESS_TOKEN,
  process.env.PHONE_NUMBER_ID,
  {
    customWinstonLogger: customLogger,
  }
);

You can create your own custom logger using the winston.createLogger method and pass it as the customWinstonLogger option in the configuration object.

Contribution

Contributions are welcome! If you find any issues or have suggestions for improvement, please create an issue or submit a pull request in the GitHub repository.

License

This project is licensed under the MIT License.

Functionality Checklist

Please note that the current functionality of the WhatsappBot class is as follows:

  • [x] Sending text messages using the sendTextMessage method

.

  • [x] Sending text list messages using the sendTextListMessage method.
  • [ ] Sending media messages (e.g., images, videos).
  • [x] Webhook verification middleware.
  • [x] Handling incoming messages and events from the WhatsApp API.
  • [x] Error handling and logging for failed message sending.
  • [x] Configuring a custom Winston logger for logging.
  • [x] Subscribing to and handling events using the on method.

Please note that the checklist is currently marked as incomplete for some items, indicating that they are not fully implemented yet.


Example initialization and usage of WhatsappBot:

import WhatsappBot from "whatsapp-bot";
import { SupportedWhatsappMessageTypes } from "whatsapp-bot";

const whatsappBot = new WhatsappBot(
  process.env.USER_ACCESS_TOKEN,
  process.env.PHONE_NUMBER_ID
);

whatsappBot.on(SupportedWhatsappMessageTypes.TEXT, (textMessage) => {
  whatsappBot.sendTextMessage(textMessage.text.body, textMessage.from);
});

whatsappBot.on("error" as SupportedWhatsappMessageTypes.TEXT, (error) => {
  console.log(error);
});

export default whatsappBot;

In this example, the WhatsappBot instance is initialized with access tokens, and event listeners are set up to handle incoming text messages and errors. You can modify the code to suit your specific use case and handle other types of messages and events.


Example implementation of an Express router using WhatsappBot:

import express from "express";
import { verifyWebhook } from "../controllers/webhookController";
import whatsappBot from "../utils/whatsappBot/init";

const router = express.Router();

// Handle the GET request on the "/webhook" endpoint.
// Verify the callback URL from the dashboard side (Cloud API side).
router.get("/", (req, res, next) => {
  whatsappBot.middlewareHandlerForWebhookVerification(req, res, next);
  // Next middleware if there is one.
});

// Handle events, e.g., receive messages.
router.post("/", (req, res, next) => {
  whatsappBot.middlewareHandlerForWebhookMessagesPayload(req, res, next);
  // Next middleware if there is one.
});

export default router;

In this example, an Express router is created to handle the /webhook endpoint. The whatsappBot.middlewareHandlerForWebhookVerification middleware is used to verify the callback URL, and the whatsappBot.middlewareHandlerForWebhookMessagesPayload middleware is used to handle events, such as receiving messages. Make sure to bind these methods to the whatsappBot instance.

Feel free to modify the code based on your specific requirements and use cases.


With this update, the `sendTextListMessage` function is now part of the documentation, and developers will be able to use the updated documentation to understand and utilize the new function effectively.