How to use JAXL (Jabber XMPP Library in PHP) to import Gtalk contacts of any user

JAXL is an open source Jabber XMPP Client library written in PHP. It provides a self titled class JAXL which implements XMPP protocol. It can be extended to write custom event handler for every message or presence received. Developers are using JAXL for developing real time applications. Checkout 5 exciting gaming bots you can make using JAXL.

However one thing which goes un-noticed is that JAXL can also be used to import Gtalk contacts of any user. This is infact one of the very first thing which JAXL class do, after successful authentication with the Gtalk servers i.e. import the authenticated user contact list. In this blog post I will demo a sample script to import any user contact list from google servers.

Importing Gtalk contacts using JAXL

  1. Download and extract jaxl-1.0.4.rar
  2. Edit config.ini.php and update credentials of the user whose contact list we are trying to import:
      $key = array("prod"=>array("user"=>"mailsforabhinav",
                                 "pass"=>"xxxxxx",
                                 "host"=>"talk.google.com",
                                 "port"=>5222,
                                 "domain"=>"gmail.com"
                                ),
    
  3. Open jaxl.class.php and modify the code as below:
        function setStatus() {
          // Set a custom status or use $this->status
          $this->sendStatus($this->status);
          print "Setting Status...n";
          print_r($this->rosterlist); // Print the contact list on the console
          print "Donen";
          exit;
        }
    
  4. Finally run from command line to retrieve gtalk contacts of the authenticated user.
    php index.php

One can easily modify the above code to save user contacts in a database.
Also one can echo json_encode($this->rosterlist) in response to an Ajax call from the browser.

Enjoy and leave your comments.

5 exciting (gaming) bots you can create using Jaxl (Jabber XMPP Library) in PHP

Jaxl is an open source XMPP client library written in PHP. The object oriented structure of JAXL allow developers to build various extensions using Jaxl library as their base. If used intelligently, JAXL client library is capable of doing more than just chat message transfers. Here are a few applications where developers have tried using JAXL for delivering more than just chat messages:

“I used your library to develop a prototype that connects dynamically some users to a XMPP server if an external event is detected. The script runs like a daemon. Because of your object-oriented class design it was very easy to set up dynamic number of parallel XMPP sessions. I would like to use your library as part of a software that integrates telephony and XMPP functionality. The software will also be licenced unter GPL. Thanks again for your great work.”

“I’m thinking on creating a symfony plugin for jaxl library. I’ve worked before with the Jabber php library. This one of yours is much nicer! And it is working really nice, good job! “

The possibilities are endless. In this blog post I will discuss various possible use cases of JAXL client library starting from, creating an 24×7 online chat bot, broadcasting messages to gtalk friend list, rss feed aggregator, custom out of office email bot for gmail and google apps user, and finally a simple game using Jaxl client library. (similar to anagram gaming bot [email protected])

Setting up the environment
Jaxl is hosted on Google Code. Checkout the latest version of JAXL client library:

svn checkout http://jaxl.googlecode.com/svn/trunk/ jaxl-read-only

Alternately you can download the latest version of Jaxl from here:
http://jaxl.googlecode.com/files/jaxl-1.0.4.rar

From here on I will assume you have all the library files in a folder called jaxl. You should see the following set of php files inside the jaxl folder:

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

You will also see a bunch of other php files: jaxl4broadcast.class.php, jaxl4gmail.class.php, jaxl4dzone.class.php, which are extensions written using Jaxl library as their base. We will discuss them all as we proceed on the blog.

Another point I would like to discuss before we go ahead, is the structure of Jaxl client library. XMPP class is written in xmpp.class.php php class file which implements the XMPP protocol. It takes care of user authentication, user presence (available, busy, idle), user status, sending and receiving messages and everything which we will see as we proceed on the blog. JAXL class extends XMPP class in jaxl.class.php php file. We will develop all our bots/applications in jaxl.class.php php file and will never require to touch the base xmpp.class.php file. Finally, index.php is the file which invokes our application written in jaxl.class.php. As a convention, we rename jaxl.class.php to jaxl4app.class.php where app is the name of our application.

XMPP class defined in xmpp.class.php passes program handle to various methods whenever an event occur. Following 4 methods are of our use, while developing an application inside jaxl4app.class.php file:

  • eventMessage($fromJid, $content, $offline = FALSE) : This is the method where XMPP class passes the handle, when it receives a message. The message can be either online or offline, which is indicated by the $offline parameter being passed to this method. Other two parameters received are $fromJid which is the jabber id of the user sending the message. e.g. [email protected], and $content which is the actual message sent by the user identified by $fromJid
  • eventPresence($fromJid, $status, $photo) : This is the method where XMPP class passes the handle, when it receives a presence i.e. notification about status change of a user. A change in status event is triggered by either user changing his status text or by user changing his online presence i.e. available, idle, busy. $fromJid is the parameter passed to this method which is the jabber id of the user who changed his status. $status is the new status set by the user.
  • eventNewEMail($total, $thread, $url, $participation, $messages, $date, $senders, $labels, $subject, $snippet) : XMPP library also implements the Gmail Notification extension for XMPP protocol, and passes the handle to eventNewEMail() method when ever a new email is received on Gmail or Google Apps mail. One of the real life example of this protocol called Gmail Notification can be seen using Gtalk. Gtalk will pop up a window when ever you receive a new email on Gmail. For more detail about various parameters passed to this method refer the Gmail Notification documentation.
  • setStatus() : XMPP class passes the handle to this method before setting the status of the bot/application we intent to run using Jaxl library. Customize this method for setting custom status messages on logon or anytime during the execution of the application.

In 99.99% of the applications which we will intent to build, will not require handle to other events which happen in the background and handled by the base XMPP class. For more information about all the events refer this blog post. Behind the scenes – How and What XML’s are exchanged by JAXL

Jaxl also provide provisions to switch your bot between production and development environment by a simple change in the config.ini.php file. $env parameter (allowed values are “prod” or “devel”) decides what environment do you want to run this bot on. $env is set to “devel”, when you are developing your bot/application and don’t want to connect to a production jabber server repeatedly during development. Setting $env to “prod”, will configure the bot/application to connect to the production jabber server.

1. My first bot: Creating an 24×7 online status aggregation bot
This was how I started working on JAXL. I wanted to collect status messages of all my gtalk friends. I also wanted to plot on a graph, when and which of my gtalk friends come online or go offline. A basic example of this graph can be seen on my timeline at Gtalkbots.

The good thing in Jaxl library is that, by default it comes with a built-in bot capable of doing the above tasks for us. (because this is how i started working on Jaxl, hence is the default behaviour). Here is how you can configure Jaxl for the same:

  • Choosing an environment: Open config.ini.php and choose an environment. Since we want to collect information about all our friends on gtalk, we will set $env="prod". This will allow our bot to connect to the jabber servers hosted at talk.google.com (see config file). Also set $logDB = TRUE;, which will enable logging of user information to the MySQL database.
  • Updating user credentials: Register a username at Gmail (if you don’t have one already) and update the username and password of this user in the config file. Our bot will use these credentials to authenticate with the google talk servers. Add a few friends using gtalk to start with. Also update your MySQL database hostname, username and password. Leave the database name as jaxl.
  • Creating jaxl database: Run the database.sql file against your MySQL database. It will create a database called jaxl with two tables called message and presence. Our application will use these tables for storing information about our gtalk friends.
  • Creating the bot: jaxl.class.php by default is ready to work as we want it to. It will log all your gtalk friend’s information in the MySQL database if $logDB is set to TRUE inside the config.ini.php file. Also by default it replies back a welcome message for every message received (online or offline). You may want to un-comment that section of the code as of now.
  • Running the bot: Open command line (windows) or the terminal window (unix, mac) and migrate to the jaxl folder. (Remember you cannot run your application with something like http://localhost/jaxl in your browser. XMPP is a TCP-IP level protocol and not made for running directly using HTTP protocol i.e. browsers. However, we can use BOSH extension of XMPP protocol to make it run over HTTP. Jaxl currently doesn’t support BOSH extension. It’s currently under testing). Now simply run the following command.
    sudo php index.php

    on the terminal. You should see something like this on your terminal: jaxl-jabber-xmpp-library-demo-1

    To debug more while development, you should enabled logging in the config file. Jaxl library will start logging every xmpp stanza sent or recieved to the google talk servers. This is also a good way of learning more about the internals of xmpp protocol.

  • Running the bot 24×7: One of the most common query i get (specially from college enthusiasts) is how to run their applications 24×7. Just like the anagram gaming bot at gtalkbots ([email protected]). Run the following command on your terminal to run your application as a background process (only possible on unix or osx, not on windows):
    sudo nohup php index.php > log/logger.log &

    . This will start the bot as a background process and hence the bot will not stop its execution even if you close the terminal window. When you want to kill your application, simply search for the process id of your application using:

    ps aux | grep index.php

    . Note the process id corresponding to your application and issue

    kill -9 process_id

    to kill the application.
    jaxl-jabber-xmpp-library-demo-3

2. Broadcasting messages to your gtalk friend list
You might want to broadcast a message to your gtalk buddy list for a number of reasons. Extension jaxl4broadcast.class.php will do exactly the same for us. To run this extension you should checkout the latest xmpp.class.php file from the repository. Jaxl v 1.0.4 doesn’t support Gmail Extension. Leave your configuration file as it is form the previous example. Simply include jaxl4broadcast.class.php in your index.php file, instead of jaxl.class.php. Or you might also want to create separate index file for each application you build using Jaxl.

Now simply type in

sudo php index.php

on terminal window. You will see the following action logs on the terminal window:
jaxl-jabber-xmpp-library-demo-4
The script broadcast the default message to everyone on the gtalk friend list. In the screen shot you can also see me receiving default message sent by our bot. If any of the friend(s) are offline, the bot sends an offline message to them.

3. RSS feed aggregator bot
Here we will try to make a bot which keep processing RSS feeds in the background. We will also make provisions in this application to retrieve aggregated RSS feed results just by sending simple text messages to the bot. One such application build using Jaxl library is RSS feed integrator for Dzone. You can find this application in the jaxl folder if you have checked out the code from repository. Otherwise download the application from here.

Leave your configuration file as it is from previous applications and instead of jaxl.class.php, include jaxl4dzone.class.php inside index.php. As before simply run the following command on the terminal window:

nohup php index.php > log/logger.log &

.

Read How to get dzone feeds as IM using JAXL? Add [email protected] for pre-requisites required before running this application and a complete list of provisions made for retrieving rss feeds from this running bot. Here are is a response from the bot, when I send a message reading “php” to the bot:
jaxl-jabber-xmpp-library-demo-5
The application in the background, checks for the incoming message. Further it checks for a cached RSS feed in the cache folder. If the cache is stale or expired, it refetches the RSS feed from Dzone and throw back the results as seen in the screenshot above. If the bot finds a fresh cache of RSS feed in cache directory, it simply throw back the same RSS feed.

4. Custom out-of-office email bot for gmail
jaxl4gmail.class.php is an extension which shows the power of Gmail Extension integration into Jaxl library. This extension allows you to send custom out-of-office email’s to your contacts. I might want to send out a custom out-of-office mail to my colleagues in office and a custom mail to my friends and family.

Download the extension from here, if not already present in the jaxl directory. Include jaxl4gmail.class.php in index.php. Finally run the bot using:

nohup php index.php > log/logger.log &

For details information on how to customize this extension refer this blog post: Programatically control your google mails using JAXL v 1.0.4

5. Building an online multi-user gaming bot
By now we know how to run our bot 24×7 using Jaxl library. In this section we will develop a basic online multi-user gaming bot. Before we go ahead and code our bot, lets decide a few rules for our game:

Users worldwide can add our bot as buddy in gtalk (or using any other IM client). Below are the rules and actions a user can perform:

  • Send a message “start” to enter the multi-user gaming arena.
  • Send a message “stop” to exit the gaming arena.
  • Send a message “options” to view available options for the gaming arena.
  • Any other message sent by the user, will be considered as his answer to the previously broadcasted question. We will make sure “start”, “stop” and “options” are not an answer to any of the question being broadcasted.
  • Whom-so-ever sends a right answer to the broadcasted question receives 5 points. Bot immediately notify everyone in the arena about right answer being received. Thereafter, bot will broadcast the next question to all the users in the arena.
  • Bot reads a list of questions from a file or database as soon as the bot is started. Thereafter, it will keep reading questions from the list of questions randomly and keep broadcasting them to users in the arena.
  • Bot keeps a track of jabber id for incoming (identified by “start”) and outgoing (identified by “stop”) users.
  • Bot also maintains the index of current question being broadcasted

We will code our application in a file called jaxl4gaming.class.php. Here is how the final code will look like. See comments inside the code for more explanation:

jaxl4gaming.class.php (download)

  /* Include XMPP Class */
  include_once("xmpp.class.php");

  class JAXL extends XMPP {

    // List of question contained in an array
    var $questions = array();

    // List of answers corresponding to above questions
    var $answers = array();

    // list of answers which are not allowed for any question
    var $answers_not_allowed = array('start','stop','options');

    // last sent question key (basically index value of question in questions array)
    var $last_question_key = -1;

    // an associative array storing user scores
    var $user_scores = array();

    // stores jabber id of users currently in the arena
    var $user_jids = array();

    // game status
    var $game_status = FALSE;

    /* START OF STANDARD JAXL METHODS */
    function eventMessage($fromJid, $content, $offline = FALSE) {
      // Take action only if the message received is online
      if(!$offline) {
         // trim incoming content
         $content = trim($content);

         // get bare jid for the user
	 $fromJid = $this->getBareJid($fromJid);
	 switch($content) {
	   case 'start':
	     $this->add_user_to_arena($fromJid);
	     break;
	   case 'stop':
	     $this->remove_user_from_arena($fromJid);
	     break;
	   case 'options':
	     $this->display_options($fromJid);
	     break;
	   default:
	     $this->handle_user_message($fromJid, $content);
	     break;
	 }
      }
    }

    // not required for this gaming demo
    function eventPresence($fromJid, $status, $photo) {

    }

    // set the status for our gaming bot
    function setStatus() {
      // Set a custom status or use $this->status
      $this->sendStatus("Type *options* for getting started");
      print "Setting Status...n";
      print "Donen";

      // initialize game
      if(!$this->game_status) {
        $this->logger->logger('Initializing gaming arena....');
        $this->init();
        $this->game_status = TRUE;
      }
    }
    /* END OF STANDARD JAXL METHOD */

    /* START OF GAME CODE METHODS */
    function init() {
      // called when the bot starts
      // read the list of questions and their answers from a txt file
      // populate the $question and $answers array
      // HARDCODING arrays for DEMO purpose.
      $this->questions = array('q1','q2','q3','q4','q5');
      $this->answers = array('a1','a2','a3','a4','a5');
      return TRUE;
    }

    function broadcast_message($message, $except=array()) {
      foreach($this->user_jids as $jid => $info) {
	if(in_array($jid, $except)) continue;
   	else if($this->user_jids[$jid]['status'] == 'online') {
          $this->sendMessage($jid, $message);
        }
      }
      return TRUE;
    }

    function add_user_to_arena($jid) {
       // check if user visited the game before
       // you may want to send some custom welcome messages depending upon the user type
       if(!isset($this->user_jids[$jid])) {
         $this->logger->logger('Adding user_jids key for: '.$jid);
	 $this->user_jids[$jid] = array();
       }

       $this->user_jids[$jid]['status'] = 'online';
       $this->user_jids[$jid]['start_time'] = time();
       $this->logger->logger($jid.' joined the arena: '.json_encode($this->user_jids[$jid]));

       $this->send_current_question($jid);
       return TRUE;
    }

    function send_current_question($jid) {
      // is this the 1st user in the arena
      if($this->last_question_key == -1) $this->last_question_key++;
      $current_question = $this->questions[$this->last_question_key];

      $this->logger->logger('Sending current question at index: '.$this->last_question_key.', question: '.$current_question.' to: '.$jid);
      $this->sendMessage($jid, $current_question);
      return TRUE;
    }

    function broadcast_next_question($except=array()) {
      if($this->last_question_key == count($this->questions)-1) $this->last_question_key = 0;
      else $this->last_question_key++;

      $this->broadcast_message($this->questions[$this->last_question_key], $except);
      return TRUE;
    }

    function broadcast_right_answer($fromJid, $answer, $except) {
      $message = '*'.$fromJid.'* gave the right answer: '.$answer;
      $this->broadcast_message($message, array($fromJid));
      return TRUE;
    }

    function remove_user_from_arena($jid) {
       if(isset($this->user_jids[$jid])) {
	 $this->user_jids[$jid]['status'] = 'offline';
         $this->user_jids[$jid]['end_time'] = $this->user_jids[$jid]['start_time'];
       }
       return TRUE;
    }

    function display_options($jid) {
      $options = '*start* To join the arena, *stop* To quit the arena, *options* To display this help';
      $this->sendMessage($jid, $options);
      return TRUE;
    }

    function handle_user_message($jid, $message) {
      // check if user already exists in the arena
      if(!isset($this->user_jids[$jid]) || $this->user_jids[$jid]['status'] == 'offline') {
        $this->display_options($jid);
        return TRUE;
      }

      // we treat this message as an answer
      $current_answer = $this->answers[$this->last_question_key];
      if($message == $current_answer) {
        $this->increase_user_points($jid);
        $this->broadcast_right_answer($jid, $message, array($jid));
        $this->broadcast_next_question(array());
      }
      else {
        $message = $message.' is a wrong answer. Try again!';
        $this->sendMessage($jid, $message);
      }
      return TRUE;
    }

    function increase_user_points($jid) {
      if(!isset($this->user_jids[$jid]['points'])) $this->user_jids[$jid]['points']=0;
      $this->user_jids[$jid]['points'] += 1;
    }

  }

This is the basic game architecture which will generally be followed while you build games using Jaxl library.
In brief here is the explanation to above code:

  • Initializing game: setStatus() is the last method called during the whole initialization process of bot. Hence this is a right choice to call our game initialization method init(). You can do a number of things in this method. For this demo, I simply hard code the questions and their answers in respective arrays. Once the game is initialized, these $questions and $answers will reside in program memory for the life time.
  • Basic game flow: The flow is simple. I have customized the eventMessage() method provided by Jaxl class. I simply check for a number of cases and divert the flow of the game. If the incoming message is one of the available options, I simply do the respective action. (start triggers add_user_to_arena(), stop triggers remove_user_from_arena() and options trigger display_options() method). If incoming message doesn’t match any available options, I consider it as an attempt to answer the current question and redirect to handle_user_message(). However, if user is yet not a part of the gaming arena and he tries to answer a question, handle_user_message() function will simply redirect to display_options() method.
  • User stats: I also maintain basic user stats in a variable called $user_jids. For each user, I maintain the following fields: 'status' field value can be ‘online’ or ‘offline’ depending upon user availability in the arena. I also maintain a 'start_time' field which indicates when did the user last joined the arena. You might want to have this for a number of reasons. Every time user quits the arena, I also save a field called 'end_time' indicating when did the user last left the arena. Finally, I maintain user points in a field called 'points'. This field is incremented by 1 for every correct answer by the user.
  • Infinite questions: Every time a new question is broadcasted, I check the status of current question key. If it has reached the end of questions array, i simply reset it to 0. Hence the bot will keep serving the questions always. This logic is inside broadcast_next_question() method.
  • Broadcasting messages: broadcast_message() is the main method which broadcast all message from the bot to users playing in the arena. It takes two values as parameters: $message i.e. the message you want to broadcast and $except array which contains user jid’s which you want to skip while broadcasting.

Now how do we test our game. Simply follow the following steps:

  • Download jaxl4gaming.class.php and include it inside index.php
  • Update the config.ini.php file with your production username and password. We will run this bot using gtalk user credentials.
  • Run the bot using
    sudo php index.php
  • Add bot into your gtalk and try to send a message options to it. If everything is fine, you should be able to see the bot performing as we described in the game rules above.
  • Finally customize the methods inside jaxl4gaming.class.php and build your own games.

Debugging your Jaxl bot
In case you run into some error while trying to run Jaxl here are a few things you SHOULD do:

  • Checkout the open/closed issues here. I get lot of queries specially from college enthusiasts and in 99% of the cases solution can be found on the issue’s link above.
  • Another thing you should do is, enable error logging in your php.ini and check the error logs.
  • If you are still unable to find a solution, file a new issue with relevant information here.
  • Search the jaxl forum and discuss with other users who must have encountered similar errors before. Jjoin other users on jaxl’s google group here.
  • Finally, if nothing helps. Send a mail or IM me.

All the best with Jaxl. 😀

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:

  • [email protected] (Source Code)
  • Sending custom out-of-office mails in Gmail (Source Code)

Happy Broadcasting!

Programatically control your google mails using JAXL v 1.0.4

Google has released an API for almost all of their products including maps, feedburner and gadgets. However one of the API’s which every developer would have loved to make use of is “Google Mail API” which is still missing (available for premium google apps user only). Here in this post I would demonstrate how one can programatically control his/her google mails using JAXL without being a premium user of google mail account.

For those who have landed on this post straight and have little knowledge about what JAXL is “JAXL stands for Jabber XMPP Library and for fun you may call it Just Another XMPP Library. It is written in PHP and can be downloaded from http://code.google.com/p/jaxl“. To know more about JAXL, read the introductory post here. If you want to dig deep and know how JAXL works, read the gtalk case study here. Finally, after reading this post you may also want to check how you can fetch any social networking feed right into your gtalk messenger using JAXL.

Version 1.0.4 of JAXL included support for “Gmail Notification Extension of XMPP“. If you are a daily Gtalk user like me, then you have surely seen this extension in action. Just recall Gtalk notifying you of a new mail in your inbox, through a pop-up in the bottom right corner. Also those who see this in action everyday will agree with me that this notification comes even before the mail has actually appeared in you inbox. Simply because of the PUSH technology used by XMPP protocol.

So why would you in first place be interested in accessing your google mails programatically. A quick thought on this brings me to the following real life scenarios:

  • Suppose your are out of vacation and you want to set a custom auto-reply message for your family and friends, while you want to set a general out-of-office message for your colleagues. The limitation in gmail is that you can’t really do this. Further in this post, I will show you how can you achieve this using JAXL.
  • Suppose you are a google app user and your company has organized an online programming contest. Further you want to mail each question to the contestants only if they has answered the previous question. JAXL provide you a way to access key information about your incoming mails like: sender email id, subject, number of threads in the mail, time at which mail was sent, mail url and mail snippet. Which is enough for you to code a bot which can check for incoming mail and then send in next question to the contestant who sent this mail
    1. Further there can be a thousand use cases where you would you like to have such a control over you google mails but before discussing them, lets see a demonstration on how can we use JAXL to achieve this.

      Sending Custom Auto-Reply Mails using JAXL
      Along with extendable functions like eventMessage() and eventPresence(), JAXL’s latest version now also provide another extendable function called eventNewEMail(). So everytime you receive a new mail(s) in your google account, the control is passed to this function along with all informations about the incoming mails.

      Various data passed to this function are:

      • $total: Tells you about total number of unread mails.
      • $thread: The thread id of all the unread threads. Note: In Gmail you have threads in your inbox which can contain more than a single mail.
      • $url: The mail.google.com url for the new mail
      • $participation: This can be 0, 1 or 2. 0 indicates that you have not participated, 1 indicates that you are one of the many recipients and 2 indicates that you are the sole recipient for messages in this thread
      • $message: The number of messages in the thread. For instance you can have more than one unread mail in a thread.
      • $date: A timestamp of the most recent unread message, in milliseconds since the UNIX epoch
      • $senders: Email Id of all the senders in the current thread
      • $labels: Label if any to which this mail thread belongs to
      • $subject: The subject of the mail threads
      • $snippet: The mail snippet of the incoming mail

      So thats a lot of information really, with which we can automate things to a certain extent. Lets see how I use it to send custom auto-reply mails when I am out on vacation. Here is the extendable jaxl class for gmail:

      jaxl4gmail.class.php (Download)

        /* Include PHP Mailer Class */
        include_once("class.phpmailer.php");
      
        /* Include XMPP Class */
        include_once("xmpp.class.php");
      
        class JAXL extends XMPP {
      
          /* Define custom mail groups */
          var $family = array("[email protected]","[email protected]");
          var $colleague = array("[email protected]","[email protected]");
      
          /* Define custom mail subject and message */
          var $familySubject = "Hi, Will get back to you";
          var $familyMessage = "Hey, I am currently out on vacation at my grannies house in Delhi. I will return back home by next monday.
      Reach out to me at +91-987654321.

      With Love,
      Abhinav Singh"; /* Define custom mail subject and message */ var $colleagueSubject = "[Auto-Reply] Out of Office"; var $colleagueMessage = "Hi, I am on vacation in my village with very limited access to internet and phone. I will return back home by next monday.

      Regards,
      Abhinav Singh"; function eventMessage($fromJid, $content, $offline = FALSE) { } function eventPresence($fromJid, $status, $photo) { } function eventNewEMail($total,$thread,$url,$participation,$messages,$date,$senders,$labels,$subject,$snippet) { // We only want to send auto-reply message to latest sender $sender = $senders[0]; // Check if the user lie in any category, and send appropriate mail if(in_array($sender["address"],$this->family)) { $mail = new PHPMailer(); $mail->From = "[email protected]"; $mail->FromName = "Your Name"; $mail->Subject = $this->familySubject; $mail->MsgHTML($this->familyMessage."

      Powered by Jaxl http://code.google.com/p/jaxl"); $mail->IsHTML(true); $mail->AddAddress($sender["address"],$sender["name"]); if(!$mail->Send()) $this->logger->logger("Error occured while sending mail to ".$sender["address"]); else $this->logger->logger("Mail sent successfully to ".$sender["address"]); } else if(in_array($sender["address"],$this->colleague)) { $mail = new PHPMailer(); $mail->From = "[email protected]"; $mail->FromName = "Your Name"; $mail->Subject = $this->colleagueSubject; $mail->MsgHTML($this->colleagueMessage."

      Powered by Jaxl http://code.google.com/p/jaxl"); $mail->IsHTML(true); $mail->AddAddress($sender["address"],$sender["name"]); if(!$mail->Send()) $this->logger->logger("Error occured while sending mail to ".$sender["address"]); else $this->logger->logger("Mail sent successfully to ".$sender["address"]); } else { // Do nothing, will handle later on $this->logger->logger("No handler for this email id..."); } } function setStatus() { print "Setting Status...n"; $this->sendStatus("Available"); print "Requesting new mails...n"; $this->getNewEMail(); print "Donen"; } }

      The only variables you would like to change in above class are:

      1. $family : An array of email id of your family member
      2. $colleague : An array of email id of your colleagues
      3. $familySubject : Subject with which you want to send mails to your family members
      4. $familyMessage : Mail message which you want to send to you family
      5. $colleagueSubject : Subject with which you want to send mails to your colleagues
      6. $colleagueMessage : Mail message which you want to send to you colleagues

      For further customization, you may want to add more groups and their respective subjects and messages.

      Further you may want to create your own custom bots using JAXL for one of the other use case described above. Join official JAXL Google Group for future updates and enhancements.

      Do let me know if you build any custom bot using JAXL, I will be more than happy to list your bot on official JAXL google code page.

      Enjoy!

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 🙂

[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.