DEV Community

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

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.

Since replies are in JSON format, you can easily extend the capabilities of your bot.
In the documentation and in the Developer Hub, we've laid out full details of what kind of response with what parameters you should expect for any request. A list of all parameters is available in the documentation. Use this data to extend your functionality!

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

Testing

As you craft your bot, testing it in a local environment before a full-scale server deployment is crucial. Utilizing tools like ngrok can effortlessly establish a secure connection to your localhost, making your local server accessible online.

To set up ngrok:

  • Download and extract ngrok.
  • Access your terminal and move to the ngrok directory.
  • Execute ./ngrok http PORT_NUMBER, substituting PORT_NUMBER with your local Express server's port.
  • You now have a global URL, fit to be your webhook URL on the Whapi.Cloud panel.

Deployment & Hosting

With your bot tried and tested, it's time for deployment. Popular hosting options include AWS, Heroku, among others. Below is a concise guide to deploy your bot on Heroku:

  1. Heroku Setup: Install the Heroku CLI and sign in.
  2. Project Directory: Access your project's folder. If not already done, initialize a git repository.
  3. New Heroku App: Execute heroku create to instantiate a fresh Heroku application.
  4. Code Deployment: Deploy your code to Heroku via git push heroku master.
  5. Environment Variables: In your Heroku dashboard, go to your app's settings and input relevant environment variables, including the Whapi.Cloud API token.
  6. Webhook Configuration: Finally, on the Whapi.Cloud dashboard, assign the webhook URL to the one provided by Heroku.

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

In this code sample:

  • We initialize the server with Express and install a webhook to handle incoming messages.
  • When a text message is received, the bot responds by repeating the received text.
  • We create a group and show how to send different types of messages

Please replace YOUR_API_TOKEN with your real API token from Whapi.Cloud. This code is a basic example and can be augmented with other functions and handlers to create more complex and interactive bots.

Conclusion and Next Steps

Kudos on crafting your WhatsApp bot! This guide has walked you through the foundational steps in setting up a bot harnessing Node.js, Express, and Whapi.Cloud API. With this rudimentary bot in hand, you're now poised to expand its capabilities tailored to your unique requirements.

Dive into our comprehensive documentation, where you'll discover intricate steps and illustrative examples on sending diverse message formats - be it files, locations, stickers, or even polls. Moreover, it empowers you to interact dynamically with messages, from marking them as read to simulating real-time typing.

Group management is a breeze as well. Modify avatars, adjust names, onboard new members, or block intruders with ease.

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

Kickstarting with this bot is plug-and-play. Begin by registering with our platform, leveraging the free trial to gauge its comprehensive offerings. Once onboarded, deploy the bot code on your server. Adhering to this guide ensures your bot springs to life swiftly.

Should you hit a snag or have a query, remember, our dedicated support team is just a message away. Your seamless experience with our API is our utmost priority.

Try for free

Top comments (2)

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...