Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

node-whatsapp-bot-api

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

node-whatsapp-bot-api

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.

  • 1.4.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3
decreased by-78.57%
Maintainers
1
Weekly downloads
 
Created
Source

Checks npm type definitions stable

# WhatsappBot

The WhatsappBot is a JavaScript class that represents a WhatsApp bot. It provides functions for sending text 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. 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:

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:

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

Please note that the checklist is currently marked as incomplete for most items, indicating that only sending text messages is implemented.


Initiating 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;

This is an example of how to initialize the WhatsappBot instance and handle incoming text messages. 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.

Keywords

FAQs

Package last updated on 08 Jul 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc