A Simple Script

Before moving on, let’s have a look at how simple it is to interact with Jabber. Example 1-1 shows a simple Perl script that connects to a Jabber server, authenticates, checks who’s online, and sends those people a reminder message. It uses the Net::Jabber library, which provides a high-level API to many Jabber-related functions such as handling the connection to the server (this is via another library that Net::Jabber uses—XML::Stream), authentication, events, and all the mechanisms to parse and create Jabber traffic.

Example 1-1. A simple Jabber script
#!/usr/bin/perl

use Net::Jabber qw(Client);
use strict;

# List of addressees for our reminder
our @addressees;

# What we want to send
my  $reminder = $ARGV[0] or die "No reminder!";

# Connect to our Jabber server
my $c= Net::Jabber::Client->new();
$c->Connect('hostname' => 'yak',
            'port'     => 5222);

# Authenticate
$c->AuthSend('username' => 'reminder',
             'password' => 'secret',
             'resource' => 'reminder');

# Set handler to deal with presence packets
# that might (will) be pushed to us (we're
# not interested in any other type of packet)
$c->SetCallBacks('presence' => \&handle_presence);

# Send out our own presence, and run an
# event loop for up to 5 seconds to
# catch any packets pushed to us
$c->PresenceSend();
$c->Process(5);

# Create a new message with our reminder text
my $m = Net::Jabber::Message->new();
$m->SetBody($reminder);

# Send the message to each of the addressees collected
# in the handle_presence() subroutine
foreach my $jid (@addressees) {

  $m->SetTo($jid);
  $c->Send($m);

}

# Disconnect from the Jabber server and exit
$c->Disconnect;
exit(0);


# Deal with presence packets
sub handle_presence {

  my ($sid, $presence) = @_;

  # Get the presence
  my $show = $presence->GetShow() || 'online';

  # If the user is around, add to addressee list
  push @addressees, $presence->GetFrom()
    if $show eq 'online' or $show eq 'chat';

}

The script is fairly self-explanatory. For now, we’ll leave the script’s description to the comments embedded within it; by the end of the book, you should have a good understanding of how to put together complete applications and utilities using Jabber libraries in Perl, Python, and Java.

Get Programming Jabber now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.