Aiming to remove need for httplib2, but sadly this commit is broken.

This commit is contained in:
Ryan McGrath 2009-05-26 01:29:03 -04:00
parent 10c32e427c
commit 1887280855

205
tango.py
View file

@ -7,114 +7,109 @@
import urllib, urllib2 import urllib, urllib2
try: try:
import simplejson import simplejson
except: except:
print "Tango requires the simplejson library to work. http://www.undefined.org/python/" print "Tango requires the simplejson library to work. http://www.undefined.org/python/"
# Should really deprecate httplib2 at some point...
try:
import httplib2
except:
print "Tango requires httplib2 for authentication purposes. http://code.google.com/p/httplib2/"
try: try:
import oauth import oauth
except: except:
print "Tango requires oauth for authentication purposes. http://oauth.googlecode.com/svn/code/python/oauth/oauth.py" print "Tango requires oauth for authentication purposes. http://oauth.googlecode.com/svn/code/python/oauth/oauth.py"
# Need to support URL shortening
class setup: class setup:
def __init__(self, authtype = "OAuth", username = None, password = None, oauth_keys = None): def __init__(self, authtype = "OAuth", username = None, password = None, oauth_keys = None):
self.authtype = authtype self.authtype = authtype
self.authenticated = False self.authenticated = False
self.username = username self.username = username
self.password = password self.password = password
self.oauth_keys = oauth_keys self.oauth_keys = oauth_keys
self.http = httplib2.Http() # For Basic Auth... self.opener = None
if self.username is not None and self.password is not None: if self.username is not None and self.password is not None:
if self.authtype == "OAuth": if self.authtype == "OAuth":
pass pass
elif self.authtype == "Basic": elif self.authtype == "Basic":
self.http.add_credentials(self.username, self.password) self.auth_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
self.authenticated = True self.auth_manager.add_password(None, "http://twitter.com/account/verify_credentials.json", self.username, self.password)
else: self.handler = urllib2.HTTPBasicAuthHandler(self.auth_manager)
pass self.opener = urllib2.build_opener(self.handler)
self.authenticated = True
def shortenURL(self, url_to_shorten): else:
# Perhaps we should have fallbacks here in case the is.gd API limit gets hit? Maybe allow them to set the host? pass
shortURL = urllib2.urlopen("http://is.gd/api.php?" + urllib.urlencode({"longurl": url_to_shorten})).read()
return shortURL def shortenURL(self, url_to_shorten):
# Perhaps we should have fallbacks here in case the is.gd API limit gets hit? Maybe allow them to set the host?
def constructApiURL(self, base_url, params): shortURL = urllib2.urlopen("http://is.gd/api.php?" + urllib.urlencode({"longurl": url_to_shorten})).read()
queryURL = base_url return shortURL
questionMarkUsed = False
for param in params: def constructApiURL(self, base_url, params):
if params[param] is not None: queryURL = base_url
queryURL += (("&" if questionMarkUsed is True else "?") + param + "=" + params[param]) questionMarkUsed = False
questionMarkUsed = True for param in params:
return queryURL if params[param] is not None:
queryURL += (("&" if questionMarkUsed is True else "?") + param + "=" + params[param])
def getPublicTimeline(self): questionMarkUsed = True
publicTimeline = simplejson.load(urllib2.urlopen("http://twitter.com/statuses/public_timeline.json")) return queryURL
formattedTimeline = []
for tweet in publicTimeline: def getPublicTimeline(self):
formattedTimeline.append(tweet['text']) publicTimeline = simplejson.load(urllib2.urlopen("http://twitter.com/statuses/public_timeline.json"))
return formattedTimeline formattedTimeline = []
for tweet in publicTimeline:
def getUserTimeline(self, **kwargs): formattedTimeline.append(tweet['text'])
# 99% API compliant, I think - need to figure out Gzip compression and auto-getting based on authentication return formattedTimeline
# By doing this with kwargs and constructing a url outside, we can stay somewhat agnostic of API changes - it's all
# based on what the user decides to pass. We just handle the heavy lifting! :D def getUserTimeline(self, **kwargs):
userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + self.username + ".json", kwargs) # 99% API compliant, I think - need to figure out Gzip compression and auto-getting based on authentication
userTimeline = simplejson.load(urllib2.urlopen(userTimelineURL)) # By doing this with kwargs and constructing a url outside, we can stay somewhat agnostic of API changes - it's all
formattedTimeline = [] # based on what the user decides to pass. We just handle the heavy lifting! :D
for tweet in userTimeline: userTimelineURL = self.constructApiURL("http://twitter.com/statuses/user_timeline/" + self.username + ".json", kwargs)
formattedTimeline.append(tweet['text']) userTimeline = simplejson.load(urllib2.urlopen(userTimelineURL))
return formattedTimeline formattedTimeline = []
for tweet in userTimeline:
def getUserMentions(self, **kwargs): formattedTimeline.append(tweet['text'])
if self.authenticated is True: return formattedTimeline
if self.authtype == "Basic":
pass def getUserMentions(self, **kwargs):
else: if self.authenticated is True:
pass if self.authtype == "Basic":
else: pass
print "getUserMentions() requires you to be authenticated." else:
pass pass
else:
def updateStatus(self, status = None, in_reply_to_status_id = None): print "getUserMentions() requires you to be authenticated."
if self.authenticated is True: pass
if self.authtype == "Basic":
self.http.request("http://twitter.com/statuses/update.json", "POST", urllib.urlencode({"status": status}, {"in_reply_to_status_id": in_reply_to_status_id})) def updateStatus(self, status, in_reply_to_status_id = ""):
else: if self.authenticated is True:
print "Sorry, OAuth support is still forthcoming. Feel free to help out on this front!" if self.authtype == "Basic":
pass self.opener.open("http://twitter.com/statuses/update.json" + urllib.urlencode({"status": status}, {"in_reply_to_status_id": in_reply_to_status_id}))
else: print self.opener.open("http://twitter.com/statuses/update.json" + urllib.urlencode({"status": status}, {"in_reply_to_status_id": in_reply_to_status_id})).read()
print "updateStatus() requires you to be authenticated." else:
pass print "Sorry, OAuth support is still forthcoming. Feel free to help out on this front!"
pass
def destroyStatus(self, id): else:
if self.authenticated is True: print "updateStatus() requires you to be authenticated."
self.http.request("http://twitter.com/status/destroy/" + id + ".json", "POST") pass
else:
print "destroyStatus() requires you to be authenticated." def destroyStatus(self, id):
pass if self.authenticated is True:
self.http.request("http://twitter.com/status/destroy/" + id + ".json", "POST")
def getSearchTimeline(self, search_query, optional_page): else:
params = urllib.urlencode({'q': search_query, 'rpp': optional_page}) # Doesn't hurt to do pages this way. *shrug* print "destroyStatus() requires you to be authenticated."
searchTimeline = simplejson.load(urllib2.urlopen("http://search.twitter.com/search.json", params)) pass
formattedTimeline = []
for tweet in searchTimeline['results']: def getSearchTimeline(self, search_query, optional_page):
formattedTimeline.append(tweet['text']) params = urllib.urlencode({'q': search_query, 'rpp': optional_page}) # Doesn't hurt to do pages this way. *shrug*
return formattedTimeline searchTimeline = simplejson.load(urllib2.urlopen("http://search.twitter.com/search.json", params))
formattedTimeline = []
def getCurrentTrends(self): for tweet in searchTimeline['results']:
# Returns an array of dictionary items containing the current trends formattedTimeline.append(tweet['text'])
trendingTopicsURL = "http://search.twitter.com/trends.json" return formattedTimeline
trendingTopics = simplejson.load(urllib.urlopen(trendingTopicsURL))
trendingTopicsArray = [] def getCurrentTrends(self):
for topic in trendingTopics['trends']: # Returns an array of dictionary items containing the current trends
trendingTopicsArray.append({"name" : topic['name'], "url" : topic['url']}) trendingTopicsURL = "http://search.twitter.com/trends.json"
return trendingTopicsArray trendingTopics = simplejson.load(urllib.urlopen(trendingTopicsURL))
trendingTopicsArray = []
for topic in trendingTopics['trends']:
trendingTopicsArray.append({"name" : topic['name'], "url" : topic['url']})
return trendingTopicsArray