The Easiest Way to Save and Share Code Snippets on the web

Twitter extract friends who don't follow back

python

posted: Mar, 9th 2009 | jump to bottom

from xml.dom import minidom
import sys, urllib, time, math
 
def getIds(url):
	ids = []
	doc = minidom.parse(urllib.urlopen(url))
	for entry in doc.getElementsByTagName("id"):
		ids.append(entry.firstChild.data)
	return ids
 
def getTimeLine(id):
	status = {}
	url = "http://twitter.com/statuses/user_timeline/%s.xml?count=1" % id
	dom_status = minidom.parse(urllib.urlopen(url)).getElementsByTagName("status")[0]
 
	status["text"] = dom_status.getElementsByTagName('text')[0].firstChild.data #last update text
 
	last_status_date = time.mktime(time.strptime(dom_status.getElementsByTagName('created_at')[0].firstChild.data, "%a %b %d %H:%M:%S +0000 %Y"))
	hours_since_last_update = (time.mktime(time.gmtime())-last_status_date)/3600 #hours passed since last update
	status["hours_since_last_update"] = "quite active right now"
	if hours_since_last_update>0:
		status["hours_since_last_update"] = "last update %-.0f hour(s) ago" % hours_since_last_update
 
	user = dom_status.getElementsByTagName('user')[0]
	status["screen_name"] = user.getElementsByTagName('screen_name')[0].firstChild.data
	return status
 
username = "raduboncea"
friends_url = "http://twitter.com/friends/ids/%s.xml" % username
followers_url = "http://twitter.com/followers/ids/%s.xml" % username
 
try:
	friends_ids = getIds(friends_url)
	followers_ids = getIds(followers_url)
except Exception,e:
	print "An error occurred while reading or processing the xml input: %s" % e
	sys.exit(0)
 
for friend_id in friends_ids:
	if friend_id not in followers_ids:
		try:
			#Getting user last timeline 
			status = getTimeLine(friend_id)
		except Exception,e:
			print "An error occurred while reading or processing the timeline xml input: %s" % e
			sys.exit(0)
		print "%s\t%s" % (status["screen_name"],str(status["hours_since_last_update"]))
 
11 views