DEV Community

Cover image for Running WhatsApp bot on Node.js
WhatsApp API for developers
WhatsApp API for developers

Posted on

Running WhatsApp bot on Node.js

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

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

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

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

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

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!

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

Example of webhook settings

In the source code from GitHub, 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)

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.

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 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 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, 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!

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

Top comments (3)

Collapse
 
whapicloud profile image
WhatsApp API for developers

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
 
gusmagnago profile image
Gustavo Magnago

Hello! I am developing a product, where my user would like to have the ability to send temple messages to their customers like notifications, payment reminders and pdf. But, is it possible for us to set their own phone numbers as sender? I know that’s tricky because of security reasons, but they think that sending from a different number would mess their customers head and would bring even more second work in it.
Thanks for your post anyway

Collapse
 
whapicloud profile image
WhatsApp API for developers

Yes, it's possible. However, it is worth warning them that their number will be connected to the API.
You can use the endpoint of receiving QR code and OTP code so that they can remotely connect their number to the channel.