Get lyrics for any song using XMPP and PHP right into your IM – Add [email protected]

XMPP is soon finding it’s way into real time applications other than just chat. I have combined JAXL (Jabber XMPP client library written in PHP) and the API from lyricsfly.com to build a real time chat bot which can assist you with lyrics for any song. You can start using it by simply adding [email protected] to your IM account (e.g. Gtalk, Jabber etc). In this blog post, I will explain in brief the working of lyricsfly bot and how you can integrate XMPP into your own application.

Try out [email protected]
Follow the following steps to get the bot working for you:

  • Login to your gtalk account using any of the IM available
  • Press Add Contact
  • Add [email protected] as your chat buddy
  • Send a chat message in following format “Song Title – Song Artist” e.g. “one – metallica”
  • You should see something like this: lyricsfly@gtalkbots.com Demo for "one-metallica"

Working of [email protected] with Jaxl
Here is in brief the working of lyricsfly bot using Jaxl client library:

  • When someone sends a message like “one – metallica” to the bot, eventMessage() method is called inside jaxl.class.php
  • eventMessage then extracts the song title and artist name from the message using PHP explode. Filter the title and artist names for allowed characters.
  • eventMessage also calls lyricsfly API and fetch the lyrics. Finally it sends the lyrics as message to requester.
  • eventMessage also uses memcached to cache the lyrics. It decreases both response time and load on lyricsfly servers
  • Bot also keeps a count of number of queries from a particular user. Since it is still under development, currently there is a limit on number of lyrics you can fetch in a single day.

Making your own custom bot

  • Checkout latest from the trunk
    sabhinav$ svn checkout http://jaxl.googlecode.com/svn/trunk/ jaxl-read-only
  • Edit config file with your bot username, password and jabber servers
  • Run from command like
    php index.php
  • To customize the bot modify eventMessage and eventPresence methods of Jaxl class inside jaxl.class.php

For a full fledged running bot example code, edit index.php and include jaxl4dzone.class.php instead of jaxl.class.php and re-run the bot.

Have fun and enjoy singing songs along with the lyrics.

How to broadcast a message to your Gtalk friends using JAXL?

In this era of social media we all look forward to easy and utility tools to easily market our site and blogs. In this post I will demonstrate a ready to use script, which will help you broadcast your message to everyone on your gtalk friend list in one go.

jaxl4broadcast.class.php
jaxl4broadcast.class.php is an extension of JAXL library. This extension simply saves all your buddy list in an array while connecting with Gtalk servers, and then send out your custom message to all of them in one go. The code that will do the task:

    function setStatus() {
      $this->sendStatus($this->status);
      print "Setting Status...n";
      print "Donen";

      foreach($this->rosterList as $buddy) {
        print "Sending message to ".$buddy."n";
        $this->sendMessage($buddy,"Message broadcasted using *JAXL Library http://code.google.com/p/jaxl*");
        sleep(1);
      }

      /* Now loggout of the system */
      exit;
    }

PS: You need to checkout the latest version of xmpp.class.php for jaxl4broadcast.class.php to work. jaxl-1.0.4 doesn’t include the latest checked in xmpp.class.php

Using jaxl4broadcast.class.php

  • Checkout the latest version of JAXL library from here
  • Open config.ini.php, replace myproductionuser => gmail id and password => gmail password
  • Open index.php, replace jaxl.class.php => jaxl4broadcast.class.php
  • Open command line window (for windows) and shell prompt (for *nix). Navigate to the checked out directory
  • From command prompt run php index.php
  • If everything goes alright, you will see something like the image below
  • See list of known issues if you are new to JAXL and having trouble

jaxl4broadcast

Other JAXL Extensions you may want to checkout:

Happy Broadcasting!

How to get dzone feeds as IM using JAXL? Add [email protected]

The most funny part of knowing XMPP protocol is that you can execute all your daily web needs using it. Be it playing anagram online or achieving your status messages. And your life gets easy if you are using an XMPP Client Library like JAXL.

Here I have tried to create a simple bot which allows you to read newest links posted on dzone category wise. Simply add [email protected] in your gtalk messenger and start by typing options.

Available options are:

  • frontpage: Will send you latest links on frontpage.
  • queue: Will send you latest links in queue.
  • tag: Send in a tag e.g. php,java,xml and you will get latest links for the particular tag

Here is modified eventMessage() method of JAXL library powering [email protected]:

    function eventMessage($fromJid, $content, $offline = FALSE) {

      // If the message is not an offliner
      if(!$offline) {
        if($this->restrictJid && !in_array($this->getBareJid($fromJid),$this->authorizedJid)) { // Block un-authorized users
          $this->logger->logger($fromJid." tried using this service by sending:n".$content);
          $message = 'You are not authorized to use this service';
          $this->sendMessage($fromJid,$message);
          return TRUE;
        }
        else {
          $content = strtolower(trim($content));

          // Build RSS Feed URL depending upon passed IM
          if($content == "options") {
            $message = "Available options are:n";
            $message .= "*1. frontpage:* Will send you latest links on frontpage.n";
            $message .= "*2. queue:* Will send you latest links in queue.n";
            $message .= "*3. tag:* Send in a tag e.g. php,java,xml and you will get latest links for the particular tagn";
            $this->sendMessage($fromJid,$message);
            return TRUE;
          }
          else if($content == "frontpage") $url = "http://www.dzone.com/links/feed/frontpage/rss.xml";
          else if($content == "queue") $url = "http://www.dzone.com/links/feed/queue/rss.xml";
          else $url = "http://www.dzone.com/links/feed/frontpage/".$content."/rss.xml";

          // Generate cache file location
          $cache_file = "cache/dzone/".md5($url)."-".$content.".rss";

          // If cache file is not older than 900 seconds (15 min)
          if(file_exists($cache_file) && (filemtime($cache_file) > time() - 900)) {
            $this->logger->logger("RSS already found cached...");
          }
          else { // else fetch a fresh copy of RSS
            $this->logger->logger("Fetching RSS for url:n".$url);
            $head = $this->fetchWebURL($url);
            if($head['errno'] == 0 && $head['http_code'] == 200) {
              $this->logger->logger("Fetched successfully...");
              $data = $head['content'];
              $fh = fopen($cache_file,"w");
              fwrite($fh,$data);
              fclose($fh);
            }
            else {
              // Send a message saying no such feed exists
              $this->logger->logger("Failed to fetch the RSS feed...");
              $message = 'No feed exists for the passed keyword: '.$content;
              $this->sendMessage($fromJid,$message);
              return TRUE;
            }
          }

          // Parse RSS Feed
          $r = &new XML_RSS($cache_file);
          $r->parse();
          $NumberOfFeeds = count($r->getItems());
          if($NumberOfFeeds > 0) {
            $message = '';
            foreach($r->getItems() as $key => $item) {
              if($this->count < $this->maxResults) {
                $message .= "*".$item["title"]."*n";
                $message .= $item["link"]."n";
                $message .= $item["description"]."nn";
                $this->count++;
              }
              else {
                break;
              }
            }
            $message .= "powered by *Jaxl* http://code.google.com/p/jaxl"."nn";
            $this->sendMessage($fromJid,$message);
            $this->count = 0;
            return TRUE;
          }
          else {
            // Send a message saying no feed found
            $message = 'No feed was found for passed keyword: '.$content;
            $this->sendMessage($fromJid,$message);
            return TRUE;
          }
        }
      }
      else {
        // Send an appropriate message
        $this->logger->logger($fromJid." sent an offliner saying:n".$content);
        return TRUE;
      }
    }

To run this sample application you need:

  • JAXL Library (http://code.google.com/p/jaxl)
  • XML_RSS Package (pear install XML_RSS)
  • Create a directory cache/dzone where this application will cache all rss files
  • Include jaxl4dzone.class.php in index.php, instead of jaxl.class.php and run ‘php index.php’ from command line to start this application

Checkout the complete code and JAXL library from http://code.google.com/p/jaxl.

Now browse new links even when dzone is down for maintenance 😛
Do let me know about your feedbacks 🙂

Introducing JAXL – Open Source Jabber XMPP Library

Introduction

JAXL stands for “Jabber XMPP Library“. For fun, it stands for “Just Another XMPP Library

This library currently supports following features:

  • Connect to a Jabber Server (e.g. Gtalk)
  • TLS Encryption
  • DIGEST-MD5 and PLAIN authentication mechanisms
  • Roster Support

Library comes with the following class files:

  1. config.ini.php : Holds your jabber account and mysql connection information
  2. mysql.class.php : Basic MySQL connection class used to insert received messages and presence into MySQL database
  3. logger.class.php : A very basic logger class which allows you to log all XML stanza’s send and received from jabber server
  4. xmpp.class.php : Base XMPP class library which implements the XMPP protocol
  5. jaxl.class.php : JAXL class which extends XMPP class library. Should be the starting point for your application.
  6. index.php : After building your application in jaxl.class.php, you finally initializa and call your methods here

Source Code
JAXL is hosted at Google Code. Checkout full source code from here:
http://code.google.com/p/jaxl

Google Groups
jaxl
Visit this group

How to use JAXL:
JAXL Client Library is highly structured. There is a base XMPP class library (xmpp.class.php) and a JAXL class library (jaxl.class.php) which is derived from the base XMPP class library.

Base XMPP class library implements the XMPP protocol and it also provides you with two extendable methods named eventMessage() and eventPresence(). These methods are internally called when a message or presence XML Stanza is received from the Jabber server.

Jaxl.class.php must be the starting point for all your applications. Simply customize the eventMessage() and eventPresence() Method for your application. Other methods which might interest you while customizing them are:

  1. sendMessage($jid,$message) : For sending message to a particular Jid
  2. sendStatus() : To set your status message
  3. roster(‘get’) : To get list of roster
  4. roster(‘add’,$jid) : Add a new contact in roster list
  5. roster(‘remove’,$jid) : Remove a contact from roster list
  6. roster(‘update’,$jid,$name,$groups) : Update a particular contact in roster
  7. subscribe($jid) : Subscribe for presence of a particular $jid

This library includes the following files:

Config File (config.ini.php)
You specify all your jabber account username and password in this file. For development environment keep $env = “devel” and for production simply change it to $env = “prod”

  // Set an enviornment
  $env = "prod";

  // Log Level for logger class
  $logEnable = TRUE;

  // Log in MySQL database
  $logDB = FALSE;

  $key = array("prod"=>array("user"=>"myproductionuser",
                             "pass"=>"password",
                             "host"=>"talk.google.com",
                             "port"=>5222,
                             "domain"=>"gmail.com"
                            ),
              "devel"=>array("user"=>"mydevelopmentuser",
                             "pass"=>"password",
                             "host"=>"localhost",
                             "port"=>5222,
                             "domain"=>"localhost"
                            )
              );

  $db = array("prod"=>array("dbuser"=>"root",
                            "dbpass"=>"password",
                            "dbhost"=>"localhost",
                            "dbname"=>"jaxl"
                           ),
             "devel"=>array("dbuser"=>"root",
                            "dbpass"=>"password",
                            "dbhost"=>"localhost",
                            "dbname"=>"jaxl"
                           )
             );


MySQL Class (mysql.class.php)
This is a basic MySQL connection class used to insert received messages and presence into MySQL database

Base XMPP Class (xmpp.class.php)
You should not worry about this class. Until and unless you are aware of what are you trying to achieve you should not touch this class file.

Logger Class (logger.class.php)
This is a basic logger class. It help you log XML send to and received from jabber server. Might prove helpful in debugging and if you are interested in learning the core of XMPP Protocol.

Extended JAXL Class (jaxl.class.php)
You will be customizing eventMessage() and eventPresence() methods here.

    function eventMessage($fromJid, $content, $offline = FALSE) {
      if($offline) {
        $this->sendMessage($fromJid,"Hi, Thanks for your offline message");
      }
      else {
        $this->sendMessage($fromJid,"Hi, Thanks for your message");
      }

      if($this->logDB) {
        // Save the message in the database
        $timestamp = date('Y-m-d H:i:s');
        $query = "INSERT INTO message (FromJid,Message,Timestamp) value ('$fromJid','$content','$timestamp')";
        $this->mysql->setData($query);
      }
    }

    function eventPresence($fromJid, $status, $photo) {
      // Change your status message to your friend's status
      $this->sendStatus($status);

      if($this->logDB) {
        // Save the presence in the database
        $timestamp = date('Y-m-d H:i:s');
        $query = "INSERT INTO presence (FromJid,Status,Timestamp) value ('$fromJid','$status','$timestamp')";
        $this->mysql->setData($query);
      }
    }

In above example I have done 4 things:

  • Sends back a message saying “Hi, Thanks for your offline message”, when I receive a offliner.
  • Sends back a message saying “Hi, Thanks for your message”, when I receive an IM from my friend.
  • Change my status message, as and when I receive a status update from my friends.
  • Save messages and presence into database if $logDB = TRUE in config.ini.php

Final Call (index.php)

  /* Include Key file */
  include_once("config.ini.php");

  /* Include JAXL Class */
  include_once("jaxl.class.php");

  /* Create an instance of XMPP Class */
  $jaxl = new JAXL($key[$env]['host'],    // Jabber Server Hostname
                   $key[$env]['port'],    // Jabber Server Port
                   $key[$env]['user'],    // Jabber User
                   $key[$env]['pass'],    // Jabber Password
                   $key[$env]['domain'],  // Jabber Domain
                   $db[$env]['dbhost'],   // MySQL DB Host
                   $db[$env]['dbname'],   // MySQL DB Name
                   $db[$env]['dbuser'],   // MySQL DB User
                   $db[$env]['dbpass'],   // MySQL DB Pass
                   $logEnable,            // Enable Logging
                   $logDB                 // Enable MySQL Inserts
                  );

  try {
    /* Initiate the connection */
    $jaxl->connect();

    /* Communicate with Jabber Server */
    while($jaxl->isConnected) {
      $jaxl->getXML();
    }
  }
  catch(Exception $e) {
    die($e->getMessage());
  }

Instant Messenger Powered by JAXL
I am pleased to announce 3 months after release of JAXL, 1st Instant Messenger powered by JAXL. Currently the instant messenger is in testing phase and will be released after some 3-4 weeks of thorough testing. Meanwhile here is the first clip shot:

Disclaimer
Currently this library is being developed and used at Gtalkbots.com . Though it is thoroughly tested and being used, I still recommend not to use it on production servers. Mainly, since it is heavily customized for Gtalkbot’s usage. I am releasing it, as I see it of use for the community worldwide. If you want to use it, use at your own risk. Let me know of any changes you make to this library. In future I look to make this library more generic.

Enjoy and let me know of any bugs, feedbacks, enhancements or any abuse you may want to pass through if it doesn’t work for you 😛

You should be running index.php using command line and not browser (recommended). This class is currently highly customized for Gtalkbots usage and works perfectly with Gtalk Servers.

What happens before you finally viewed this page?

Since past 1 week or so I am trying to make a small tiny light weight web server of my own, and for the same I have been referring to dozens of papers, websites, people and what not. I still haven’t finished making one, I am still toggling between Java and Python, since both seems to satisfy my needs and unfortunately I am master in none. While I was digging deep into the theory of how can I make a web server, I cleared many other concepts of mine, which finally leads to this post.

“What happens before you finally viewed this page/post of mine ?” – Many of you might know behind the scene stories and many like me might have a vague idea. But for the good of all those who don’t know and for people like me who needs a reference, I thought of better penning it down.

Lets see what possibly is going in the background:

  1. Suppose you type in http://www.yahoo.com in your web browser or clicked this link on some other page.
  2. Your browser see’s the above URL, and identifies it as a HTTP protocol.
  3. Then it breaks the URL into Protocol, Domain Name, File Name (in above case no file name is specified)
  4. Browser contacts its default DNS (Domain Name Server), which helps it with an IP Address. DNS is a huge distributed database which contains mapping of URL’s to IP Address. Your browser’s default DNS might or might not have the required mapping of URL to IPAddress.
  5. If it don’t have the IPAddress corresponding to http://www.yahoo.com , it will try to contact other root name servers for the required IPAddress.
  6. If it already have the IPAddress corresponding to http://www.yahoo.com (which is possible if a similar request has already been made recently) it will provide the required IPAddress to your browser.

And finally your browser then connects to the IPAddress it received and servers you the page returned back by Yahoo!. If you are still not clear about the process, following practical example might help you.

  1. I thought of starting a website and decided to name it as http://gtalkbots.com
  2. Firstly, I needed to register domain name with a registrant. For e.g. In my case I blocked the domain name gtalkbots.com with godaddy.com.
  3. Secondly, I needed to have a machine i.e. a place where I can have all my HTML, PHP files. So I bought a VPS (Virtual Private Server)
  4. Thirdly, I had to link the above two i.e. when someone types in http://gtalkbots.com in his browser, it should come to my VPS where I have my HTML files.
  5. For linking the domain name and my VPS, I simply make an ARecord entry at godaddy, telling it the IPAddress of my VPS. In turn when you type in http://gtalkbots.com in your browser, GoDaddy redirects you to my VPS. (Google for ARecord and CNAME for more details)
  6. Last 4 entries in the image above are for linking my gtalkbots.com domain with my google apps account, so that I can send and receive my gtalkbots.com email on google apps.

There is a lot more to it, however the info above is more than sufficient to understand the basics of
“What happens before you finally viewed this page/post of mine ?”

[email protected] – Online gaming enabled on Gtalk

Anagram, many of you might be familiar with it or even played many a times back in school and colleges. Its a simple text based game, where you are given a jumbled word and you need to re-arrange it. E.g. You will be given huldos and you need to quickly identify that as should.

So getting bored back in college or office, add [email protected] and type anagram to start gaming. Play and score well. Your score will turn up on the Gtalkbots front page. They have kept this game open for the world i.e. one can play this game even without registering at Gtalkbots.

A few important points:

  1. Add [email protected] as your friend in Gtalk Messenger.
  2. Type rules to read them before you start gaming.
  3. Type anagram to start gaming.
  4. You will be given a jumbled word which you needs to rearrange and reply back.
  5. If your answer is correct you get 10 Points.
  6. If your answer is not correct and you are finding it tough to solve it, Type hint to get a clue, and a clue will be sent to all users playing the game.
  7. DO NOT FORGET to type exit when you are finished gaming. If you forget to do so, you will be considered as a part of next round being played and eventually your average score decreases.
  8. If total number of wrong answers = 5 (including all users), the bot will automatically reply back with correct answer and moves to the next word.

So try out and enjoy.

Save your and your friend’s status messages. Share and promote your website through your status

Hello Everyone,

http://gtalkbots.com

Here is this new website which help you save your and your friends Gtalk status messages. It also provides a social bookmarking feature with a different edge.

Are you fed up with posting your website and blogs at digg.com, delicious, stumble or any other such site there. If not, you must surely be fed up with the hard work you need to do to make sure your link reach out to millions out there. Well through this site, you just need to put your blog and site link as your gtalk status message and this site will  make sure it reaches to the relevant audience out there without any sweat from your.

Try out, promote, enjoy, comment and let me know your feedbacks.

GTalk Status Message Collector

Hello Everyone,

I have started http://gtalkbots.com , based on the example demonstrated here. Try out and Help spreading the word.

I am not a big fan of twitter, but after I heard they do something similar to what I will be demonstrating here. I thought of building this one out. So here is my demo application, also known as GTalk Chat Bot.

Do the following things to get started:

  1. Add [email protected] in your GTalk Messenger.
  2. It will collect your status messages as and when you change them.
  3. You can view all your status messages by visiting this URL : http://abhinavsingh.com/webdemos/chatbot/
  4. The status messages will reflect at the above URL by the end of the day. (I had to do this because the server where I have my bot running i.e. my VPS is different from where my personal site is hosted, hence we have this restriction)
  5. Come back anytime after a day and you can see your status messages over time.

I am currently testing this application, which is running 99.99% bug free. Once I am satisfied with it, I will put the code for download with a possible explaination.

Meanwhile enjoy the bot.

Thanks.