我很重视在Ars Technica的这个出色的tutorial上代码,所以我能够跟踪我自己的新追随者,因为我的登录信息是硬编码的。但是,我想追踪其他追随者人们的帐户也是如此。我怎样才能做到这一点没有他们的密码?如何使用Twitter Streaming API跟踪其他帐户的新追随者我没有登录信息?
import pycurl, json, StringIO
STREAM_URL = "http://stream.twitter.com/1/statuses/filter.json?follow=[userid1],[userid2]&track=[keyword1],[keyword2]"
REST_URL = "http://api.twitter.com/1/"
class Client:
def __init__(self):
self.friends = []
self.buffer = ""
self.userid = None
self.conn = pycurl.Curl()
def authenticate(self, username, password):
output = StringIO.StringIO()
self.conn.setopt(pycurl.USERPWD, "%s:%s" % (username, password))
self.conn.setopt(pycurl.URL, REST_URL + "account/verify_credentials.json")
self.conn.setopt(pycurl.WRITEFUNCTION, output.write)
self.conn.perform()
data = json.loads(output.getvalue())
if "error" in data: return False
self.userid = data["id"]
return True
def connect(self):
self.conn.setopt(pycurl.URL, STREAM_URL)
self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
self.conn.perform()
def on_receive(self, data):
self.buffer += data
if data.endswith("\r\n") and self.buffer.strip():
content = json.loads(self.buffer)
self.buffer = ""
print content
if "friends" in content:
self.friends = content["friends"]
elif "event" in content and content["event"] == "follow":
id_list = ['[userid1]','[userid2]']
print "NEW FOLLOWER!!"
print "target id:", content["target"]["id"]
if content["target"]["id"] in id_list:
print content
print "New follower:", content["source"]["name"], "(@" + content["source"]["screen_name"] + ")"
elif content["source"]["id"] == self.userid:
self.friends.append(content["target"]["id"])
elif "text" in content:
to = content["in_reply_to_user_id"]
if to and to != self.userid and to not in self.friends: return
if to == self.userid: print "(REPLY)",
print u"{0[user][name]}: {0[text]}".format(content)
client = Client()
if client.authenticate("[username]", "[password]"):
client.connect()
else:
print "Login credentials aren't valid!"
FTFY - 如果您在问题窗口中缩进代码,它将被格式化为代码(仅对内联代码使用反引号)。 – katrielalex 2010-08-19 15:33:49
谢谢,katrielalex! – user374372 2010-08-19 15:49:26
为什么你不能在你的'follow'参数中添加更多'[userid]'并且继续寻找你正在做的跟随事件?它似乎并不是(只要用户不受保护),您需要通过用户身份验证,以使用流api进行跟踪。如果我在正确的轨道上,我会将其扩展为一个答案。 – nearlymonolith 2010-08-19 18:42:29