'''
Using Google Talk as a distributed Twitter client
A distributed Twitter client in the spirit of:
http://blog.labnotes.org/2008/05/05/distributed-twitter-client-in-20-lines-of-code/
'''
#!/usr/bin/env python
import xmpp
import sys
class DistTwit(object):
def __init__(self,user,pwd,callbacks=None,showself=False):
self._my_jid = xmpp.protocol.JID(user+"/distwit.py")
self._client = xmpp.Client(self._my_jid.getDomain(), debug=[])
if not callbacks:
self._callbacks=[]
else:
self._callbacks=callbacks
self.showself=showself
self._connect()
self._auth(pwd)
self._run()
def _connect(self):
print "Connecting..."
if self._client.connect(server=('talk.google.com',5223)) == "":
raise ConnectionException()
def _auth(self,pwd):
print "Authenticating..."
if self._client.auth(self._my_jid.getNode(),pwd) == None:
raise AuthException()
def add_callback(self,func):
self._callbacks.append(func)
def _run(self):
self._client.sendInitPresence()
self._roster = self._client.getRoster()
self._client.RegisterHandler('presence', self._presence)
quit=False
while not quit:
try:
self._client.Process(1)
except KeyboardInterrupt:
quit=True
def _presence(self,conn,msg):
jid=xmpp.protocol.JID(msg.getFrom())
name=self._roster.getName(jid.getNode()+"@"+jid.getDomain())
if not name:
name=jid.getNode()+"@"+jid.getDomain()
if not self.showself and name == self._my_jid.getNode()+"@"+self._my_jid.getDomain():
return
status = msg.getStatus()
show = msg.getShow()
if not msg.getPriority():
status="Signed out"
elif not status and show:
status="("+msg.getShow()+")"
elif show and status:
status="("+msg.getShow()+") "+status
for f in self._callbacks:
f(name,status)
class ConnectionException(Exception):
def __init__(self):
pass
def __str__(self):
return "Error connecting to talk.google.com"
class AuthException(Exception):
def __init__(self):
pass
def __str__(self):
print "Error authenticating to talk.google.com"
if __name__=="__main__":
def callback(name,status):
print "%s: %s" % (name,status)
DistTwit(sys.argv[1],sys.argv[2],callbacks=[callback])