DEV Community

Cover image for Whatsapp Bot in NodeJS: a step-by-step guide
WhatsApp API for developers
WhatsApp API for developers

Posted on • Updated on

Whatsapp Bot in NodeJS: a step-by-step guide

For those who don't have time to read:
Source code of a powerful WhatsApp bot on GitHub

Detailed step-by-step instructions on how to launch and configure the bot


Given today's emphasis on customer engagement, a WhatsApp bot can elevate user experience and boost business efficiency and sales. Dive into this detailed guide on creating a WhatsApp bot using Node.js.

Image description

Setting Up Your Development Workspace

Before delving into the world of code, it's vital to have the proper tools in place. Here's what you'll need and a step-by-step guide on setting everything up:

Prerequisites:

  • Node.js and npm: If they aren't already on your computer, you'll need to install both. They are available for download from the official Node.js site.
  • IDE: While any editor will suffice, IDEs like Visual Studio Code or WebStorm are recommended. They offer developer-friendly features such as auto-completion and debugging.
  • Terminal/Command Prompt: Essential for executing your Node.js scripts.

Connecting WhatsApp API provider

Whapi.Cloud is a gateway easing WhatsApp integration, allowing you to automate messaging without moderation and charging money for each message, as in Cloud API from Meta. While we'll explore methods for message handling in WhatsApp, the tool offers much more. Start Free Trial

Connecting to Whapi.Cloud:

  • Registration: Sign up at the Whapi.Cloud website for a free account without the need for credit card details.
  • Test Channel Access: Post-registration, you'll instantly get a limited test channel. Once initiated, you'll need to link your phone for automation and testing. Messages are dispatched from this connected device. The service's appeal lies in its rapid setup time.
  • Phone Connection: In your account, click on your trial channel to reveal a QR code. On your phone, access WhatsApp, navigate to Settings -> Connected devices -> Connect device -> Scan QR code.
  • Channel Settings: The platform prompts you to personalize your channel: naming it, configuring webhooks, and adjusting settings. While we'll skip them now, webhooks will be revisited. Your API KEY or Token, essential for API request authentication, is displayed in the central section. Depending on the API method, it can be included in the request headers as a Bearer Token or as a request parameter.

Image description

The Whapi.Cloud API provides a large number of methods for interacting with WhatsApp, effectively allowing you to automate almost every action and function of the messenger. You can view and test all methods on the channel page in your personal account, as well as in a very handy developer hub (offers code snippets for each function and the ability to test it immediately, showing both the result and the server response). The quick process of connecting and starting testing is a distinctive feature of Whapi.Cloud, allowing you to get started with WhatsApp within minutes.

Laying the WhatsApp Bot's Foundation

Initializing the Server with Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. We'll use it to initialize our server. Installation: If you haven't installed Express yet, you can do so with the following npm command.

npm install express --save

Initialize Your Server: Create a new file called index.js and initialize the Express server.

const express = require('express');
const app = express();
const port = 3000;

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

Basics of Asynchronous Programming in Node.js

Node.js is built on top of the V8 JavaScript engine, which is asynchronous and event-driven. Understanding the basics of asynchronous programming, such as callbacks, promises, and async/await, is essential for developing your bot.

async function fetchData() {
  const data = await getData();
  console.log(data);
}
Enter fullscreen mode Exit fullscreen mode

With these foundations laid, we'll move on to the specifics of message handling in the next chapter.

Handling Incoming Receive WhatsApp Messages

In this chapter, we will delve into the core part of any messaging bot — processing incoming messages. We'll cover how to set up a webhook, the basics of routing, and finally, the implementation of some elementary logic to respond to text messages.

Webhooks for WhatsApp API | How to receive incoming message | How to get the status of a message - YouTube

When developing a WhatsApp chatbot or integrating with any CRM, questions often arise: How to receive a message? How to process an incoming message? How to g...

favicon youtube.com

Your WhatsApp bot and API gateway need to communicate so that when something changes in one system, the other system knows about it. For example, tracking changes in the status of messages such as "sent", "delivered" and "read".

This is where a webhook comes to the rescue! A specially configured webhook allows your server to be instantly aware of certain events. Depending on your settings, you can receive notifications about messages, their status, channel status and even missed calls.

Image description

Whapi.Cloud provides the ability to set up a webhook for your bot. And it is possible to set up several Webhooks at once, for different events and with different conditions. This makes the work of programmers very easy.

Technically, upon receiving a message, the system will perform a POST request with a JSON body to the configured URL of your script. The JSON body will include all the information about the incoming message, such as text, sender's number, sending time, etc., allowing you to read this information on the fly.
Let's move on to setting up this URL!

Locally or on a Server

When developing a WhatsApp bot, you might want to test it locally before deploying it to a server. The simplest way to do this is to use tools like Ngrok, which creates a secure tunnel to your localhost, allowing you to provide access to your local server from the internet.

Let's take a test chatbot link from Ngrok right now. Download Ngrok from the official website and extract it. Open the terminal and navigate to the folder where Ngrok is stored.

Run ./ngrok http PORT_NUMBER, replacing PORT_NUMBER with the port your Express server is running on locally.
Now you should have a public URL that you can use as a URL for your webhook.

Features of Hosting on a Server

To receive incoming webhooks, it is necessary for the public IP address / host to be accessible from the internet. Thus, the Whapi.Cloud server will be able to send a request to your server at the specified address and deliver the incoming hook.

Server configuration:

  • Whapi.Cloud only works with webhooks that use HTTPS;
  • Your endpoint must accept POST/PUT/PATCH/DELETE;

Below, in the 'Deployment' chapter, we will talk about several publicly available services where you can host your chatbot.

Routing and Request Handling

For routing and request handling, we'll continue to use Express. The webhook URL that we provided in Whapi.Cloud will point to a specific route in our application.

const express = require('express');
const app = express();

app.use(express.json());

app.post('/webhook', (req, res) => {
  // Handle incoming messages
});

app.listen(3000, () => {
  console.log('Server started');
});
Enter fullscreen mode Exit fullscreen mode

Sample Message Format

When utilizing the Whapi.Cloud WhatsApp API and configuring a webhook URL, incoming messages are delivered in a well-defined JSON structure.

{
  "messages": [
    {
      "id": "IINCYddajIbJxaBbi0gwXQ-gOUSdTZG3w",
      "from_me": false,
      "type": "text",
      "chat_id": "15055913687@s.whatsapp.net",
      "timestamp": 1696502988,
      "text": {
        "body": "Hello"
      },
      "from_name": "Alexander"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Finally, let's add some basic logic to reply based on incoming text messages. For the sake of simplicity, we'll use a basic if-else structure, although you can later extend this to something more sophisticated.

app.post('/webhook', async (req, res) => {
  const message = req.body.message.text;

  if (message === 'hello') {
    await sendMessage('Hi there!');
  } else if (message === 'help') {
    await sendMessage('How can I assist you today?');
  }

  res.sendStatus(200);
});
Enter fullscreen mode Exit fullscreen mode

The sendMessage function will be a placeholder for now, which we'll replace in next Chapter with actual code to send messages.

Send WhatsApp message using Node JS

In this chapter, we will go through the nitty-gritty of sending text and media messages. Sending the right type of content at the right time can make your bot much more engaging. We will look at code snippets that will allow your bot to send text messages, media files, and even documents.

Sending Text Messages

Sending text messages is the most basic but essential feature. Below is a code snippet demonstrating how to send a text message using the Whapi.Cloud API. Here is this method with all the parameters and example answers in the documentation

const request = require('request');

const options = {
  method: 'POST',
  url: 'https://gate.whapi.cloud/messages/text?token=YOUR_API_TOKEN',
  headers: {accept: 'application/json', 'content-type': 'application/json'},
  body: {typing_time: 10, to: '1234567891@s.whatsapp.net', body: 'Hello, world!'},
  json: true
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
Enter fullscreen mode Exit fullscreen mode

Sending Multimedia, Documents

WhatsApp allows the sending of various types of media - images, audio, videos. You can submit a file by URL, or by uploading it to our storage. You can also send document files, such as PDFs or text files. Below is an example using a base64 encoded file.

const request = require('request');

const options = {
  method: 'POST',
  url: 'https://gate.whapi.cloud/messages/document?token=YOUR_API_TOKEN',
  headers: {accept: 'application/json', 'content-type': 'application/json'},
  body: {
    to: '1234567891@s.whatsapp.net',
    media: 'data:application/octet-stream;name=site.webmanifest;base64,ewogICAgIm5hbWUiOiAiIiwKICAgICJzaG9ydF9uYW1lIjogIiIsCiAgICAiaWNvbnMiOiBbCiAgICAgICAgewogICAgICAgICAgICAic3JjIjogIi9hbmRyb2lkLWNocm9tZS0xOTJ4MTkyLnBuZyIsCiAgICAgICAgICAgICJzaXplcyI6ICIxOTJ4MTkyIiwKICAgICAgICAgICAgInR5cGUiOiAiaW1hZ2UvcG5nIgogICAgICAgIH0KICAgIF0sCiAgICAidGhlbWVfY29sb3IiOiAiI2ZmZmZmZiIsCiAgICAiYmFja2dyb3VuZF9jb2xvciI6ICIjZmZmZmZmIiwKICAgICJkaXNwbGF5IjogInN0YW5kYWxvbmUiCn0K'
  },
  json: true
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
Enter fullscreen mode Exit fullscreen mode

Below, at the end of the article, we will publish the source code of the bot, which you can copy for your own work.

Working with WhatsApp Groups using Node.JS

In this chapter, we will explore how to interact with WhatsApp groups using the Whapi.Cloud API. Specifically, we will look at how to get the list of all groups, count the number of participants in each group, and handle messages coming from groups.

Getting the List of Groups

Firstly, to get the list of all the groups you are a part of, you can use the following code snippet:

const request = require('request');

const options = {
  method: 'GET',
  url: 'https://gate.whapi.cloud/groups?token=YOUR_API_TOKEN',
  headers: {accept: 'application/json'}
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
Enter fullscreen mode Exit fullscreen mode

The response will include an array of group details such as name, chat picture, last message, name of the owner, description, participants, and more.

Counting the Number of Participants in WhatsApp Group

Now that we have group details, we can go ahead and count the number of participants in each group. The following code snippet demonstrates this. In this code snippet, we loop through each group and log the group name and the number of participants it contains. The participants field is an array of objects, and we can get its length to count the number of participants.

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  const groups = JSON.parse(body);
  groups.forEach(group => {
    console.log(`Group Name: ${group.name}`);
    console.log(`Number of Participants: ${group.participants.length}`);
  });
});
Enter fullscreen mode Exit fullscreen mode

Handling WhatsApp Group Messages

To handle messages coming from groups, you can modify your webhook handler like so:

app.post('/webhook', (req, res) => {
  const message = req.body;

  if (message.from.endsWith('@g.us')) {
    // This is a group message
    handleGroupMessage(message);
  } else if (message.type === 'text') {
    // Handle Text Messages
    sendTextMessage(message.from, 'You said: ' + message.body);
  }

  res.status(200).end();
});

function handleGroupMessage(message) {
  console.log(`Received a group message from ${message.from}: ${message.body}`);
  // Further logic for group messages can be implemented here.
}
Enter fullscreen mode Exit fullscreen mode

In the updated webhook, we check whether the message.from field ends with @g.us, which is a typical identifier for group messages in WhatsApp. If it does, we call the handleGroupMessage function to handle the message. And there you have it! You now have a basic understanding of how to work with groups in WhatsApp using Whapi.Cloud. From here, you can extend the functionality as per your needs.

Try for free

Troubleshooting

Various issues can arise during the testing and operation of the WhatsApp chatbot. Here are a few typical situations and recommendations for their resolution:

The Bot Does Not Respond to Incoming Messages

  • Ensure you are sending messages to the number on which the bot is running from a different phone. The bot will not be able to respond to messages sent from the same number.
  • If the bot does not respond to messages from other numbers, check the operation of webhooks. Use services to simulate webhooks, for example, Webhook.site, to ensure which path the callback requests are coming through. Afterwards, check if the path matches the one you have configured. Also, ensure your server responds with 200Ok.

If you encounter difficulties, do not hesitate to contact our technical support for help. You can write in the web chat widget on our site or email care@whapi.cloud. We will assist you and figure out exactly what's wrong with the webhook.

The Bot Sends Messages Non-Stop

Return to the original version of the code. Our script includes a check to determine whether a message is incoming or outgoing, to prevent getting into an infinite loop of sending messages. Infinite sending may occur if there is no check for outgoing messages in the code, causing the bot to call itself, or if there is a cyclic sending of messages in the code.

The Bot Works in Some Chats, But Not in Others

Check your tariff plan on Whapi.Cloud. If you are using the trial mode or the "Sandbox" tariff, interaction is limited to a certain number of chats per month (currently up to 5 chats). In such a case, the bot will not be able to process messages in the sixth chat and subsequent ones.

It's important to remember that many issues can be prevented by carefully checking your chatbot's configuration and logic before launching. Regularly updating your code and paying attention to the details of settings can help avoid most typical errors. And our support team is always in touch and ready to assist you!

Deployment and Using Servers

To ensure your WhatsApp chatbot is available 24/7, it needs to be hosted on a reliable hosting platform. You can use your server, but in this chapter, we will consider the three most popular platforms - Firebase, AWS, and Heroku - and go through the basic steps of deploying your bot on each of them.

The choice of platform depends on your preferences, budget, and project requirements. Each of the considered platforms offers its unique features and advantages. Firebase and AWS Lambda provide powerful backend functionality without the need to manage a server, while Heroku offers simplicity in deploying applications based on Git.

Firebase

Firebase offers Cloud Functions functionality, allowing you to run your bot without worrying about server infrastructure. In our opinion, this is the most optimal option.

  1. Create a project in Firebase Console;
  2. Install Firebase CLI, following the instructions;
  3. Initialize Firebase in your project directory with the command firebase init;
  4. Deploy your bot using the command firebase deploy --only functions.

AWS (Amazon Web Services)

AWS Lambda offers the ability to run code in response to triggers from other AWS services, making it a good choice for a bot.

  1. Register or log in to AWS Management Console;
  2. Create a new Lambda function through the AWS console, selecting API Gateway as the trigger;
  3. Upload your bot's code into the Lambda function;
  4. Configure the API Gateway to interact with your bot and the outside world.

Heroku

Heroku offers an easy-to-use platform for hosting applications, which can automatically deploy code from your Git repository.

  1. Create an account on Heroku;
  2. Install Heroku CLI and log in;
  3. Create a new Heroku app through the console or using the command heroku create;
  4. Link your Git repository to Heroku and perform deployment with the commands git push heroku master;
  5. Set the webhook URL provided by Heroku.

Expanding Functionality

After successfully launching and testing your WhatsApp chatbot, there are numerous ways to further expand its functionality to make the bot even more useful and interactive for users. Here are some common use cases:

Sending files via link.

Sending a media file via a link is very simple. The main condition is that the file itself must be directly accessible via the link (which is why Cloud services like Google Drive or Dropbox do not work as they do not provide direct file access). Use the media parameter in any of the methods that allow sending media files. Read more in our article: Endpoint for sending a media file.

Distributing leads among groups.

You will need the group creation function, as well as adding a participant to the group. Adding a participant to a group is straightforward, but there are some nuances. We described in detail in the article: "Adding a new member to a group"

CRM Integration with WhatsApp.

Technically, CRM integration is not much different from a chatbot, except that it adds an additional resource with its own API that needs to be utilized. Add functions that allow users to book services, order products, or receive up-to-date information from external sources in real time.

WhatsApp API Full Documentation

Surveys as an alternative to buttons.

Interactive buttons in WhatsApp are a very convenient tool for customer engagement. However, this feature is not available to most WhatsApp users. We advocate for making communication with users easier, so we offer you a convenient alternative - using surveys as buttons. Detailed article with NodeJS source code and how to use it.

Increasing customer engagement.

Use stories, change your number statuses, put likes and other emojis on your customers' messages, send voice messages - increase engagement in customer service.

Checking for WhatsApp availability on a number.

Check whether a given phone number exists on WhatsApp or not. Determine which phone numbers are active and which cannot receive WhatsApp messages. Integrate into your application before making a broadcast! Source code on GitHub and instructions here.

We provide comprehensive support to our clients! If you have any questions about bot operation, platform setup, or encounter technical difficulties, you can always count on our help.

We hope this guide will help you successfully launch your WhatsApp chatbot. Good luck in your endeavors!

Image description

Source code of ready-made simple WhatsApp bot Node.JS

Here is an example of a complete code to create a simple WhatsApp bot using Node.js and Express. This code includes server initialization, handling incoming messages via webhook and sending text and media messages.

Source code of a powerful WhatsApp bot on GitHub

Thanks to its vast feature suite, your bot creation journey is simplified. Your Node.JS bot can be effortlessly amalgamated into various platforms, including websites, apps, CRMs, ERPs, and more.

Image description

Try for free

Top comments (3)

Collapse
 
whapicloud profile image
WhatsApp API for developers

Step-by-step instructions on how to set up and run this chatbot: whapi.cloud/setting-up-chatbot-wha...
We'll talk in detail about how to test the bot on a local, which servers to use, some tips and the main causes of popular failures.

Collapse
 
whapicloud profile image
WhatsApp API for developers • Edited

Made by developers for developers <3
WhatsApp API Platform

For DEV Community members we will be ready to make a discount :) While we are developing a system of promo codes, but if someone is interested, just write in the support chat that you are from here and you will get a 20% discount on the first payment

Collapse
 
whapicloud profile image
WhatsApp API for developers

Uploaded the source code of a powerful bot on GitHub (NodeJS)
github.com/Whapi-Cloud/nodejs-what...