http://blog.labnotes.org/2008/05/05/distributed-twitter-client-in-20-lines-of-code/
1 2 #!/usr/bin/env python 3 import xmpp 4 import sys 5 6 class DistTwit(object): 7 def __init__(self,user,pwd,callbacks=None,showself=False): 8 self._my_jid = xmpp.protocol.JID(user+"/distwit.py") 9 self._client = xmpp.Client(self._my_jid.getDomain(), debug=[]) 10 if not callbacks: 11 self._callbacks=[] 12 else: 13 self._callbacks=callbacks 14 self.showself=showself 15 16 self._connect() 17 self._auth(pwd) 18 self._run() 19 20 def _connect(self): 21 print "Connecting..." 22 if self._client.connect(server=('talk.google.com',5223)) == "": 23 raise ConnectionException() 24 25 def _auth(self,pwd): 26 print "Authenticating..." 27 if self._client.auth(self._my_jid.getNode(),pwd) == None: 28 raise AuthException() 29 30 def add_callback(self,func): 31 self._callbacks.append(func) 32 33 def _run(self): 34 self._client.sendInitPresence() 35 self._roster = self._client.getRoster() 36 37 self._client.RegisterHandler('presence', self._presence) 38 quit=False 39 while not quit: 40 try: 41 self._client.Process(1) 42 except KeyboardInterrupt: 43 quit=True 44 45 def _presence(self,conn,msg): 46 jid=xmpp.protocol.JID(msg.getFrom()) 47 name=self._roster.getName(jid.getNode()+"@"+jid.getDomain()) 48 49 if not name: 50 name=jid.getNode()+"@"+jid.getDomain() 51 52 if not self.showself and name == self._my_jid.getNode()+"@"+self._my_jid.getDomain(): 53 return 54 55 status = msg.getStatus() 56 show = msg.getShow() 57 58 if not msg.getPriority(): 59 status="Signed out" 60 elif not status and show: 61 status="("+msg.getShow()+")" 62 elif show and status: 63 status="("+msg.getShow()+") "+status 64 65 for f in self._callbacks: 66 f(name,status) 67 68 class ConnectionException(Exception): 69 def __init__(self): 70 pass 71 def __str__(self): 72 return "Error connecting to talk.google.com" 73 74 class AuthException(Exception): 75 def __init__(self): 76 pass 77 def __str__(self): 78 print "Error authenticating to talk.google.com" 79 80 81 if __name__=="__main__": 82 def callback(name,status): 83 print "%s: %s" % (name,status) 84 85 DistTwit(sys.argv[1],sys.argv[2],callbacks=[callback]) 86