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 games@gtalkbots.com)

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:

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. jabberxmpplibrary@gmail.com, 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 (games@gtalkbots.com). 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.

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:
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 dzone@gtalkbots.com 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:
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 */

  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;

    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':
	   case 'stop':
	   case 'options':
	     $this->handle_user_message($fromJid, $content);

    // 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->game_status = TRUE;

    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]));

       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') {
        return TRUE;

      // we treat this message as an answer
      $current_answer = $this->answers[$this->last_question_key];
      if($message == $current_answer) {
        $this->broadcast_right_answer($jid, $message, array($jid));
      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. 😀