Advertisement
Guest User

V

a guest
Aug 23rd, 2010
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. import pycurl, json, StringIO
  2. STREAM_URL = "http://stream.twitter.com/1/statuses/filter.json?follow=[userid1],[userid2]&track=[keyword1],[keyword2]"
  3. REST_URL = "http://api.twitter.com/1/"
  4.  
  5. class Client:
  6.     def __init__(self):
  7.         self.friends = []
  8.         self.buffer = ""
  9.         self.userid = None
  10.         self.conn = pycurl.Curl()
  11.  
  12.     def authenticate(self, username, password):
  13.         output = StringIO.StringIO()
  14.         self.conn.setopt(pycurl.USERPWD, "%s:%s" % (username, password))
  15.         self.conn.setopt(pycurl.URL, REST_URL + "account/verify_credentials.json")
  16.         self.conn.setopt(pycurl.WRITEFUNCTION, output.write)
  17.         self.conn.perform()
  18.  
  19.     data = json.loads(output.getvalue())
  20.     if "error" in data: return False
  21.     self.userid = data["id"]
  22.     return True
  23.  
  24.     def connect(self):
  25.         self.conn.setopt(pycurl.URL, STREAM_URL)
  26.         self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
  27.         self.conn.perform()
  28.  
  29.     def on_receive(self, data):
  30.         self.buffer += data
  31.         if data.endswith("\r\n") and self.buffer.strip():
  32.             content = json.loads(self.buffer)
  33.             self.buffer = ""
  34.             print content
  35.  
  36.         if "friends" in content:
  37.             self.friends = content["friends"]
  38.  
  39.         elif "event" in content and content["event"] == "follow":  
  40.             id_list = ['[userid1]','[userid2]']
  41.             print "NEW FOLLOWER!!"
  42.             print "target id:", content["target"]["id"]
  43.             if content["target"]["id"] in id_list:  
  44.                 print content
  45.                 print "New follower:", content["source"]["name"], "(@" + content["source"]["screen_name"] + ")"  
  46.             elif content["source"]["id"] == self.userid:  
  47.                 self.friends.append(content["target"]["id"])
  48.  
  49.         elif "text" in content:
  50.             to = content["in_reply_to_user_id"]
  51.             if to and to != self.userid and to not in self.friends: return
  52.             if to == self.userid: print "(REPLY)",
  53.             print u"{0[user][name]}: {0[text]}".format(content)
  54.  
  55. client = Client()  
  56. if client.authenticate("[username]", "[password]"):  
  57.     client.connect()  
  58. else:  
  59.     print "Login credentials aren't valid!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement