DEV Community

GathuaKiragu
GathuaKiragu

Posted on

Building a Chatbot with NodeJS

Building a WhatsApp Chatbot using Node.js
WhatsApp is one of the most popular messaging apps in the world, with over 2 billion monthly active users. As a business, being able to reach and communicate with your customers through WhatsApp can be a game-changer. One way to do this is by building a chatbot that can automatically respond to customer inquiries and requests.

In this tutorial, we will show you how to build a simple WhatsApp chatbot using Node.js. We will be using the Twilio API for WhatsApp to send and receive messages from your chatbot.

Prerequisites
Before we get started, you will need the following:

A Twilio account and a WhatsApp sandbox: You can sign up for a Twilio account here and set up a WhatsApp sandbox here.
Node.js and npm: You can download and install Node.js here and npm will be installed along with it.
A text editor: We recommend using Visual Studio Code, but you can use any text editor of your choice.
Setting up your project
First, create a new folder for your project and navigate to it in your terminal. Then, run the following command to create a package.json file:

npm init -y

This will create a package.json file with default values. Next, we will install the required dependencies for our project. Run the following command to install the Twilio npm package:

npm install twilio

This will install the Twilio library that we will use to send and receive messages from our chatbot.

Sending a message from your chatbot
Now that we have everything set up, let's write some code to send a message from your chatbot.

First, require the Twilio library in your project:

const twilio = require('twilio');

Next, set up your Twilio credentials and the phone number that you will be sending the message from (which should be the phone number you registered with your WhatsApp sandbox). You can find your Twilio Account SID and Auth Token in the Twilio Console.

const accountSid = 'your-twilio-account-sid';
const authToken = 'your-twilio-auth-token';
const fromNumber = 'your-twilio-phone-number';
Enter fullscreen mode Exit fullscreen mode

Now, let's create a function that sends a message to a given phone number:

function sendMessage(toNumber, message) {
  const client = new twilio(accountSid, authToken);
  client.messages
    .create({
      body: message,
      from: fromNumber,
      to: toNumber
    })
    .then(message => console.log(message.sid))
    .done();
}
Enter fullscreen mode Exit fullscreen mode

To test this out, call the sendMessage function from whatsapp.

Top comments (0)