Running WhatsApp bot on Node.js
Tags: beginners, tutorial, node, whatsapp
Published: 2024-04-01 10:40:36

_Bot source code and step-by-step guide for setup and launch. Key features: sending messages to private chats and groups, creating groups, sending media files and products, receiving and reading messages, server tips_


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7s8821gmny4usakavlea.png)

## Introduction
A WhatsApp chatbot allows automatic responses to requests, sending notifications, requesting information, making communication efficient and available 24/7.

This guide for programmers is a step-by-step instruction on setting up and launching your own chatbot using the Whapi.Cloud API on Node.JS, as well as demonstrating the key functions and capabilities of the gateway and bot.

You will be able to use our source code in your project, easily modifying and supplementing the script's functionality. Based on the code, you can create your chatbot or any integration. Easily integrate it into existing workflows, continuing to use WhatsApp as usual!

[A short video demonstration of the bot in action](https://youtube.com/shorts/7tC0mvkn8fY)

## Source Code
The script of this chatbot includes basic functions that are often used by small and medium businesses and covers most tasks:

- Sending a plain message;
- Sending media: image / file / video;
- Sending a contact (vCard);
- Sending a product;
- Creating a WhatsApp group;
- Sending a group invitation;
- Sending a message to a WhatsApp group;
- Receiving and processing incoming messages;
- Responding to an unknown command (for implementing menus, instructions, or a welcome message).

GitHyb: [https://github.com/Whapi-Cloud/nodejs-whatsapp-chatbot](https://github.com/Whapi-Cloud/nodejs-whatsapp-chatbot)

## WhatsApp API Provider
Whapi.Cloud provides an easy-to-use API gateway compatible with any programming language. This allows you to integrate your website, store, app, or CRM with WhatsApp seamlessly.

Our Cloud API is an independent development and has no restrictions for working with sending messages, groups, channels, statuses, calls, and other functionalities of your messenger. Additionally, access to the API has a fixed price, and no charges are made for sent messages. This is a key advantage of our simple and powerful API.

### How to Connect to Whapi.Cloud
Another advantage of our gateway is the speed of onboarding and startup. You will not need to undergo business verification or change your number. Connect your own number and continue using WhatsApp as usual!

So, [register at Whapi.Cloud](https://panel.whapi.cloud/register). You will need a valid email address to pass email verification or a Google account.

On the Dashboard, you will find a trial channel individually allocated for you. For the first 5 days, you will have the opportunity to test all the API functionality completely free.


![Free access to the API for 5 days](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f91n55v2fs7qmj2400o1.png)

Navigate to the page of this channel by simply clicking on it.

Unlike other providers, we give you the opportunity to connect your existing WhatsApp or WhatsApp Business to the API. Simply scan the QR code as you do in WhatsApp Web, and you'll be ready to go in a few seconds. From Meta's perspective, this is a standard connection to WhatsApp Web, and if you do not use Whapi.Cloud for spamming, your number will continue to work in the usual manner.

Skip the third step 'Channel Settings', as we won't need them right now.

Great, now you have access to the **API Token**, which will be required for testing and further work with the endpoints. Save this token, as it will come in handy more than once.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ighf3srh3ib1avpp31x.png)

Let's move to _config.js_ and replace the token variable by inserting your current key:
`token: "YOUR_CHANNEL_TOKEN"`

## Webhook Configuration

### What is a Webhook and Why is it Needed
To receive incoming data from your messenger, such as an incoming message or incoming call or a notification that someone has joined your group, you will need to use a Webhook.

This technology will allow you to instantly receive notifications about any event in your WhatsApp and respond to it.

In simple terms, for example: Contact A sent you a message -> The chatbot script received a message from Contact A -> Checked if this message is a command it recognizes -> Executed the script command (for example, sent a welcome message or sent a product, etc.)

Thus, the two systems (our API gateway connected to WhatsApp and your chatbot) exchange information without the need for any external actions.

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.

Copy this link into the config.js file:
`botUrl: "https://84c7-151-33-282-113.ngrok-free.app/hook"`

Attention, leave “/hook” at the end of the link! The chatbot script is currently programmed to this address!

{% embed https://www.youtube.com/watch?v=gql85pOlYs4 %}

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

### Configuration and Various Events
Channel and webhook settings in Whapi.Cloud offer extensive customization options that can be particularly useful in projects with individual requirements.

However, to simplify the launch process, we have included the installation of necessary settings directly in the code of our chatbot, freeing you from the need to enter them manually. This allows you to focus on development without worrying about additional configuration.

If you want to delve into customization options or need more detailed webhook setup, you can always consult the full list of options in the Whapi.Cloud Knowledge Base in the article: [Detailed Webhook Settings](https://support.whapi.cloud/help-desk/receiving/webhooks/detailed-webhook-settings)


![Example of webhook settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hmjghfuj4xygx4t4hugr.png)

[In the source code from GitHub](https://github.com/Whapi-Cloud/nodejs-whatsapp-chatbot), the webhook link is automatically assigned to your channel through an API method, so no further action is required on your part. Let's dive a bit deeper into webhook modes and the events about which our service can notify you.

Currently, for sending a webhook, the `Method` mode is selected. This method is particularly suited for detailed event handling, allowing the use of different HTTP methods for specific actions. Thus, the webhook will differentiate the sent requests and send them to different addresses, for example, _https://****/hook/messages_ (events related to messages) or _https://****/hook/statuses_ (events related to message statuses) or _https://****/hook/groups_ (events related to groups).
There are two more modes for the webhook: `Body` (directly sends the request body to the link) and `Path` (fully specifies the API URL request).

The event and the way we notify the original chatbot is POST Messages. This webhook tracks any changes related to new messages, including sent messages and incoming messages.

Learn more about all the possible events (receiving information about groups, channels, calls, statuses, message changes, etc.), supported by our system, in the article: [Our Webhooks (Tracked Events)](https://support.whapi.cloud/help-desk/receiving/webhooks/our-webhooks-tracked-events)

## Launching and Configuring the Bot
Right now, you can test the chatbot! Make sure that the token and webhook address in config.js are correctly specified.

Launching the chatbot is done by running the command `node index.js` in the terminal from the project's root directory. Your bot should now be active and ready to operate.

By sending a message to the number to which the bot is linked from another phone, you should receive an automatic response. If the bot does not react, we recommend referring to the 'Troubleshooting' section for diagnostics and resolving potential issues.

## Predefined Settings (Group and Product)
The _config.js_ file contains preset values, including group and product identifiers, which your chatbot uses for sending messages. To ensure the bot operates correctly in the context of your data, it's necessary to update these parameters according to your needs.

- group: '120363167596599603@g.us'
- product: '6559353560856703'

The first identifier is for the group to which the chatbot will send the message. You can obtain this identifier by creating a group in WhatsApp or using an existing one. The group identifier can only be obtained through the API.

For this, use the API call '**Get Group List**' (method: [https://whapi.readme.io/reference/getgroups](https://whapi.readme.io/reference/getgroups) in Documentation). The group identifier looks like this: _120363194020948049@g.us_

So, once you've found the group identifier you need, now copy it into config.js.

Do the same with the products from your catalog (available only in the Business version of the app). Determine the product identifier that will be sent by your chatbot. You can get a list of products using the method [https://whapi.readme.io/reference/getproducts](https://whapi.readme.io/reference/getproducts) in Documentation.

Replace the preset values in config.js with your group and product identifiers. After making changes, save the file and restart the bot. It should now function using the new parameters, allowing you to fully test its operation.

## 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](https://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](https://firebase.google.com/docs/cli);
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](https://support.whapi.cloud/help-desk/sending/send-video-audio-image-document).

### Distributing leads among groups.
You will need the [group creation function](https://whapi.readme.io/reference/creategroup), 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"](https://support.whapi.cloud/help-desk/groups/add-new-member-to-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](https://whapi.readme.io/reference/sendmessagetext)

### 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](https://support.whapi.cloud/help-desk/hints/how-to-use-polls-as-buttons).

### Increasing customer engagement.
Use [stories](https://whapi.readme.io/reference/createstory), 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](https://support.whapi.cloud/help-desk/source-code/whatsapp-phone-number-checker).

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!

The original article: https://whapi.cloud/setting-up-chatbot-whatsapp-nodejs