JabChapter 9

From WikiContent

Revision as of 01:53, 1 August 2009 by RacgeTcaze (Talk | contribs)
Jump to: navigation, search

silent movie theater on fairfax american express money wire las vegas poker tournaments february printed sweatshirts gazebo designs wwe diva stacy keibler. razzle map iowa city entertainment walley fishing manitoba site indecent proposal video clip free gd55 mobile panasonic ringtone moms movies.com a perfect circle music video downloads amateur submitted movies auto nationwide watch.com marisa miller video free mobile panasonic ringtone movie schedule tinseltown sponges phylum popup blockers russian mature movies secretely music roger video zapp nude madonna dan post boots sitemap annie lennox ringtone framed photos movie clip heather graham link mass transit magazines coach replica amr ringtones free download english to german masterbate clit electric burr grinder pharmacy ethnic video sexual intercourse photos deer hunting igrice video microsoft open license site nostalgiques stickers russian movie download movie icon avatars anna ohura videos phentermine pharmacy biz wet nurses white water rafting wales uk playstation3 merman movies ritalin adderall concerta sitemap decadron preview torrent file mpeg4 movie converter asia movie trailer craigs list denver irish drink mix 2005 draft nhl media player movie trailors leonard maltin movie reviews apache mysql php windows installer hohner nik sharpener pro serial index link penneys radiator hose wu-tang clan woman naked lowden guitar serial numbers recurso humanos matthew perry drug addiction kill myself eminem puke video easy producer video aspiration book guest lex on blondes domain oxycontin lil wyte lyrics what is extacy drug pretty ricky video total wine naked photo post adam brody jimmy kimmel best way to lose weight magnum movie p.i infant blood pressure normal plastic license plate blanks allfreegay trackpad powerbook adobe photoshop 8 cs cracked interpreter memphis homes el nino red envolope irene hunt pictures pussy eating gallery free web design template pwl cracker download activation end process product software cell motorola phone razr ringtone showplace 16 coon rapids mn url in nevada pharmacy school sexy seamed stockings sample sex video and movie speculumpages archive video files free ringtones alltel audiovox nastyrat.com marmalade mr review lolita index alive blaine clip david drowned video pioneer press page aurora fox mall valley 2 best camera digital megapixel links eating a balanced diet adultactioncam.com cardizem cd anabolic steroids actos altace robert palmer simply irresistible music video girls messy cheerleader pacific assault no cd crack shemale domination lunchboxes live night rap saturday video karate kata video free ohiolottery rakuen movie 4 inuyasha smoothmag wholesale home tanning bed honda radiator skydiving video clip movie lobby card index environmental sampling supplies valassis ivp care pharmacy pure country movie quotes student housing chicago cubs index pictures of rainbows top suffolk realty agents

Contents

Groupchat, : Components, and Event Models


By now, you should have a

good idea of how scripts interact with Jabber and how the core
elements such as <message/> and
<presence/> can be constructed and handled.

This chapter builds upon what we've already seen in Chapter 8 and introduces new concepts. We build a nosy assistant that joins a conference room and alerts us to words and phrases that we want it to listen for. There are two popular conference protocols, as mentioned in Section 6.2.6—the presence-based Groupchat protocol, and the jabber:iq:conference-based Conference protocol. The assistant recipe, a foray into the world of 'bots, takes a look at the original presence-based one.

As we've seen, programming within Jabber's event model is fairly straightforward. But what happens when you want to meld other components with event models of their own? We look at a couple of typical scenarios where this melding needs to happen. The first is a homage to the Trojan Room Coffee Machine (http://www.cl.cam.ac.uk/coffee/coffee.html), where we give life, or at least presence, to a coffeepot, using LEGO® MINDSTORMS™. The second is a Tk-based RSS headline viewer. Both the coffeepot and the Tk programming library have event loops of their own. With the coffeepot, we need to have a loop that polls the coffeepot's status, independently of the polling for incoming packets from the Jabber server. The Tk programming library's event model is similar to those of the Jabber programming libraries that are used in the recipes in this book, in that handlers are set up and a loop is started that listens for UI events. In both cases, we need to get these event loops to work in harmony with the Jabber libraries' event loops.

Building Jabber solutions without event loops is a Sisyphean task. The very nature of Jabber communication is event-based, and it's important to understand how to use the event features of the Jabber programming libraries and also how to be able to mesh those features with similar features in other libraries and systems.

We also look at extending messages and build a mechanism that delivers RSS headlines to clients who register with that mechanism. These headlines are carried using an extended message type. In fact, the RSS Delivery Mechanism is a component. The three recipes in Chapter 8, were Jabber clients, in that they connected to the Jabber network via the Jabber Session Manager (JSM) service. We look at the differences between programming a client and programming a component in this chapter and build a complete component that can be queried and interacted with using the third of Jabber's building blocks—the <iq/> element.

Happy coding!


Keyword Assistant


Many of the Jabber core and peripheral developers hang out in a conference room called jdev hosted by the Conferencing component on the Jabber server running at jabber.org. While a lot of useful information is to be gleaned from listening to what goes on in jdev, it isn't possible to be there all the time. Conversations in jdev are logged to web pages, which can be used to visit after the fact to try to catch up with things; however, this can be a hopeless task. One solution is to build a 'bot that looks for specific keywords and Uniform Resource Locators (URLs) in the conversations in jdev and send those on as Jabber messages.

This script, keyassist, connects to a Jabber server, enters a conference room, and listens to the conversations, looking for certain words and phrases to be uttered. The keyassist script is given a bit of "intelligence" in that it can be interacted with and told, while running, to watch for (or stop watching for), certain words and phrases.

The keyassist script introduces us to programmatic interaction with the Conferencing component. Before looking at the script, however, let's have a brief overview of Conferencing in general.



Conferencing


The Conferencing component at jabber.org is conference.jabber.org. Details of the component instance configuration for such a Conferencing component can be found in Section 4.10, where we see that the component exists as a shared object library connected with the library load component connection method. This component provides general conferencing facilities, oriented around a conference room and conference user model.

A Jabber user can enter (or join) a conference room, thereby becoming a conference user identified by a nickname that is chosen upon entering that room. Nicknames are generally used in conference rooms to provide a modicum of privacy—it is assumed that by default you don't want to let the other conference room members know your real JID.

The Conferencing component supports two protocols for user and room interaction: a simple one that provides basic features and a more complex one that provides the basic features plus facilities such as password-protected rooms and room descriptions—Groupchat and Conference.


{{Note|There is a third protocol, called Experimentaliq:groupchat, which came between the Groupchat and Conference protocols. This reflected an experimental move to add features to the basic Groupchat protocol using IQ elements, the contents of which were qualified by a namespace jabber:iq:groupchat. This protocol has been dropped, and support for it exists only in certain versions of WinJab and JIM.

</code>

Groupchat
The Groupchat protocol is the simpler of the two and provides basic
functions for entering and exiting conference rooms and choosing
nicknames. : This Groupchat protocol is known as the presence-based
protocol, because the protocol is based upon
<presence/> elements used for room entry, exit, and
nickname determination. The Groupchat protocol has a nominal version
number of 1.0.
Conference
The Conference protocol offers more advanced features than the
Groupchat protocol and makes use of two IQ namespaces:
jabber:iq:conference and jabber:iq:browse. It has a
nominal protocol version number of 1.4, which reflects the version of
the Jabber server with which it is delivered. Sometimes this version
number is referred to as 0.4, such as in the downloadable tarball and
in the value returned in response to a "version query" on the
component itself, as shown in Example 9-1. : The version number isn't
that important. The main thing to keep in mind is that the component
that is called conference.so (see the reference to the
shared object library in Section 4.10.4) supports both the
Groupchat protocol and the Conference protocol. If you come across a
shared object library called groupchat.so, this is the
original Conferencing component that was made available with Jabber
server Version 1.0. This library supports only the Groupchat protocol.

Querying the Conferencing component's version

SEND: <iq type='get' to='conference.gnu.mine.nu'> <query xmlns='jabber:iq:version'/> </iq>

RECV: <iq to='dj@gnu.mine.nu/jarl' from='conference.gnu.mine.nu' type='result'> <query xmlns='jabber:iq:version'> <name>conference</name> <version>0.4</version> <os>Linux 2.4.2-2</os> </query> </iq> In this recipe we'll be using the simpler Groupchat protocol. It's widely used and easy to understand. Example 9-2 shows a typical element log from Groupchat-based activity. It shows a user, with the JID qmacro@jabber.com, entering a room called "cellar," hosted on the conference component at conf.merlix.dyndns.org, a room that currently has two other occupants who go by the nicknames flash and roscoe. The elements are from qmacro's perspective, and are all explained following the example.


The Groupchat protocol in action The user qmacro tries to enter the conference room with the nickname flash and fails:


SEND: <presence to='cellar@conf.merlix.dyndns.org/flash'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='error'> <error code='409'>Conflict</error> </presence>

He tries again, this time with a different nickname, deejay, and is successful:


SEND: <presence to='cellar@conf.merlix.dyndns.org/deejay'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/deejay'/>

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>deejay has become available</body> </message>

roscoe says hi, and qmacro waves back:


RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe' type='groupchat' cnu=> <body>hi</body> </message>

SEND: <message to='cellar@conf.merlix.dyndns.org' type='groupchat'> <body>/me waves to everyone</body> </message>

flash sends a private message to qmacro:


RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='chat'> <body>Is that you, qmacro?</body> <thread>jarl1998911094</thread> </message>

Feeling left out of the conversation, roscoe leaves the room:


RECV: <presence to='qmacro@jabber.com/jarltk' type='unavailable' from='cellar@conf.merlix.dyndns.org/roscoe'/>

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>roscoe has left</body> </message> Let's take the stages in Example 9-2 one by one.


Failed attempt to enter room
qmacro makes an attempt to enter the room using the Groupchat
protocol. This is done by sending a directed
<presence/> element to a particular JID that represents
the room and the chosen nickname. This JID is constructed as follows:

[room name]@[conference component]/[nickname]

In this example, the conferencing component is identified with the
hostname conf.merlix.dyndns.org. qmacro's choice of
nickname is flash:

cellar@conf.merlix.dyndns.org/flash

Thus the following element is sent:

SEND: <presence to='cellar@conf.merlix.dyndns.org/flash'/>

The conference component determines that there is already someone
present in the room cellar@conf.merlix.dyndns.org with the
nickname flash, so qmacro is notified of this and
receives a directed presence with an <error/> tag:

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='error'> <error code='409'>Conflict</error> </presence>

Note that the <presence/> element has the type
error and comes from the artificial JID constructed in the
room entry attempt. The element is addressed to qmacro's real
JID, of course—qmacro@jabber.com/jarltk—as otherwise it
wouldn't reach him. : The error code 409 and text "Conflict" tells
qmacro that the nickname conflicted with one already in the
room. This is a standard error code/text pair; Table 5-3 shows a
complete set of code/text pairs. : At this stage, qmacro is
not yet in the room.
Successful attempt to enter room
qmacro tries again, this time with a different nickname,
deejay:[1]

SEND: <presence to='cellar@conf.merlix.dyndns.org/deejay'/>

This time, there is no conflict—no other user is in the room "cellar"
with that nickname—and the conference component registers the entry.
It does this by sending qmacro the presence of all the room
occupants, including that of himself:

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/deejay'/>

These presence elements are also sent to the other room occupants so
they know that deejay is present.
Conference component-generated notification
In addition to the presence elements sent for each room occupant, a
general roomwide message noting that someone with the nickname
deejay just entered the room is sent out by the component as
a type='groupchat' message to all the room occupants:

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>deejay has become available</body> </message>

The text "has become available" used in the body of the message is
taken directly from the Action Notices definitions, part of the
Conferencing component instance configuration described in Section
4.10.3. Note that the identity of the room itself is simply a generic
version of the JID that the room occupants use to enter:

cellar@conf.merlix.dyndns.org

Roomwide chat
Once the user with the nickname roscoe sees someone enter the
room, he sends a greeting, and qmacro waves back:

RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe' type='groupchat' cnu=> <body>hi qmacro</body> </message>

SEND: <message to='cellar@conf.merlix.dyndns.org' type='groupchat'> <body>/me waves to everyone</body> </message>

As with the notification message, each message is a
groupchat-type message. The one received appears to come from
cellar@conf.merlix.dyndns.org/roscoe, which is the JID
representing the user in the room with the nickname roscoe.
This way, roscoe's real JID is never sent to qmacro.
The message deejay sends is addressed to the room's identity
cellar@conf.merlix.dyndns.org, and contains a message that
starts with /me. This is simply a convention that is
understood by clients that support conferencing, meant to represent an
action and displayed thus:

* deejay waves to everyone

{{Note|Ignore the cnu attribute; it's put there and used by the component and should never make it out to the client endpoints. The attribute name is a short name for the conference user and refers to the internal structure that represents a conference room occupant within the component.

</code>

One-on-one chat
The Conferencing component also supports a one-on-one chat mode, which
is just like normal chat mode (where messages with the type
chat are exchanged) except that the routing goes through the
component. The intended recipient of a conference-routed chat message
is identified by his room JID. So in this example:

RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='chat'> <body>Is that you, qmacro?</body> <thread>jarl1998911094</thread> </message>

the user nicknamed flash actually addressed the chat message
to the JID:

cellar@conf.merlix.dyndns.org/deejay

which arrived at the Conferencing component (because of the hostname,
conf.merlix.dyndns.org causes the <message/>
element to be routed there), which then looked up internally who
deejay really was (qmacro@jabber.com/jarltk) and
sent it on. This way, the recipient of a conference-routed message
never discovers the real JID of the sender. In all other ways, the
actual <message/> element is like any other
<message/> element—in this case, it contains a message
<body/> and a chat <thread/>. (See
Section 5.4.1 for details on the <message/> element.)
Leaving the room
In the same way that room entrance is effected by sending an
available presence (remember, a <presence/>
element without an explicit type attribute is understood to
represent type="available'), leaving a room is achieved by
doing the opposite:

RECV: <presence to='qmacro@jabber.com/jarltk' type='unavailable' from='cellar@conf.merlix.dyndns.org/roscoe'/>

The people in the conference room are sent a message that
roscoe has left the room by the unavailable presence
packet. This is by and large for the benefit of each user's client, so
that the room occupant list can be updated. The component also sends
out a verbal notification, in the same way as it sends a verbal
notification out when someone joins:

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>roscoe has left</body> </message>

Like the join notification, the text for the leave notification ("has
left") comes directly from the component instance configuration
described in Section 4.10.3.


The Script's Scope


The Keyword Assistant (keyassist) script will be written in Python using the Jabberpy library. As mentioned earlier, the script will perform the following tasks:

  • Connect to a predetermined Jabber server
  • Join a predetermined conference room
  • Sit there quietly, listening to the conversation
  • Take simple commands from people to watch for, or stop watching for, particular words or phrases uttered in the room
  • Relay the context of those words or phrases to whomever requested them, if heard In addition

to setting the identity of the Jabber server and the conference room in variables, we'll also need to keep track of which users ask the assistant for words and phrases.
We'll use a dictionary (hash in Perl terms), as shown in Example 9-3, because we want to manage the data in there by key, the JID of those users that the script will be assisting. Having a look at what this dictionary will look like during the lifetime of this script will help us to visualize what we're trying to achieve.


Typical contents of the Keyword Assistant's dictionary

{ 'dj@gnu.pipetree.com/home': { 'http:': 1, 'ftp:': 1

                                         },
 'piers@jabber.org/work':                { 'Perl': 1, 'Java': 1, 'SAP
 R/3': 1
                                         },
 'cellar@conf.merlix.dyndns.org/roscoe': { 'dialback': 1
                                         }

}

We can see from the contents of the dictionary in Example 9-3 that three people have asked the script to look out for words and phrases. Two of those people—dj and piers—have interacted with the script directly by sending a normal (or chat) <message/>. The other person, with the conference nickname roscoe, is in the "cellar" room and has sent the script a message routed through the Conference component in the same way that flash sent qmacro a private message in Example 9-2: the JID of the sender belongs to (has the hostname set to) the conference component. Technically, there's nothing to distinguish the three JIDs here; it's just that we know from the name that conf.merlix.dyndns.org is the name that identifies such a component.

If we dissect the dictionary, we can see that:

  • dj wants to be notified if any web or FTP URLs are mentioned.
  • piers is interested in references to two of his favorite

languages and his favorite business software solution.

  • roscoe

is interested in any talk about dialback. We said we'd give the script a little bit of intelligence. This was a reference to the ability for users to interact with the script while it runs, rather than having to give the script a static list of words and phrases in a configuration file. dj, piers, and roscoe have done this by sending the script messages (directly, not within the room) with simple keyword commands, such as:

dj: "watch http:" script: "ok, watching for http:" dj:
"watch gopher:" script: "ok, watching for gopher:" dj:
"watch ftp:" script: "ok, watching for ftp:" dj: "ignore
gopher:" script: "ok, now ignoring gopher:"

...

piers: "list" script: "watching for: Perl, Java, SAP R/3"

...

roscoe: "stop" script: "ok, I've stopped watching"


The keyassist Script


Example 9-4 shows the keyassist script in its entirety. The script is described in detail, step by step, in the next section.


The keyassist Perl script

import jabber from string import split, join, find import sys

keywords = {}

def addword(jid, word): if not keywords.has_key(jid): keywords[jid] = {} keywords[jid][word] = 1

def delword(jid, word): if keywords.has_key(jid): if keywords[jid].has_key(word): del keywords[jid][word]

def messageCB(con, msg):

   type = msg.getType() if type == None: type = 'normal'
   # Deal with interaction
   if type == 'chat' or type == 'normal': jid = str(msg.getFrom())
       message = split(msg.getBody(), None, 1); reply = ""
       if message[0] == 'watch': addword(jid, message[1]) reply =
       "Okay, watching for " + message[1]
       if message[0] == 'ignore': delword(jid, message[1]) reply =
       "Okay, now ignoring " + message[1]
       if message[0] == 'list': if keywords.has_key(jid): reply =
       "Watching for: " + join(keywords[jid].keys(), ", ") else: reply
       = "Not watching for any keywords"
       if message[0] == 'stop': if keywords.has_key(jid): del
       keywords[jid] reply = "Okay, I've stopped watching"
       if reply: con.send(msg.build_reply(reply))


   # Scan room talk
   if type == 'groupchat': message = msg.getBody()
       for jid in keywords.keys(): for word in keywords[jid].keys(): if
       find(message, word) >= 0: con.send(jabber.Message(jid, word +
       ": " + message))


def presenceCB(con, prs):

   # Deal with nickname conflict in room
   if str(prs.getFrom()) == roomjid and prs.getType() == 'error':
   prsnode = prs.asNode() error = prsnode.getTag('error') if error: if
   (error.getAttr('code') == '409'): print "Cannot join room -
   conflicting nickname" con.disconnect() sys.exit(0)
   # Remove keyword list for groupchat correspondent
   if prs.getType() == 'unavailable': jid = str(prs.getFrom()) if
   keywords.has_key(jid): del keywords[jid]

Server = 'gnu.mine.nu' Username = 'kassist' Password = 'pass' Resource = 'py'

Room = 'jdev' ConfServ = 'conference.jabber.org' Nick = 'kassist'

con = jabber.Client(host=Server) try: con.connect() except IOError, e: print "Couldn't connect: %s" % e sys.exit(0) else: print "Connected"

if con.auth(Username,Password,Resource): print "Logged in as %s to server %s" % ( Username, Server ) else: print "Problems authenticating: ", con.lastErr, con.lastErrCode sys.exit(1)

con.setMessageHandler(messageCB) con.setPresenceHandler(presenceCB)

con.send(jabber.Presence())

roomjid = Room + '@' + ConfServ + '/' + Nick print "Joining " + Room con.send(jabber.Presence(to=roomjid))

while(1): con.process(5)


Dissecting the keyassist Script


Taking keyassist step by step, the first section is probably familiar if you've seen the previous Python-based scripts in Section 8.1 and Section 8.3, both in Chapter 8.


import jabber from string import split, join, find import sys

Here, all of the functions and libraries that we'll need are brought in. We'll use the find function from the string library to help with the keyword searching.

Next, we declare the dictionary. This will hold a list of the words that the script will look for, as defined by each person, as shown in Example 9-3.


keywords = {}


Maintaining the keyword dictionary


To maintain this dictionary, we will use two subroutines to add words to and remove words from a user's word list. These subroutines are called when a command such as watch or ignore is recognized in the callback subroutine that handles incoming <message/> elements:


def addword(jid, word): if not keywords.has_key(jid): keywords[jid] = {} keywords[jid][word] = 1

def delword(jid, word): if keywords.has_key(jid): if keywords[jid].has_key(word): del keywords[jid][word]

A string representation of the JID (in jid) of the correspondent giving the command is passed to the subroutines along with the word or phrase specified (in word) by the user. The dictionary has two levels: the first level is keyed by the JID, and the second by word or phrase. We use a dictionary, rather than an array, at the second level simply to make removal of words and phrases easier.



Message callback


Next, we define the callback to handle incoming <message/> elements:


def messageCB(con, msg):

   type = msg.getType() if type == None: type = 'normal'

As usual, we're expecting the message callback to be passed the connection object (in con) and the message object itself (msg). How this callback is to proceed is determined by the type of message received. We determine the type (taken from the <message/> element's type attribute) and store it in the variable called type. Remember that if no type attribute is present, a message type of normal is assumed. (See Section 5.4.1.1 for details of <message/> attributes.)

The two types of incoming messages we're expecting this script to receive are those conveying the room's conversation—in groupchat-type messages—and those over which the commands such as watch and ignore are carried, which we expect in the form of normal- or chat-type messages.

The first main section of the messageCB handler deals with incoming commands:


# Deal with interaction if type == 'chat' or type == 'normal': jid = str(msg.getFrom())

       message = split(msg.getBody(), None, 1); reply = ""
       if message[0] == 'watch': addword(jid, message[1]) reply =
       "Okay, watching for " + message[1]
       if message[0] == 'ignore': delword(jid, message[1]) reply =
       "Okay, now ignoring " + message[1]
       if message[0] == 'list': if keywords.has_key(jid): reply =
       "Watching for: " + join(keywords[jid].keys(), ", ") else: reply
       = "Not watching for any keywords"
       if message[0] == 'stop': if keywords.has_key(jid): del
       keywords[jid] reply = "Okay, I've stopped watching"
       if reply: con.send(msg.build_reply(reply))


If the <message/> element turns out to be of the type in which we're expecting a potential command, we want to determine the JID of the correspondent who sent that message. Calling the getFrom() method will return us a JID object. What we need is the string representation of that, which can be determined by calling the str() function on that JID object:


jid = str(msg.getFrom())

Then we grab the content of the message by calling the getBody() on the msg object and split the whole thing on the first bit of whitespace. This should be enough for us to distinguish a command (watch, ignore, and so on) from the keywords. After the split, the first element (index 0) in the message array will be the command, and the second element (index 1) will be the word or phrase, if given. At this stage, we also declare an empty reply:


message = split(msg.getBody(), None, 1); reply = ""

Now it's time to determine if what the script was sent made sense as a command:


if message[0] == 'watch': addword(jid, message[1]) reply = "Okay, watching for " + message[1]

       if message[0] == 'ignore': delword(jid, message[1]) reply =
       "Okay, now ignoring " + message[1]
       if message[0] == 'list': if keywords.has_key(jid): reply =
       "Watching for: " + join(keywords[jid].keys(), ", ") else: reply
       = "Not watching for any keywords"
       if message[0] == 'stop': if keywords.has_key(jid): del
       keywords[jid] reply = "Okay, I've stopped watching"

We go through a series of checks, taking appropriate action for the supported commands:


watch
Watch for a particular word or phrase.
ignore
Stop watching for a particular word or phrase.
list
List the words and phrases currently being watched.
stop
Stop watching altogether; remove the list of words and phrases. The
addword() and delword() functions defined earlier
are used here, as well as other simpler functions; one that lists the
words and phrases for a particular JID:


keywords[jid].keys()

and one that removes them:


del keywords[jid]

If there was something recognizable for the script to do, we get it to reply appropriately:


if reply: con.send(msg.build_reply(reply))

The build_reply() function creates a reply out of a message object by setting to to the value of the original <message/> element's from attribute and preserving the element type attribute and <thread/> tag, if present. The <body/> of the reply object (which is just a <message/> element) is set to whatever is passed in the function call; in this case, it's the text in the reply variable.

Now that we've dealt with incoming commands, we need another section in the message callback subroutine to scan for the words and phrases. The target texts for this scanning will be the snippets of room conversation, which arrive at the callback in the form of groupchat-type <message/> elements:


# scan room talk if type == 'groupchat': message = msg.getBody()

The message variable holds the string we need to scan; it's just a case of checking for each of the words or phrases on behalf of each of the users who have asked:


for jid in keywords.keys(): for word in keywords[jid].keys(): if find(message, word) >= 0: con.send(jabber.Message(jid, word + ": " + message))

If we get a hit, we construct a new Message object, passing the JID of the person for whom the string has matched (in the jid variable) and the notification, consisting of the word or phrase that was found (in word) and the context in which it was found (the sentence uttered, in message). Once found and constructed, the <message/> is sent to that user. By default, the Message constructor specifies no type attribute, so the user is sent a "normal" message.


Presence callback


Having dealt with the incoming <message/> elements, we turn to the <presence/> elements. Most of those we receive in this conference room will be notifications from people entering and leaving the room, as shown in Example 9-2. We want to perform housekeeping on our keywords dictionary so the entries don't become stale. We also want to deal with the potential problem of conflicting nicknames. Let's look at that first.

We want to check for the possibility of nickname conflict problems that may occur when we enter the room, and the chosen nickname (flash) is already taken.

Remembering that a conflict notification will look something like this:


<presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='error'> <error code='409'>Conflict</error> </presence> we test for the receipt of a <presence/> element with the following:


def presenceCB(con, prs):

   # Deal with nickname conflict in room
   if str(prs.getFrom()) == roomjid and prs.getType() == 'error':
   prsnode = prs.asNode() error = prsnode.getTag('error') if error: if
   (error.getAttr('code') == '409'): print "Cannot join room -
   conflicting nickname" con.disconnect() sys.exit(0)

The <presence/> element will appear to be sent from the JID that we constructed for the initial room entry negotiation (in the roomjid variable further down in the script); for example:


jdev@conference.jabber.org/kassist We compare this value to the value of the incoming <presence/>'s from attribute, and also make sure that the type attribute is set to error. If it is, we want to extract the details from the <error/> tag that will be contained as a direct child of the <presence/>.

The Jabberpy library currently doesn't offer a direct high-level function to get at this tag from the Presence object (in prs), but we can strip away the presence object "mantle" and get at the underlying object, which is a neutral "node"—a Jabber element, or XML fragment, without any preconceived ideas of what it is (and therefore without any accompanying high-level methods such as getBody() or setPriority()).


{{Note|If this seems a little cryptic, just think of it like this: each of the Presence, Message, and IQ classes are merely superclasses of the base class Protocol, which represents elements generically.

</code> The asNode() method gives us what we need—a Protocol object representation of the <presence/> element. From this we can get to the <error/> tag and its contents. If we find that we do have a nickname conflict, we abort by disconnecting from the Jabber server and ending the script.

The general idea is that this script will run indefinitely and notify the users on a continuous basis, so we need to do a spot of keyword housekeeping. No presence subscription relationships are built (mostly to keep the script small and simple; you could adapt the mechanism from the recipe in Section 8.3 if you wanted to make this script sensitive to presence), so notifications will get queued up for the user if he is offline with the use of the mod_offline module of the Jabber Session Manager (JSM). This makes a lot of sense for the most part; however, we still want to have the script send notifications even if the user is offline. Additionally, a command could be sent to the script to watch for a keyword or phrase from a user within the room. We would receive the command from a JID like this:


jdev@conference.jabber.org/nickname This is a transient JID, in that it represents a user's presence in the jdev room for a particular session. If a word is spotted by the script hours or days later, there's a good chance that the user has left the room, making the JID invalid as a recipient. Although the JID is technically valid and will reach the conferencing component, there will be no real user JID that it is paired up with. Potentially worse, the room occupant's identity JID may be assigned to someone else at a later stage, if the original user left, and a new user entered choosing the same nickname the original user had chosen. See the upcoming sidebar titled "Transient and Nonexistent JIDs" for a short discussion of the difference between a transient JID and a nonexistent JID.

So as soon as we notice a user leave the room we're in, which will be indicated through a <presence/> element conveying that occupant's unavailability, we should remove any watched-for words and phrases from the dictionary:


# Remove keyword list for groupchat correspondent if prs.getType() == 'unavailable': jid = str(prs.getFrom()) if keywords.has_key(jid): del keywords[jid]

As before, we obtain the string representation of the JID using the str() function on the JID object that represents the presence element's sender, obtained via the getFrom() method.


{{Sidebar|Transient and Nonexistent JIDsWhat happens when you send a message to a "transient" conference room JID? Superficially, the same as when you send one to a nonexistent JID. But there are some subtle differences.

A transient JID is one that reflects a user's alternate identity in the context of the Conferencing component. When you construct and send a message to a conference transient JID, it goes first to the conference component because of the hostname in the JID that identifies that component, for example:


jdev@conference.jabber.org/qmacro The hostname conference.jabber.org is what the jabberd backbone uses to route the element. As mentioned earlier, the Conferencing component will relay a message to the real JID that belongs to the user currently in a room hosted by that component.

While the component itself is usually persistent, the room occupants (and so their transient JIDs) are not. When a message is sent to the JID jdev@conference.jabber.org/qmacro and there is no room occupant in the jdev room with the nickname qmacro, the message will still reach its first destination—the component—but be rejected at that stage, as shown in Example 9-5.


A message to a nonexistent transient JID is rejected

SEND: <message to='jdev@conference.jabber.org/qmacro'> <body>Hello there</body> </message>

RECV: <message to='dj@gnu.mine.nu/jarl' from='jdev@conference.jabber.org/qmacro' type='error'> <body>Hello there</body> <error code='404'>Not Found</error> </message>

Although the rejection—the "Not Found" error—is the same as if a message had been sent to a JSM user that didn't exist, the difference is that the transient user always had the potential to exist, whereas the JSM user never did. Of course, if the JID referred to a nonexistent Jabber server, then the error returned wouldn't be a "Not Found" error 404, but an "Unable to resolve hostname" error 502.

</code>

The main script


Now that we have the subroutines and callbacks set up, all we need to do is define the Jabber server and room information:


Server = 'gnu.mine.nu' Username = 'kassist' Password = 'pass' Resource = 'py'

Room = 'jdev' ConfServ = 'conference.jabber.org' Nick = 'kassist'

The kassist user can be set up simply by using the reguser script presented in Section 7.4:


$ ./reguser gnu.mine.nu username=kassist password=pass [Attempt] (kassist) Successful registration $ In the same way as in previous recipes' scripts, a connection attempt is made, followed by an authentication attempt:


con = jabber.Client(host=Server,debug=0,log=0) try: con.connect() except IOError, e: print "Couldn't connect: %s" % e sys.exit(0) else: print "Connected"

if con.auth(Username,Password,Resource): print "Logged in as %s to server %s" % ( Username, Server ) else: print "Problems authenticating: ", con.lastErr, con.lastErrCode sys.exit(1)

Then the message and presence callbacks messageCB() and presenceCB() are defined to the connection object in con:


con.setMessageHandler(messageCB) con.setPresenceHandler(presenceCB)

After sending initial presence, informing the JSM (and anyone who might be subscribed to kassist's presence) of the assistant's availability:


con.send(jabber.Presence())

we also construct—from the Room, ConfServ, and Nick variables—and send the <presence/> element for negotiating entry to the jdev room hosted by the Conferencing component at conference.jabber.org:


roomjid = Room + '@' + ConfServ + '/' + Nick print "Joining " + Room con.send(jabber.Presence(to=roomjid))

The con.send() function will send a <presence/> element that looks like this:


SEND: <presence to='jdev@conference.jabber.org/kassist'/> We're sending available presence to the room, to negotiate entry, but what about the initial presence? Why do we send that too if there are no users who will be subscribed to the kassist JID? If no initial presence is sent, the JSM will merely store up any <message/> elements destined for kassist, as it will think the JID is offline.


The processing loop


Once everything has been set up, we simply need to have the script sit back and wait for incoming packets and handle them appropriately. For this, we simply call the process() function every 5 seconds to look for elements arriving on the XML stream:


while(1): con.process(5)


Connecting Devices to Jabber


LEGO MINDSTORMS. What a great reason to dig out that box of LEGO bricks you haven't touched in years. When I found out that LEGO was bringing out a programmable brick, the RCX,[2], I went to my favorite toy shop and purchased the set. In addition to the RCX (shown in Figure 9-1), the MINDSTORMS set comes with an infrared (IR) port and an IR tower, which you can connect to the serial port of your PC, a battery compartment,[3] motors, touch and light sensors, and various LEGO Technic parts.

The LEGO MINDSTORMS RCX, or "programmable brick"


</code> There are plenty of ways to interact with the RCX. The MINDSTORMS Robotics Invention System (RIS)™ set comes with Windows software with which you can build programs by moving blocks of logic around graphically on the screen and chaining them together. In addition, various efforts on the parts of talented individuals have come up with many different ways to program the RCX. The Unofficial Guide to LEGO® MINDSTORMSâÃÃÂ�

Personal tools