Skip to content
This repository has been archived by the owner on Feb 19, 2020. It is now read-only.

Event Handlers

Lance Stout edited this page Oct 25, 2010 · 1 revision

Event Handlers

SleekXMPP has an event-driven architecture, which makes understanding how SleekXMPP generates and handles events necessary. SleekXMPP's events fall in two categories: stream events, and triggered events. Stream events arise whenever particular stanzas are received from the XML stream. Triggered events are created whenever xmpp.event(name, data) is called (where xmpp is a SleekXMPP object). See the Event Index for a table of event names and their associated data objects.

Creating Regular Event Handlers

Handling a triggered event is a simple process. For example, if you wish to respond to the "presence_available" event, you would do the following:

# If self is a SleekXMPP object
self.add_event_handler("presence_available", self.handle_available)

The method self.handle_available will need to accept one argument - a <presence /> stanza object. To see what stanzas events use, check the Event Index.

Now, there are two optional parameters to add_event_handler. These are: threaded and disposable. Using threaded=True will allow the event handler to run in its own thread. If you include disposable=True then the event will only be handled once and then the handler will be removed.

Creating Stream Event Handlers

Creating a stream event handler requires a bit more setup. First, we must register a callback handler with the signature of the stanza we wish to handle. For example, taking the <task /> stanza example from Stanza Objects, we would define the following callback:

# If self is a SleekXMPP object and Task is a stanza object class
# See the wiki page Stanza Objects for details on Task

self.registerHandler(
    Callback('Example Handler',
             MatchXPath('{%s}iq/{%s}task' % (self.default_ns, Task.namespace)),
             self.handle_task))

Note that the callback takes a name. The name is necessary if you later wish to remove the handler.

The reference self.handle_task is a method that accepts at least one parameter - a stanza object; in this case, an <iq /> stanza object.

Removing Handlers

Sometimes, it is necessary to remove either stream or event handlers. For example, your application could serve two different roles, and needs to switch between them at runtime.

Removing a handler for an event can be done by using:

self.del_event_handler("presence_available", self.handle_available)

If you want to remove a stream handler, you will need the name used to create the original callback.

self.removeHandler('Example Handler')