Create a Simple Chatbot Using the Vonage Messages API

Shreyas Sreenivas
The Startup
Published in
8 min readNov 14, 2020

--

Unlike my previous two posts, this is not about the website I built, but an API I found out about during Hacktoberfest.

If you don’t know what Hacktoberfest is, it’s this month long celebration of open source in the month of, you guessed it, October. Even though I started late, it was probably one of the best experiences I’ve had so far. Interacting with the community on Discord, joining them on Twitch streams and what not. One of the sponsors of Hacktoberfest happened to be Vonage. A company I had never heard of before, but have probably some of the nicest and coolest employees, developers and community. Unfortunately, I was not able to try out their product during the month of October even though I wanted to.

Vonage is a company that makes a bunch of communication API’s. Communication API’s let you easily add Messaging or Video conferencing to your applications or make it easy to set up two factor authentication and services that require you to interact on SMS, WhatsApp, Messenger etc.

A week and a half after the end of Hacktoberfest, I finally spared some time to try out their API. Their website, including their documentation, probably has the best User Interface and User Experience on any website I’ve visited, it’s just so good! They also have many good tutorials on their site, but I’m writing this anyway.

What we’re going to be building

If you thought we were going to be building some cool bot which has Natural Language Processing Involved, I’m sorry to dissapoint you because all we’ll be doing is creating a simple webhook which responds with “hi” whenever you tell “hey there!” on WhatsApp, Facebook Messenger or any of the other services the Messages API supports and testing it out using something called ngrok. We’ll be building the application using node and express.

Setup a Vonage account

Before we write any code, we need to set up an account on Vonage. To do that you sign up at https://dashboard.nexmo.com/sign-up, no credit card required. You also get credit worth 2 euros but don’t worry we won’t be spending any of those credits today.

But before we get started, what is the Vonage Messages API?

The Messages API allows you to send and in some cases receive messages over SMS, MMS, Facebook Messenger, Viber, and WhatsApp.

Creating the webhooks

What are webhooks? In short webhooks are callbacks to events that happen in some other application or another part of the same application. A webhook is triggered whenever a certain event or action occurs. In our case, the webhook we’ll be creating will be triggered by Vonage whenever a message is sent to the corresponding platform we choose. This may sound confusing right now but bear with me till the end of this.

Initial setup

Let’s create a folder named hello-vonage and run npm init -y in it since we’ll be using node. Once that’s done let’s install expressand thebody-parse middleware to easily read the body of the request by running npm install express body-parser. If you prefer you can use Typescript as well, but in this case, it doesn’t make much of a difference.

Once we have everything installed, we can go ahead and set up our express application by creating app.js with the below code

The webhooks itself

The Vonage Messages API requires us to expose two webhooks, one as a callback to any messages received or the inbound message webhook and another which is a callback to updates on the status of a sent message or the message status webhook. An example of when the message status webhook is called is when a message you sent using the API is delivered to a user, or read by them.

First the inbound webhook.

Here, we’re indicating that the inbound webhook is at to webhooks/inbound and is handled by the handleInbound function. For now, let’s just console.log the body of the request. The Vonage Messages API also requires us to always send a 200 whenever a request is sent the webhooks and that’s exactly what we’re doing.

Next, the status webhook.

Just like before, we’re just logging the body of the request and sending a 200 response to the request. Before we go ahead and write any logic for our app let’s see how we can test our webhooks and see them in action.

At this point, your app.js should like somethings like this

To test our webhooks we’ll be using two tools, namely the Vonage sandbox and another tool called ngrok.

Testing with ngrok

To test our webhooks, it needs to be accessible via a URL to Vonage and the only way to do that is to expose our node server to the internet. But we can’t just expose our computer to the internet, can we. That’s where a tool called ngrok comes in. Ngrok generates a one time public URL and routes that URL to a port on your local server.

To get started with it, head over to https://ngrok.com and create an account. Once you’ve created an account, you should be redirected to the dahsboard from where you should be shown instruction to install and setup ngrok (it should probably take 2–3 minutes).

Okay, now that we’ve got ngrok set up, let’s start our node server by running node app.js and start ngrok by running ngrok http 3000. This command is just telling to ngrok to create a URL and route it port 3000 on localhost . Ngrok should generate and display public URL which should look something like https://asdfas23as.ngrok.io. It might show you two different URLs, one with http and one https , you can use either since this is just for testing but I suggest you use the https URL anyways.

What this means is, we can access http://localhost:3000/webhooks/inbound from https://1f34b279009.ngrok.io/webhooks/inbound . I know, it’s awesome right?!

Creating the sandbox

A sandbox is just a place to test our application. In this case it’s either WhatsApp, Facebook Messenger or Viber. We’ll just go ahead and make a sandbox on WhatsApp because I don’t use the others, but the process should be the same if you’d like to try them out.

To create a sandbox, go to your Vonage Dashboard and under the Messages and Dispatch section and click on sandbox. Under the WhatsApp section, click add to sandbox.

Remember that the route for the inbound message hook is /webhooks/inbound and for the status hook it is /webhooks/status . Scroll down and you should see a section titled Webhooks. In the text box beside Inbound enter the URL https://<your-ngrok-generated-url>/webhooks/inbound and beside Status https://<your-ngrok-generated-url>/webhooks/status . Click save webhooks and we should be ready to test our application.

You should see instructions under the WhatsApp section on how to get started with the sandbox. Go ahead and send a message to the number mentioned in the section and keep an eye on the terminal window in which your node app is running. You should get a response with something like this

{
message_uuid: 'asdfasfd-asdf-adsf-adfs-asdfasdfasd',
from: { type: 'whatsapp', number: '00000000000' },
to: { type: 'whatsapp', number: '000000000000' },
message: { content: { type: 'text', text: 'Hi' } },
timestamp: '2020-11-14T19:48:24.688Z'
}

You can go ahead and explore all the properties that are in the request body.

Note: Every time you restart ngrok, a new URL is generated. So make sure you update the Webhooks URL in the sandbox page.

Sending a response

It’s finally time to send a response. We’ll be sending a POST request using axios to the Vonage Messages API to send a response to the text message our webhook just received.

Setup Authentication

Before we proceed any further, Vonage needs to know that it’s us who’s sending a request to their API and for this, we need to provide credentials. For security reasons and as a best practice credentials should never directly be inserted into code. We’ll be storing the credentials in environment variables in a .env file.

// .envVONAGE_NUMBER=<your-vonage-number>
VONAGE_API_KEY=<your-vonage-api-key>
VONAGE_API_SECRET=<your-vonage-api-secret>

You can get your API key and API secret from the Vonage Dashboard and the Vonage Number is the number of your sandbox which you can find under the WhatsApp section at https://dashboard.nexmo.com/messages/sandbox.

Dotenv is a library that reads the .env file and makes it accessible to the node application. To setup dotenv first install it by running npm install dotenv and then add require("dotenv").config() to the top of app.js. Environment variables are accessed in node using process.env . We can now access our API key in node by using process.env.VONAGE_API_KEY and the API secret with process.env.VONAGE_API_SECRET .

Axios

We’ll be using axios to simplify sending requests to the Messages API. To get started, first install axios by running npm install axios . Then let’s create a function that takes the number which takes the number to send the message to and the message itself as arguments and send a request to API with the appropriate parameters.

  • https://messages-sandbox.nexmo.com/v0.1/messages is the URL at which we can send requests to the Messages API.
  • The second parameter takes a Javascript object which is sent as the body of the request. Here we specify the information the Messages API needs to send the message.
    * Under the from section, the type parameter is the platform to which the message is sent and the number is the number the sandbox uses. This is the same number that you used when messaging the.
    * The to section contains information of the receiver of the message, in this case it’s the person which sent the message in the sandbox.
    * Under the message section, we specify information about the content of the message itself. The type of message will be text as we’re just going to be sending a plain text message.
  • The third parameter in axios is additional options. We can directly provide our credentials with the auth parameter. The username and password will the Vonage API key i.e. process.env.VONAGE_API_KEY and Vonage API secret i.e. process.env.VONAGE_API_SECRET respectively.

Send the response

Now let’s change the inbound message to resemble the below code.

All we’re doing is getting the number of the user who sent the message and the content of the message and checking if the message says hi and if it is send a message back to the same number.

And that’s it, we’re done! You can restart your node server (you don’t have to restart ngrok) and try it out for yourself. You can add any sort of logic, add any number of if statements you’d like and customize it as much as you like.

Keep a close eye on your console and you should see the use of the status webhook whenever a message is sent by the API.

In the end, our app.js should look something like this.

What’s next

  • Right now, our webhook is open to the entire internet. We need a way to make sure only the Vonage Messages API can access the endpoint. This is achieved using JWT tokens. You can read more about it at https://developer.nexmo.com/messages/concepts/signed-webhooks.
  • Try modifying the sendWhatsappMessage function to be able to send messages to Messenger as well or even include other kinds of messages such as location.
  • Explore the Vonage Docs and build something amazing!

--

--

Shreyas Sreenivas
The Startup

Programmer. Writer. TypeScript, GraphQL and React Lover. Oh and also a GSW fan