Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
node-whatsapp-bot-api
Advanced tools
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.
# 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
To use the WhatsappBot
class in your JavaScript or TypeScript code, follow these steps:
Import the WhatsappBot
class:
import WhatsappBot from "whatsapp-bot";
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.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.
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.
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.
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.
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.
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.
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.
This project is licensed under the MIT License.
Please note that the current functionality of the WhatsappBot
class is as follows:
sendTextMessage
method.
sendTextListMessage
method.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.
FAQs
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.
We found that node-whatsapp-bot-api demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.