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.

Sunday 6 November 2016

A simple perl script to make a file content unique

This simple perl script does the job of sort -u (of course not in windows)

Script:


 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
#!/usr/bin/perl

use strict;

use warnings;


#File reading code

open(my $in,"<:utf8",$ARGV[0]) or die "Cannot open $ARGV[0]:$!\n";

my @in =<$in>;

close($in);


#declare hash

my %hash=();


#store content in hash

foreach my $in (@in) {

 chomp($in);

 $hash{$in} = 1;

}


#Finally print the hash

foreach my $keys(sort keys %hash){

 print "$keys\n";

}
How to run:

Lets assume that our script is saved as my_unique.pl 


$ perl my_unique.pl <filename>

* Without angular brackets.

Explanation:
Here in Perl hash the duplicate keys are overridden which means only single instance of each line in the file is stored in the hash. Remember that while storing the lines in hash each single line is treated as key so as to remove duplicates. 

Note: Always use strict and use warnings when dealing with Perl code so as to write bug free code.

Linux: How to find duplicate lines count in a file from terminal.

Linux has many commands that are useful to process/analyze a file. In this post I would just explain a simple utility that would just print out the number of times each line is repeated in that file.

So here is the command:

terminal$ sort yourfilename.txt | uniq -c

Here yourfilename.txt can be any file name which I used here for an example.
Suppose the contents of yourfilename.txt be

line1
line1
line2
line3
line1
line3

Output:

3 line1
2 line3
1 line2

Explanation:

The sort command is quite self explanatory over here its output is piped/redirected to uniq. Uniq command requires its input to  be sorted(keep in mind always hard to remember). Uniq -c just prints the count of each line.