Infolinks

Sunday, July 15, 2012

Auto Chat Bot with Node.js and XMPP

Want something that respond your chats automatically, without your presence. If you want a system like that here i come for solution for that using Node.js and XMPP Protocol (Used in most chat system like google, facebook). So here we go step by step to implement a system like i have describe above.

First of all you have a system installed node.js, After it for use xmpp with node.js you need a node.js module node-xmpp. To install node-xmpp you just need run a command using npm

npm install node-xmpp

The node-xmpp module is entirely written in Node.js. The GitHub page of the project is located here. Refer other details about node-xmpp from GitHub page. Now we are going to create a chat bot.
First of all you need to include node-xmpp module in your code.

Example of a simple Auto Chat bot system


var xmpp = require('node-xmpp');

//Chat Rules Start from Here
var arr_rules_id = new Array("1","2","3","4");
var arr_rules_text = new Array("Hi","How are you","Where are You","Are you Coming");
var arr_rules_resp_text = new Array("Hi There i am auto chat bot","I am fine","I am online","No never");
//Chat Rules Ends Here

//XMPP Account Details Starts from Here
var client_id = "your_chat_account@server.com"; //Use any XMPP Supported Account like Gmail
var client_pwd = "your_chat_account_password";
var client_host = "XMPP HOST of Your Account";  //talk.google.com for gmail
var client_port = "XMPP port for Host";   //5222 for gmail
var status_msg = "I am Online";   //Set it as you want
//XMPP Account Details End Here

//Now Creating XMPP Client
var cl = new xmpp.Client({ jid: client_id,
password: client_pwd,
host: client_host,
port: client_port
});
//Client Created

//Now Set the Presence of Bot
cl.on('online', function() {
    cl.send(new xmpp.Element('presence', { }).
c('show').t('chat').up().
c('status').t(status_msg)
);
console.log("Connected");
});

//Receiving of Stanza's Starts(Messages are also recieved)
cl.on('rawStanza',
      function(stanza) {
console.log(stanza);
 if (stanza.is('presence') && (stanza.attrs.type == 'subscribe')) {
            cl.send(new xmpp.Element('presence', { to: stanza.attrs.from, type: 'subscribed' }));
        }
if (stanza.is('message') &&
// Important: never reply to errors!
stanza.attrs.type !== 'error') {

// Swap addresses...
var frm = stanza.attrs.from;
var body = stanza.getChild('body');
console.log(stanza);
console.log("\n"+body);
if (!body) {
    return;
  }

var message_recv = body.getText();   //Get Incoming Message
var index = checkarr(arr_rules_text, message_recv);   //Check for incoming message's response text index in array

function checkarr(arr,mes)
{
for(var i=0; i<arr.length; i++) {
        if (arr[i].toLowerCase() == mes.toLowerCase())
        {
        return i;
        }
    }
    return 'notvalid';
}

if(index!='notvalid')     //If message keyword matches then reply back 
{
    var response = arr_rules_resp_text[index];
    cl.send(new xmpp.Element('message', { to: frm, type: 'chat' }).
        c('body').t(response)
    );
}
else
{
    cl.send(new xmpp.Element('message', { to: frm, type: 'chat' }).
        c('body').t("Not Response Found Against Keyword")
    );
}
}
});
cl.on('error', function(err) {
    console.error(err);
});

cl.on('conn-close', function() {
console.log('connection ends');
});

So here we have done all stuff to do chat automatic response bot now run this script and your account goes online. Below i have attach sample screenshot of autochat.


Saturday, July 14, 2012

Custom Infowindow / InfoBox to Google Maps API V3

Here i am going to tell you that how to create custom infowindow/InfoBox with Google Maps Api V3 .
Here some steps to achieve this.. To use google maps first of all you need to insert google maps API in your code.
Necessary file can be downloaded from here
<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=true" type="text/javascript"></script>

Now include infobox.js in your code
<script src="infobox.js" type="text/javascript"></script>

Now here is a simple map example containing custom infobox
<script type="text/javascript">
var map;
function initialize() {
        var myOptions = {
          zoom: 12,
          center: new google.maps.LatLng(-34.397, 150.644),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
            myOptions);
  var marker = new google.maps.Marker({
  position: map.getCenter(),
  map: map,
  title: 'Click to zoom'
  });

      var boxText = document.createElement("div");
      boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: #999; border-radius:5px; padding: 5px; color:#FFF;";

      boxText.innerHTML = "Hello This is a custom styled InfoWindow<br />You Can Design it as you want";
   var myOptions1 = {
                 content: boxText,
                 disableAutoPan: false,
                 maxWidth: 0,
                 pixelOffset: new google.maps.Size(-140, 0),
                 zIndex: null,
                 boxStyle: { 
                 background: "url('tipbox.gif') no-repeat",opacity: 0.85,width: "380px"
                 },
                 closeBoxMargin: "10px 2px 2px 2px",
                 closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
                 infoBoxClearance: new google.maps.Size(1, 1),
                 isHidden: false,
                 pane: "floatPane",
                 enableEventPropagation: false
        };
        var ib = new InfoBox(myOptions1);
        ib.open(map, marker);
        google.maps.event.addListener(marker, "click", function() { 
        ib.open(map, marker); 
 });
      }


</script>


Add above scripts in your page's head tag.
Now initialize the map
<body onload="initialize();">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>


That's all now you can view your map with custom InfoWindow.

How to use Node.js with mysql


New to Node.js and want to know that how to use most famous open source database 'mysql' with it. Here i have a big surprise for you - it is surprisingly very easy to get MySQL working with Node.js. My this post will show you that how you can do it
So for use mysql with node.js first of all you need a node.js module mysql. To install mysql module just use following command using npm
$ npm install mysql


The mysql module is entirely written in Node.js, and implements an async MySQL client. The GitHub page of the project is located here , refer to it for other details about the API. Once you have installed the module, you can include it in your Node.js files and configure it this way.

var mycon = require('mysql'); 


var HOST = 'Your_MYSQL_HOST'; 
var PORT = Your_MYSQL_PORT; //Default 3306
var MYSQL_USER = 'Your_MYSQL_USER'; 
var MYSQL_PASS = 'Your_MYSQL_PASSWORD'; 
var DATABASE = 'Your_MYSQL_DATABASE';


var mysql = mycon.createClient({ 
            host: HOST, 
            port: PORT, 
            user: MYSQL_USER, 
            password: MYSQL_PASS, 
            });


mysql.query('use ' + DATABASE);


Now you can execute MySQL commands on the database.
Here is an example of mysql select query


mysql.query('select id,emp_name,emp_dep from TABLE_NAME where emp_salery > 300000',
function(err, result, fields) {
    if (err) throw err;
    else {
        console.log('Employees with salary greater than 300000 \n');
        for (var i in result) {
            var empdata = result[i];
            var empid = empdata.id;
            var emp_name = empdata.emp_name;
            var emp_dep = empdata.emp_dep;
            console.log("Emp ID : "+empid+"  Emp Name : "+emp_name+"  Emp Dep : "+emp_dep);
        }
    }
});


Now Here is an example of mysql insert query

mysql.query('insert into TABLE_NAME (emp_name, emp_dep, emp_salery) values ('XYZ', 'ABC', 500000)',
function selectCb(err, results, fields) {
    if (err) throw err;
    else 
    {
    console.log("Mysql Query Successfully Executed");
    }
});

Same process is used for mysql update query, Now To get the last insert ID, you use the insertid property of the insert result object.

client.query('INSERT INTO TABLE_NAME(column1, column2) values('a','b')', function(err, ress) {
    console.log(ress.insertId);
});


So above describe steps are used to use mysql with node.js. There are also many modules available for use mysql with node.js, but this is the best module which fulfill your requirements.

Tuesday, April 3, 2012

Hide php extension -- URL Rewriting on Apache using htaccess

URL Rewrite using .htaccess on Linux Apache and Wamp Server
URL rewriting can be one of the best and quickest ways to improve the usability and search friendliness of your site. It can also be the source of near-unending misery and suffering. Definitely worth playing carefully with it - lots of testing is recommended. With great power comes great responsibility, and all that.

URL rewriting on Linux Apache and wamp
For rewriting url on Centos Please do these steps.
  1. First go to '/etc/httpd/conf/httpd.conf' and for wamp left click on wamp icon and go to Apache then httpd.conf and uncomment - #LoadModule rewrite_module modules/mod_rewrite.so and #AddModule mod_rewrite.c, so do so please remove trailing #.

  2. Now Edit directory section in this file for directory /var/www/html and change 'AllowOverride none' to 'AllowOverride All'.

    Eg.
    Options Indexes FollowSymLinks
    AllowOverride none
    Order allow,deny
    Allow from all
    ;
    TO

    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    ;

  3. Now make a file in server root directory '/var/www/html' name .htaccess and write these line in this

    Options +FollowSymlinks

    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteCond %{REQUEST_FILENAME}\.php -f

    RewriteRule ^(.*)$ $1.php


  4. Now this will remove php extension in your file so now if you want to open index.php then write only http://url/index only instead of http://url/index.php

Thursday, March 29, 2012

Install phpMyAdmin on Linux --- CentOS , Ubuntu

Here are the Steps for installing phpMyAdmin in Linux Platform...
  1. Get the latest phpMyAdmin Copy from sourceforge by typing on terminal..... wget -c http://sourceforge.net/projects/phpmyadmin/files/phpMyAdmin/3.4.10.1/phpMyAdmin-3.4.10.1-english.tar.gz
  2. Move this to /var/www directory for ubuntu or /var/www/html/ directory for centos by........ mv source_file destination eg. mv phpMyAdmin-3.4.10.1-english.tar.gz /var/www/html/
  3. Now cd to /var/www/html directory and Extract it by typing tar xvfz phpMyAdmin-3.4.10.1-english.tar.gz
  4. Now Move Extracted phpMyAdmin-3.4.10.1-english to phpmyadmin by typing...... mv phpMyAdmin-3.4.10.1-english/ phpmyadmin/
  5. Now cd /var/www/html/phpmyadmin/ directory
  6. Copy configuration file ...... cp config.sample.inc.php config.inc.php
  7. Now vi config.inc.php and change......
  8. $cfg['Servers'][$i]['auth_type']=’cookie’; to $cfg['Servers'][$i]['auth_type']=’http’;
  9. $cfg['Servers'][$i]['nopassword'] = FALSE; to $cfg['Servers'][$i]['nopassword'] = TRUE;
  10. Now Restart Apache Server and access phpmyadmin by typing your local server url .... http://localhost/phpmyadmin/