DEV Community

Cover image for Creating a Whatsapp chatbot using Node JS, Dialogflow and Twilio

Creating a Whatsapp chatbot using Node JS, Dialogflow and Twilio

Newton Munene on January 03, 2020

I'm going to walk you through creating a WhatsApp chatbot using Dialogflow. I initially wanted to do this in several blog posts but I'm going to co...
Collapse
 
kleiton profile image
Kleiton Moraes

Hi Newton, great article!
How can I identify the name of the itent that matched the dialogflow and give a specific answer?

I know the value in the dialogflow is at
body.intent.displayName, but how can I capture this value in the code to give a dynamic response?

Thank you!

Collapse
 
newtonmunene_yg profile image
Newton Munene

Hey sorry for the late reply. I'm not sure I understand what you mean, but I'll answer what I understood.
When your fulfilment webhook is called the intent name will be in body.queryResult.intent.displayName you can use a switch case statement to check the name of the intent and perform some actions. You then have to return a webhook response for the request.

Here's how you can do this in express

app.post('/webhook', (req, res) => {
  switch (req.body.queryResult.intent.displayName) {
    case 'INTENTNAME':{
        const customParameter = req.body.queryResult.parameters.mYCustomParameter;
      res.send({
        fulfillmentMessages: [
          {
            text: {
              text: [`My custom response based on ${customParameter}`],
            },
          },
        ],
      });
      break;}

    default:
      break;
  }
});

Please read more about this here cloud.google.com/dialogflow/docs/f...

Collapse
 
kleiton profile image
Kleiton Moraes

Hello @newton , thank you very much for your answer!
I'm having trouble understanding which part of your project I should create this code that you informed.
I understand how the webhook should work, but I don't know where I put that part of the code that you passed.

I must create a new route in the bot.js file
router.post (/webhook, (request, response) => {}); ?

and then refer to BotController.ts?
With the code you passed?

Sorry for the long text, if you have any code examples that are working, you can share that I analyze and try to understand, thank you my friend!

Thread Thread
 
newtonmunene_yg profile image
Newton Munene • Edited

Hi,
From my understanding, what you're looking to achieve is something like this:

  1. User send message from whatsapp
  2. You get the message and send it over to dialogflow for intent matching and await a response
  3. Use dialogflow fulfilment webhook to do something in your server
  4. Send back a response for the fulfilment webhook
  5. Receive the response from Dialogflow (this is the response you're awaiting in step 2)
  6. Send the response back to whatsapp.

I have updated the repo to include a controller for Dialogflow webhook. github.com/newtonmunene99/wa-chatbot

When you receive the webhook from dialogflow, do whatever you need to do with the intent and parameters and then return the response to dialogflow. In BotController.ts, or wherever you execute the runQuery function, just await the result then send that to Whatsapp.

Thread Thread
 
kleiton profile image
Kleiton Moraes

Thank you so much @newton !
I'll look at it right now, have a great day my friend!

Collapse
 
kleiton profile image
Kleiton Moraes • Edited

Hello, this is more or less what I need to do,

I have a web service that receives four input parameters and returns an object on the output, I need to return the value of that object to WhatsApp
My doubt is in which part of your project I put the code you passed, so when the dialogflow returns the parameters I make the call to the Webservice and use its output on WhatsApp
Thank you!

Collapse
 
teenahg profile image
Tinashe Gondwa

Hi Newton. Thanks for the tutorial. I seem to be having problems with the code, when i try to run the main file, it says 502 - Bad Gateway and the app won't even run.

Collapse
 
newtonmunene_yg profile image
Newton Munene

Let me look at this. Thanks

Collapse
 
teenahg profile image
Tinashe Gondwa

You're welcome. Thanks, also awaiting your response on this.

Thread Thread
 
newtonmunene_yg profile image
Newton Munene

Hi Tinashe, have you tried the sample code? Here's the repository github.com/newtonmunene99/wa-chatbot

Thread Thread
 
teenahg profile image
Tinashe Gondwa

Hi Newton. Yes, I cloned the code from github and only changed the Credentials but it's not working.

Thread Thread
 
newtonmunene_yg profile image
Newton Munene

Did you rename .env.copy to .env.
Also what OS are you running?

Thread Thread
 
teenahg profile image
Tinashe Gondwa

yes, I renamed it. I'm running Windows 10

Thread Thread
 
newtonmunene_yg profile image
Newton Munene

Please tell me if it runs with npm run dev:watch or npm run dev

Thread Thread
 
newtonmunene_yg profile image
Newton Munene

The issue might be that rm isn't supported by Windows OS

Thread Thread
 
teenahg profile image
Tinashe Gondwa

Thanks mate. I was able to debug it and now it's running. Several factors were taking play, one of which is the issue of platform compatibility. Thanks so much for the assistance

Thread Thread
 
chriskahiga profile image
chriskahiga

Hi Tinashe, how did you solve your issue, I'm also getting the same 502 Bad Gateway error

Thread Thread
 
teenahg profile image
Tinashe Gondwa

Hi Chris. First, check if you have all of the required node modules installed. The second check is this: if you're testing your project in a local environment, you must run npm run dev first, then once the server is running, you also start any other service or app that wants to use your project.

Collapse
 
kleiton profile image
Kleiton Moraes • Edited

Hello @newtonmunene_yg , how are you my friend?
Do you know if it is possible to send an image as a reply on WhatsApp?
Currently I receive the parameters through Dialogflow, process in the webhook and respond with some text back to WhatsApp, I would like to know if it is possible to respond with an image stored locally for example.

I saw it here, but I couldn't make it work
twilio.com/blog/whatsapp-media-sup...

Thank you!

Collapse
 
alejomv21 profile image
alejomv21

hello Newton, I`m starting to program, I want to know if it is possible, to connect twilio with another message control service such as front ap, at the moment I have twilio connected with dialogflow, but I also need to connect it with front app, I need the input messages and output that go through twilio also reach the front app, I don't know if it is possible to do so.

Collapse
 
pranjalvatsa86 profile image
Pranjal Vatsa

Hi Newton,

I am getting a PERMISSION_DENIED: IAM permission 'dialogflow.sessions.detectIntent' when trying to send a message from Whatsapp.

I am added the 'Dialogflow API Admin' role from Google IAM & Admin.

Need help on this please.

Collapse
 
roberthedler profile image
Robert Son Hedler

Hi Team. Thanks for the post, it is very useful.
I doit exactly as is says and i got the following error:
src/controllers/BotController.ts:10:12 - error TS1146: Declaration expected.

I do not have much experience on. what it could be? this is the only error i received.

Collapse
 
abubakr28355335 profile image
Abubakr Elghazawy

our botcontroller.ts should we put our local server like that

@Controller("localhost:3000/api/bot")
export class BotController {
@post ()
private postMessage(request: Request, response: Response) {
Logger.Info("A post request has been received");
return response.status(200).json({
message: "A post request has been received"
});
}

}
or ngrok server
7b2eac7593d3.ngrok.io -> localhost:3000

Collapse
 
nicolasoccal profile image
NicolaSoccal • Edited

Hi Newton, Can you please detail more how to expose the local server with Ngrok. I'm totally new in this area, thank you.

Collapse
 
newtonmunene_yg profile image
Newton Munene

Hello Nicola. You need to first install ngrok on your machine. Check out ngrok.com/ for instructions on this. Once you have this installed, run the Node Js project using npm run dev. Take note of the port that it's running on, I believe its 3000 for this particular project. Next you need to expose your local webserver. Read about that here, dashboard.ngrok.com/get-started/tu... . The command you will need to run will be something like ./ngrok http 3000. 3000 here being the port the project is running on. Ngrok will expose your local server and give you a couple of links that are accessible on the internet. Copy the https link and thats what you will paste in the Twilio Whatsapp Sandbox page (twilio.com/console/sms/whatsapp/sa... ). Don't forget to add the bot's route. ie /api/bot

Collapse
 
nicolasoccal profile image
NicolaSoccal

I'm sorry Newton for bothering you, When I run "npm run dev" it looks like I miss the file package.json (See log below)

In your article you talk about a package.json file where to add scripts. Are you referring to the package.json I find in the dialoflow fullfilment section or is it another file?

I think I'm missing something very important here. Sorry...

npm ERR! path /home/nicolasoccal/wa-chatbot/package.json
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open '/home/nicolasoccal/wa-chatbot/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! /home/nicolasoccal/.npm/_logs/2020-04-20T18_53_19_411Z-debug.log

Collapse
 
nicolasoccal profile image
NicolaSoccal

Hi Newton. Thank you. Can you detail how to expose the local server with Ngrok?
I developed quite powerful agent in dialogflow but here I'm totally new. Thanks a lot if you can help.

Collapse
 
philnash profile image
Phil Nash

This looks like a great article. I've bookmarked it to come back to when I've got some time!

Collapse
 
newtonmunene_yg profile image
Newton Munene

Thank you Phil

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
chiquiipu profile image
Angie

Thanks to you I could understand the logic and create my own project.

Collapse
 
newtonmunene_yg profile image
Newton Munene

You're welcome Angie

Collapse
 
widebyte profile image
Rafael Barbosa

Hello Newton, can you explain how to create this alert (notification) from a message received from the client (POST)?

Collapse
 
newtonmunene_yg profile image
Newton Munene

Hello.
I'm not sure I understand your question.
Could you give me more details please.

Collapse
 
mateocgomez profile image
Mateo Castaño Gomez

Hi Newton, thanks for your help, I have a question when you receive a message and you return the answer successfully, twilio doesn't mark you as a mistake?

Collapse
 
abubakr28355335 profile image
Abubakr Elghazawy • Edited

I really apraciate your work here

And I Have A Q?
Assume 1- we have user or multi user send messages to whatsapp my number
2- how chatbot will work After !

Collapse
 
newtonmunene_yg profile image
Newton Munene

Hi 😀, I'm sorry for the delayed response. I'm not sure I understand what you meant to ask, could you please try and rephrase it?

Collapse
 
stevenhdz profile image
Alexander Jimenez

Great, article !!