Sunday 13 November 2016

How to build a basic facebook messenger bot using Nodejs ?

To build a facebook bot, you may choose any server side technology like php, nodejs, python, ruby. I am choosing Nodejs, as it is simple and has built in libraries that would ease in building a bot.

To start building a bot, you need to install Nodejs on your computer. You may install nodejs from link below:

https://nodejs.org/en/download/

Let's start of  with building that would say hello on your input.

1. The front end API is provided by facebook which can be accessed through a facebook page. To accomplish this you'll have to create a facebook page.

2. In order to have your bot communicate with the page, facebook provides a unique token which is to be included in your code. To generate a token, you will have to create a facebook app here. Once you are done creating the app, click on "Messenger" and select your page from the drop down which generates a random token. Have this token saved for later use in the code. Then click on "Add Products" and select webhooks.

3.  Now that we have token ready, lets write the code say file name is server.js. Note that the above generated token needs to be replaced in the below code 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    const http = require('http')
    const Bot = require('messenger-bot')
    var bot = new Bot({
     token: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
     verify: 'VERIFY_TOKEN'
    })
    bot.on('error', (err) => {
     console.log(err.message)
    })
    bot.on('message', (payload, reply) => {
     var text = payload.message.text;
     text = text.toLowerCase();
     text = text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()?'"@|\+<>\[\]]/g,"");
     text = text.replace(/\s{2,}/g," ");
     console.log(text);
     if(typeof text === "undefined" || text == "")
     {
     text = "Oops! we couldn't find this word in our database. Try other.";
     console.log("Sorry! we couldn't find this word in our database. Try other.");
     }
    else if(text == "hi" || text == "hello"){
     text= "Hi. I am hello bot.";
     reply({ text }, (err, info) => {
     });
    else if(text == "bye"){
     text= "Bye. See ya!.";
     reply({ text }, (err, info) => {
     });
     else if(text == "How are you?"){
     text= "Am fine thanks.";
     reply({ text }, (err, info) => {
     });
     bot.getProfile(payload.sender.id, (err, profile) => {
      if (err) throw err
      reply({ text }, (err) => {
       if (err) throw err
       console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
      })
     })
    });
    http.createServer(bot.middleware()).listen(3000);
    console.log("chat bot up and running..");

4. Now that we are done with the code, its time to run our bot. To run the server, type node server.js.

5. Since, the facebook API communicates through secure tunnel, we need a secure server to establish the connection between facebook and our node server. Ngrok comes to the rescue in this case. Ngrok provides a secure tunnel which allows our server to connect to facebook API.  Install and run Ngrok which generates a secure link. Copy the generated secure link(looks like https://localhost:XXX).

6. In the facebook Developers page, click on "Webhooks" and paste the above secure link in callback url field and enter the verify token from code in "Verify Token" section, click "Verify and save". To activate the tunnel, click on "Messenger"  and select your page and click on "Subscribe" to subscribe it.

7. Finally, we are done with setup and our bot is ready to talk. In the created facebook page, click on Message and type "Hi" and boom you'll get the response.

This is a basic chat bot which simply sends text message. Similarly, you can use different templates available in Messenger platform to make your own bot.

2 comments:

  1. Hey very nice tutorial sravan kumar.
    One doubt may sound silly as I dont have any prior experience of working with ngrok/localtunnel.

    I exposed my localhost to WWW using ngrok.
    But like how to run this server.js when FB pings my callback url.

    What I mean is If I bought a domain name say www.mydomain.com and have a file server.js then I would specify https://www.mydomain.com.server.js as callback URL to FB.

    But in case of ngrok we get somethink like https://session_id.ngrok.io so little confused on specifying the file that needs to run when callback url is called by FB

    ReplyDelete
    Replies
    1. Pardon my late reply @Amitabh. In case if you have your own domain, then you can specify the url path of where the server.js file is located in your domain.
      For instance, if you have your server file in a directory named 'app', then you may specify the url as 'www.mydomain.com/app/'.
      But make sure your domain has SSL enabled connection.

      Delete