Saturday, 21 October 2017

Developing a basic responsive Telegram bot that echoes your input

Well it's not quite easy for a beginner to develop telegram bot in a short time by exploring the telegram bot API. I'll just brief you the procedure by developing a basic telegram bot and I'm sure this tutorial would help you kick start with developing a telegram bot of your own with in a short time. Once you get familiar with basic bot, you could explore the official telegram bot API for customizing your bot.

Let's get started with developing a basic telegram bot.

1. Firstly, you would need to create or register your bot with Telegram. A Telegram's bot called "BotFather" will help you do this.

Login into telegram either through web or app and search for "BotFather" in search box.



2. Select BotFather and you'll find options to create a new bot in botfather chat.



3.  Click on "/newbot" option and enter your bot's name. I am naming my bot as "echo bot".


 4. Once you are done with creating your bot, you'll be issued a token. Save this token for later use.

5. Now your bot is ready to show up on telegram, you may search your bot using it's user name in search box.




 6. Now that the bot is ready, let's add some life to it. For this, we'll have to develop a server for our bot to help it handle the actions(echo user input in our case). To get our server communicated with this bot, we use the token(in step 3) issued by BotFather.

7. Let's develop a script which upon sending an input from our bot echoes it back to bot. I am using nodejs as server side language, it can also be developed in python. Since, node has pretty good number of modules that would make it easy for developing server-side, I'm using it. Here, I'm using a node module called node-telegram-bot-api which has pre-defined packages required for telegram bot API.

Server code for bot with filename echobot.js:

const http = require('http');

const https = require('https');

var TelegramBot = require('node-telegram-bot-api');

var token = 'XXXX'; //Token issued by BotFather

var bot = new TelegramBot(token, {

    polling: true

});


//getMe() returns the user name of the bot


bot.getMe().then(function(me) {

    console.log('Hi my name is %s!', me.username); //prints on console  when you run the server.

});


//on entering any text, we're converting the character case to lower


bot.onText(/.*/, function(msg, match) {

    var text = msg.text;

    text = text.toLowerCase();


    //remove special characters in the input


    text = text.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()?'"@|\+<>\[\]]/g, "");

    text = text.replace(/\s{2,}/g, " ");


    //just to add AI, on input hi/hello, it prints this message


    var fromId = msg.from.id; // get the id, of who is sending the message

    if (text == "hi" || text == "hello") {

        //  console.log("hi d d gdg d"+msg.text);

        var from = msg.from.first_name; // get the id, of who is sending the message

        var message = "Hi " + from + " Welcome to your eng-hin Bot\n"

        message += "Type any english word and get the respective hindi meaning.";

        bot.sendMessage(fromId, message);

    } else {

        message = text;

        bot.sendMessage(fromId, message); //echoes the message

    }


});

});

8. Now that our server is ready, let's run the server using the following command:


$ node echobot.js



9. Try the echo bot in telegram by sending the messages.



That's it, your bot is ready to talk to you now :) Hope you are aware of customizing your own telegram bot now.

Happy coding ;)


Monday, 16 October 2017

Creating a backup of installed ubuntu(ISO image)

1. Download Relinux 0.2 from

http://sourceforge.net/projects/re-linux/?source=directory

                                     OR

http://nchc.dl.sourceforge.net/project/re-linux/relinux_0.2.1b1.tar.gz

2. Create a folder "relinux" on Desktop and extract the content from the above link to this folder.

3. To install, simply type this into a Terminal window( Read file relinux/INSTALL on Desktop for instructions):

$ sudo cp -R usr etc /

4. After you have installed it, look at Desktop/relinux/usr/share/doc/relinux/README.

   Type this into a Terminal window to generate the configuration file:
 
$ cp /etc/relinux/relinux.conf ./relinux.conf
 
$ sed -i 's:EXCLUDES="\(.*\)":EXCLUDES="\1 '`readlink -f ./relinux.conf`'":g' ./relinux.conf

5. Install Dependencies for Relinux :

$ sudo apt-get install libdebian-installer4 casper ubiquity ubiquity-frontend-gtk discover-config xresprobe tree dialog

6. Copy the file

Desktop/relinux/etc/relinux/relinux/splash/splash.png to Desktop

Edit relinux.conf for customisation from Desktop/relinux/

Replace the following line

SPLASHIMAGE=/etc/relinux/relinux/splash/splash.png
           
          with

SPLASHIMAGE=/home/ebs/Desktop/splash.png

7. Type the following command in terminal:

$ sudo relinux squashfs ./relinux.conf

8. Type the following command to prepare an iso file.

$ sudo relinux onlyiso ./relinux.conf

Reference Video link : http://ubuntutes.com/wp/index.php/2016/12/31/create-backup-of-installed-ubuntu-12-04-12-10-13-04-as-install-iso-using-relinux/

Tuesday, 26 September 2017

Setup SSL self signed on certificate on linux mint/ubuntu(to get https in url)

In the web world, it is quite vital to secure your website from malicious attacks. The SSL(Secure Socket Layer)  is used to secure the data transmitted over the internet between your computer and the destination servers.

This could be the password you used to log into Facebook or your credit card information when you are purchasing something online, basically any important information you wouldn’t want others to know.

With an SSL certificate, any information that is transmitted becomes encrypted by inserting random characters into the original message making it unread.

If a website is secure, you will find the https or a lock symbol in the url. Mostly, you can find the https connection on e-commerce and banking websites.

You may install a self signed SSL certificate or purchase it online from SSL service providers like McAfee, comodo etc. However, the certificate from SSL provider is recommended to be secure than self signed.

Let's see how to configure SSL on our host with self signed certificated.

Open the terminal and use the following commands:

Step 1:

$ mkdir -p /etc/apache2/SSL

Step 2:

$ cd /etc/apache2/SSL

Step 3:

a) Generate self signed key with pass phrase

$ openssl genrsa -des3 -out self-signed.key 2048&nbsp; #create a certificate with a passphrase

Output :
 
Generating RSA private key, 2048 bit long modulus

e is 65537 (0x10001)
Enter pass phrase for self-signed.key:
Verifying - Enter pass phrase for self-signed.key:

b) a) Generate self signed key without pass phrase

$ openssl genrsa -out self-signed.key 2048 #Create certificate without a passphrase

Output :

Generating RSA private key, 2048 bit long modulus
e is 65537 (0x10001)

4. Generate CSR(certificate sign request)A

$ openssl req -new -key self-signed.key -out self-signed.csr<br />

Output:

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields, there will be a default value,
If you enter '.', the field will be left blank.

Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:Telangana
Locality Name (eg, city) []:Hyderabad
Organization Name (eg, company) [Internet Widgits Pty Ltd]:learnindetail
Organizational Unit Name (eg, section) []:technical
Common Name (e.g. server FQDN or YOUR name) []:www.learnindetail.blogsport.com
Email Address []:test@learnindetail@gmail.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: Enter
An optional company name []: Enter


5. Generate self signed certificate

$ openssl x509 -req -days 365 -in self-signed.csr -signkey self-signed.key -out self-signed.crt

Output :

Signature ok
subject=/C=IN/ST=Telangana/L=Hyderabad/O=ebhasha setu/OU=ebhashasetu/CN=sravan/emailAddress=your emailid
Getting Private key

6. Configure Self-Signed with Apache

a)enable ssl using command

$ a2enmod ssl

b) edit config file in

/etc/apache2/sites-available/default-ssl.conf

(back up this file prior to editing)

 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
<VirtualHost *:443>


    ServerAdmin localhost

    ServerName localhost

    DocumentRoot /var/www/html


ErrorLog ${APACHE_LOG_DIR}/error.log

    CustomLog ${APACHE_LOG_DIR}/access.log combined

#SSL Configuration

    SSLEngine on

    SSLCertificateKeyFile /etc/apache2/SSL/self-signed.key

    SSLCertificateFile /etc/apache2/SSL/self-signed.crt

    <Directory /var/www/html>

        Options  -Indexes -FollowSymLinks

        AllowOverride All

        Require all granted

    </Directory>

</VirtualHost>

Add/edit these lines to file and save it.

7. run command

$ apache2ctl -t

8. restart apache

$ sudo service apache2 restart

9. now access your localhost with https connection.

https://learnindetail.blogspot.com/

If you are purchasing an SSL certificate from SSL service providers, you may follow the same instructions till step 4 and they'll provide you with .crt file along with the instructions to install it. You may follow those instructions to install the SSL from service provider.

Monday, 18 September 2017

Escape HTML entities in JavaScript variables to render as plain text

Rendering strings containing HTML entities would require special attention as browser can only understand HTML tags and are formatted according to the HTML entities. So this post will help in dealing with such cases which will render HTML entities as plain text in browser.

First step:

1
2
3
4
5
function escapeHtml (string) {
        return String(string).replace(/[&<>"'`=\/]/g, function (s) {
        return entityMap[s];
      });
}

This is the major function that does the espcaping of HTML entities. As you can see it require an entityMap which contains all HTML entities that you want to require.

So here is our enitityMap:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var entityMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;',
        '/': '&#x2F;',
        '`': '&#x60;',
        '=': '&#x3D;'
};

As you can notice that these are the possible basic HTML entities, you can convert them to escape string that browser understands as plain text.

So what next:

We are all ready and I am giving you a sample text to test this.

1
2
text = escapeHtml(text);
$("#demo").html(text);

When you do all the above mentioned steps correctly, you would get the following result.

1
<स्क्रिप्ट भाषा = PHP> ... </ script> </ Body> # यह एक टिप्पणी है, और print <<<END $ 4 <tab> = <tab2 <tab> + <tab> 2// रिक्त स्थान और टैब <? Php ?>

Observe that all HTML tags are restored as it is.

Still having a problem you can check our live demo over here.



Most Effective Way To Reset Your Lost Password Or Forgotten Password Of MySQL.

You have to reset the password! steps for mac osx(tested and working) and ubuntu

Stop MySQL

$ sudo /usr/local/mysql/support-files/mysql.server stop


Start mysql in safe mode:

$ sudo mysqld_safe --skip-grant-tables

(above line is the whole command)

This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a  password:

$ mysql -u root

Now:

mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';


$ sudo /usr/local/mysql/support-files/mysql.server start

your new password is 'password'.

Downloading A Zip File Using Javascript Is Not Rocket Science! Know how!

Initially, the prerequisite for downloading a simple text file in javascript requires FileSaver.js. This can be downloaded from here.

Next step would be the creation of zip file.

1. Download jSZip and load it in your html.

2. Here comes the core part where we initalize jSZip and download a zip file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 var zip = new JSZip();         

    //skip this step if you don't want your files in a folder.
    var folder = zip.folder("example");
    folder.file("myfile1.txt", "HELLO WORLD IN 1ST FILE"); //requires filesaver.js
    folder.file("myfile2.txt", "HELLO WORLD IN 2ND FILE");

    //...so on until you have completed adding files

    zip.generateAsync({type:"blob"})
               .then(function(content) {
                //see FileSaver.js
                saveAs(content, "example.zip");
      });

Thursday, 2 February 2017

Where do I learn to code bots?

If you are well versed with API and has some hands-on experience with server-side programming ilke nodejs or php or python , then you could refer Messenger platform guide to build messenger bots. If you are newbie to programming, then using a bot engines would be a better option. Once you are familiar with messenger bot, you will be able to build bots on other platforms like telegram, slack etc.

I have listed few bot engines which makes it easy for you to build a bot.

wit.ai

gupshup bot builder

Chatfuel

Flowxo

API.ai

Botsify

Smooch

Botkit

I have built a few bots in messenger. Let me share them if that might help.

e Bhasha Dictionary bot

This is an English-Hindi dictionary bot. Enter any English word and it gives you the corresponding Hindi meaning.

e Bhasha News bot

This bot gives you the daily news updates, you can also subscribe to daily news alerts. This is available in 4 Indian languages(Hindi, Urdu, Punjabi, Telugu).

e Bhasha Quiz bot

This is a quiz bot that shoots general knowledge questions and is available in 3 Indian Languages(English, Telugu, Hindi ).

e Bhasha Translation bot

This is a translation bot that helps you translate any words or sentences in regional languages. Currently, this bot supports Hindi-Punjabi, Hindi-Urdu, English-Hindi language pairs.

We look forward to building many more bots as such for regional language support to help people eliminate the language barrier.

Happy Learning!