Jabber is my favorite IM protocol for years and not only because of this Open Source license but for its open minded approach. You can choose which server will provide you your service. I could be your company, a server in your country or Google because GTalk is build on top of Jabber (they just added Jingle for the sound supports). (BTW I’m waiting for Telepathy for my (stable) GNU/Linux box.)
That matter isn’t about Jabber or not here, but about a tool that lots of people are intrigued about, Bots. I’m not talking about Spambot but a chatting bot. Mine is very easy and it does quite nothing. Like a hello world, it’s interesting because you can see what is the power underlying a concept or a technology.
First of all, you need a jabber account (not a Google one, see bellow). Now let’s start by importing everything that is required for this from the Twisted Words libraries.
from twisted.words.protocols.jabber import client, jid from twisted.xish import domish, xmlstream from twisted.internet import reactor
Now, create the client. JID stands for Jabber ID.
me = jid.JID("greutly@swissjabber.ch/TwistedWords") factory = client.basicClientFactory(me, "password")
The client works with callbacks, it’s event driven here. The one that is required is relative to the authentication.
def authd(xmlstream): # need to send presence so clients know we're # actually online. presence = domish.Element(('jabber:client', 'presence')) presence.addElement('status').addContent('Online') xmlstream.send(presence) # add a callback for the messages xmlstream.addObserver('/message', gotMessage)
The callback called gotMessage
will receive the incoming
messages and display them directly.
def gotMessage(message): # sorry for the __str__(), makes unicode happy print u"from: %s" % message["from"] for e in message.elements(): if e.name == "body": print unicode(e.__str__()) break
Now set the authentication callback to the factory.
factory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, authd)
And go!
reactor.connectTCP("swissjabber.ch", 5222, factory) reactor.run()
The previous example doesn’t work with GMail account because they require TLS (that isn’t support for my version of Twisted Words). It seems that in the trac their is a support for TLS but I didn’t search much more longer in this direction.
The little script that is above. There is another one that will answer you when you talked to him. It reverses the words in the sentence you gave it before answering you.
Have fun! Twist’n’shout!