Sunday, March 12, 2023
HomeReactCreate a Chatbot with Dialogflow, NodeJS, and Webhooks by Aman Mittal

Create a Chatbot with Dialogflow, NodeJS, and Webhooks by Aman Mittal


Create a Chatbot with Dialogflow, NodeJS, and Webhooks

Revealed on Jul 19, 2019

13 min learn

cover_image

Chatbots are the most well liked issues within the trendy digital world. Day by day, organizations and people are powering their digital merchandise equivalent to web sites or messenger apps to offer conversational experiences for his or her customers. Every conversational expertise is dependent upon the implementation of the chatbot to both be a great or poor expertise for the consumer. The trendy day world resides within the know-how wave of Synthetic Intelligence, and chatbots are an enormous a part of it.

On this tutorial, you will be launched to a straightforward to make use of instrument for such makes use of circumstances referred to as Dialogflow. Previously referred to as API.AI, it may be personalized to offer data equivalent to climate in your consumer’s metropolis or details about a film they prefer to see. This customization, nonetheless, can solely be utilized utilizing a 3rd get together API that’s constant in delivering outcomes for the particular search time period.

By offering a step-by-step on establishing and working the chatbot and tips on how to use a 3rd get together API with Dialogflow. You will create a customized webhook utilizing Nodejs, deploy it as a service, after which use it together with your Dialogflow setups to develop brokers and intents. What are webhooks, you ask?

A Webhook is an easy HTTP callback that will get triggered primarily based on some occasion. These occasions are outlined by the consumer, for instance, publishing a remark to weblog submit, or publishing a brand new tweet in your Twitter app.

You will construct a film chatbot that gives details about a film utilizing The Open Film Database API. The webhooks can be used to fetch the small print of a movie.

Desk of Contents

  • Necessities
  • Create a Node Server
  • Fetching the Film
  • Deploy the Webhook on Heroku
  • Setup Dialogflow
  • Create Coaching Phrases
  • Allow the Webhook
  • Conclusion

Necessities

🔗

To comply with this tutorial, you want the next:

  • Nodejs v8.x.x or larger put in together with npm/yarn because the bundle supervisor
  • Github Account
  • Crowdbotics App builder Platform account (ideally log in together with your legitimate Github ID)
  • Dialogflow account (you should use your Google ID)
  • OMDb API API Key: make sure that if you register the account, you request for an API key. It is rather to get one, register an account.
  • Heroku or some related service to deploy the webhook

Create a Node Server

🔗

The next steps need to carry out contained in the mission listing you’ve got set as much as create the Nodejs server. As soon as you’re contained in the server folder, ensure you run the next instructions sequentially utilizing a terminal window. The primary command will initialize the server listing as a node server and generate a bundle.json file. The second command will allow you to set up all of the required dependencies.

npm init --yes

npm set up -save categorical dotenv

As soon as all of the dependencies are put in, allow us to bootstrap a small server and see if all the pieces is working or not. Create a brand new file index.js and add the next snippet to it.

1const categorical = require('categorical');

2

3const http = require('http');

4

5require('dotenv').config();

6

7const app = categorical();

8const port = course of.env.PORT || 3000;

9

10app.use(categorical.json());

11app.use(categorical.urlencoded({ prolonged: true }));

12

13app.get('/', (req, res) => {

14 res.standing(200).ship('Server is working.');

15});

16

17app.hear(port, () => {

18 console.log(`🌏 Server is working at http://localhost:${port}`);

19});

The above server is easy as it may be with just one / dwelling route for now. This route is created now solely to check whether or not the server being bootstrapped on this part goes to work or not. Typically small errors are time wasters, so it’s higher to take a look at. The module dotenv allow the file to learn atmosphere variables and their values from the file .env. Right here is how the .env the file seems like.

The Xs are going to be the worth of the API key that you’ve got from registering an account at OMDB API. Exchange the worth of those Xs with that key. Now, go to the terminal window and execute the command node index.js. This may immediate with the message you’ve got outlined within the above snippet. Go to the URL http://localhost:3000 from the browser window, and you’re going to get the next consequence.

Fetching the Film

🔗

On this part, you will create a route known as /getmovie. It’s going to be a submit request. This request goes to seek for the film specified on the consumer’s enter. If that film exists, it’ll return the consumer with the small print of the film such because the title itself, the yr it was launched, a summarised plot, and so forth.

Open index.js file and the next after you’ve got outlined middleware features.

1app.submit('/getmovie', (req, res) => {

2 const movieToSearch =

3 req.physique.queryResult &&

4 req.physique.queryResult.parameters &&

5 req.physique.queryResult.parameters.film

6 ? req.physique.consequence.parameters.film

7 : '';

8

9 const reqUrl = encodeURI(

10 `http://www.omdbapi.com/?t=${movieToSearch}&apikey=${course of.env.API_KEY}`

11 );

12 http.get(

13 reqUrl,

14 responseFromAPI => {

15 let completeResponse = '';

16 responseFromAPI.on('information', chunk => {

17 completeResponse += chunk;

18 });

19 responseFromAPI.on('finish', () => {

20 const film = JSON.parse(completeResponse);

21

22 let dataToSend = movieToSearch;

23 dataToSend = `${film.Title} was launched

24 within the yr ${film.Yr}. It's directed

25 by ${film.Director} and stars ${film.Actors}.n Right here some glimpse of the plot: $

26 {film.Plot}.

27 }`;

28

29 return res.json({

30 fulfillmentText: dataToSend,

31 supply: 'getmovie'

32 });

33 });

34 },

35 error => {

36 return res.json({

37 fulfillmentText: 'Couldn't get outcomes presently',

38 supply: 'getmovie'

39 });

40 }

41 );

42});

The http module is from Nodejs core. It’s going to ship the request which is the variable reqUrl and a callback operate responseFromAPI. This operate goes to set off two occasions: information and finish. The occasion information goes to return the details about the film from API in chunks.

The completeResponse holds the information is parsed into JSON when the response from the API is ended. The personalized response that’s being returned within the above route’s snippet ought to include the sector fulfillmentText and error response for circumstances which may now work in any respect.

On a aspect observe, right here is how an object for a selected film information in JSON seems like from the OMDB API.

1{

2 "Title": "Flashbacks of a Idiot",

3 "Yr": "2008",

4 "Rated": "R",

5 "Launched": "17 Oct 2008",

6 "Runtime": "109 min",

7 "Style": "Drama",

8 "Director": "Baillie Walsh",

9 "Author": "Baillie Walsh",

10 "Actors": "Emile Robert, Scoutt Lowe, Daniel Craig, Julie Ordon",

11 "Plot": "A fading Hollywood star seems again at

12 the times of his youth as he returns dwelling from his

13 greatest good friend's funeral.",

14 "Language": "English",

15 "Nation": "UK",

16 "Awards": "N/A",

17 "Poster": "https:

18 MV5BMTIzMDk0MDc3OV5BMl5BanBnXkFtZTcwODMwODY5MQ@@.

19 _V1_SX300.jpg",

20 "Scores": [

21 { "Source": "Internet Movie Database", "Value": "6.8/10" },

22 { "Source": "Rotten Tomatoes", "Value": "38%" }

23 ],

24 "Metascore": "N/A",

25 "imdbRating": "6.8",

26 "imdbVotes": "11,348",

27 "imdbID": "tt1037218",

28 "Kind": "film",

29 "DVD": "22 Sep 2008",

30 "BoxOffice": "N/A",

31 "Manufacturing": "Anchor Bay Leisure",

32 "Web site": "http://www.thefilmfactory.co.uk/flashbacks/",

33 "Response": "True"

34}

From this appreciable object, you’re solely utilizing some quantity of data described within the earlier snippet. To check that the result’s being fetched from the OMDB API, begin the server by going to the terminal window. Execute command node index.js.

Open your favourite relaxation shoppers equivalent to Postman or Insomnia. Enter the URL http://localhost:3000/getmovie and though it’s POST request, and you’ll have to enter the parameters as proven under. Allow us to take a look at out if the API is returning the small print of the film title entered or not. Within the under picture, you possibly can confirm that the knowledge associated to the information is being changed.

Deploy the Webhook on Heroku

🔗

For the reason that route /getmovie is working, it’s time to deploy the webhook you efficiently construct within the earlier step. Login to your Heroku account or should you wouldn’t have one, create an account. You may add as much as 5 internet functions that may run without spending a dime to some variety of hours (known as as dynos).

Earlier than you proceed with any of the steps under, within the bundle.json file, make sure that the begin script exists as specified under.

1"scripts": {

2 "begin": "node index.js",

3 "take a look at": "echo "Error: no take a look at specified" && exit 1"

4}

When you log in, you can be welcomed by the display screen referred to as Dashboard. Create on the button New on the highest proper nook after which create select Create new app.

Fill within the title of the applying. After you have entered the small print, click on the button Create app.

Now, you can be welcomed by the next web page that has directions to deploy your present Node app. If you’re utilizing Github, go forward and select the Hook up with Github deployment methodology. I’m going to make use of heroku-cli.

To proceed with the next set of directions, additionally as talked about within the above display screen underneath the part Deploy utilizing Heroku Git. What this implies is that the occasion of your full Node utility goes to be deployed from the native growth atmosphere the place the applying is at the moment situated. After you have put in the Heroku CLI, enter the next command to proceed. Additionally, if you’re utilizing the Crowdbotics platform to generate the present demo app or have initialized the listing, you’re working utilizing the command git init, ignore the part Clone the repository within the above picture.

heroku login

$ git add .

$ git commit -am "deploy"

$ git push heroku grasp

The one factor to note right here is that you’re not going to git push to the origin however heroku. As soon as the deployment is finished, you’re going to get a message like under within the terminal window.

distant: https://getmoviehook.herokuapp.com/ deployed to Heroku

distant:

distant: Verifying deploy... completed.

To https://git.heroku.com/getmoviehook.git

* [new branch] grasp -> grasp

You’re going to get the URL https://getmoviehook.herokuapp.com/ from the above deployment process. To check it out, you can’t merely ship a GET request by visiting the URL https://getmoviehook.herokuapp.com/getmovie from a browser window. You may once more use a REST shopper like Postman. Simply change the localhost URL with deployed one that’s beforehand talked about.

You’re going to get profitable outcomes.

Setup Dialogflow

🔗

Dialogflow is a Pure Language Processing (NLP) service from Google. It has many integrations, SDKs for programming languages and a few prebuilt brokers. It really works very simple with Google Assistant. Go to the Dialogflow web site and create a brand new account or log-in together with your present Google ID.

As soon as you’re logged in, you can be welcomed by a display screen that consists of various Brokers.

Click on on the Create Agent button to make one for your self. Identify it one thing much like OMDBbot. Fill within the particulars like under.

After filling out the small print, click on on the button Create.

Typically, for small functions, you should have one agent. In Dialogflow, the essential movement of dialog includes these steps:

  • The consumer giving enter within the type of a question
  • Your Dialogflow agent parses the enter from the coaching phrases
  • Your agent returns a response again to the consumer

These brokers perceive the various nuances of human language. They’ll translate that to plain and structured that means that chatbot functions and companies can perceive. Every agent accommodates completely different intents. The intent is the motion taken primarily based on the consumer’s enter. It may be the response despatched again to the consumer in a chatbot utility. It will possibly include various kinds of responses or actions. The following step within the course of is to create your first intent.

Click on on the button Create intent and fill within the title getmovie. You may title your intent something.

Intent could be a easy textual content response that’s displayed again to the consumer or a set of skilled phrases. There are additionally actions and parameters that extract data from consumer queries. Examples of this sort of data embrace dates, instances, names, locations, and extra.

Create Coaching Phrases

🔗

Allow us to create new coaching phrases on this part. To create a brand new phrase, go to the part Coaching phrases and a singular consumer expression as reveals under.

For the film chatbot, every consumer expression goes to include the title of the film. The Dialogflow agent shouldn’t be sensible sufficient to extract the title of the film out of the consumer’s expression. You need to present an entity that may spotlight the title of the film each time a brand new coaching phrase is launched to the bot.

From the sidebar menu, go to the entity part and click on on the button Create Entity. Fill within the title of your entity as film as a result of that is what’s being handed contained in the webhook’s request physique. From the server, keep in mind the next line:

1req.physique.queryResult.parameters.film;

After you have saved your entity, return to the intent.

Allow the Webhook

🔗

To check out that all the pieces is working, allow us to use the default response supplied by the Dialogflow intent. As proven under, on the right-hand aspect of the display screen, you possibly can take a look at out by getting into a consumer expression. The film chatbot will return the default response.

That is okay and verifies that the intent has been created efficiently. Now, to make use of the real-time information from the OMDB API, you will allow the webhook. From the sidebar menu, go to the Achievement part. You can be welcomed by the next display screen.

Allow the Webhook after which enter the URL of the deployed endpoint.

As soon as that’s completed, return to the Intents part, and scroll right down to the underside of the online web page. There’s a Achievement part. Toggle the button to Allow webhook name for this intent.

As soon as that’s completed, go to the appropriate aspect of the display screen to check it out. Fill within the consumer expression much like a coaching phrase you’ve got supplied earlier. The agent will get a response again with the small print of the film.

Conclusion

🔗

You might have efficiently created, deployed, and examined a Nodejs Webhook for Dialogflow chatbot utility. By the tip of this tutorial, we’re positive you’ve got discovered how straightforward it’s to create a brand new chatbot agent utilizing Dialogflow. The chances of utilizing a strong API equivalent to Dialogflow are limitless. Very quickly, you possibly can construct up your individual chatbot interface for front-end shoppers utilizing Reactjs, Angular, and even cell cross-platform framework like React Native. We hope this tutorial supplied you a straightforward walkthrough to seize the ideas and construct one thing of your individual.


I am a software program developer and a technical author. On this weblog, I write about Technical writing, Node.js, React Native and Expo.

Presently, working at Expo. Beforehand, I’ve labored as a Developer Advocate, and Senior Content material Developer with corporations like Draftbit, Vercel and Crowdbotics.

RELATED ARTICLES

Most Popular

Recent Comments