Properly porting files...

This commit is contained in:
Ryan McGrath 2009-08-03 00:45:29 -04:00
parent fb41d4100c
commit 3b22ff34ce
2 changed files with 90 additions and 88 deletions

View file

@ -1,7 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
""" """
Tango is an up-to-date library for Python that wraps the Twitter API. Twython is an up-to-date library for Python that wraps the Twitter API.
Other Python Twitter libraries seem to have fallen a bit behind, and Other Python Twitter libraries seem to have fallen a bit behind, and
Twitter's API has evolved a bit. Here's hoping this helps. Twitter's API has evolved a bit. Here's hoping this helps.
@ -23,14 +23,14 @@ except ImportError:
try: try:
import json as simplejson import json as simplejson
except: except:
raise Exception("Tango requires a json library to work. http://www.undefined.org/python/") raise Exception("Twython requires a json library to work. http://www.undefined.org/python/")
try: try:
import oauth import oauth
except ImportError: except ImportError:
pass pass
class TangoError(Exception): class TwythonError(Exception):
def __init__(self, msg, error_code=None): def __init__(self, msg, error_code=None):
self.msg = msg self.msg = msg
if error_code == 400: if error_code == 400:
@ -38,7 +38,7 @@ class TangoError(Exception):
def __str__(self): def __str__(self):
return repr(self.msg) return repr(self.msg)
class APILimit(TangoError): class APILimit(TwythonError):
def __init__(self, msg): def __init__(self, msg):
self.msg = msg self.msg = msg
def __str__(self): def __str__(self):
@ -65,11 +65,13 @@ class setup:
self.opener = urllib.request.build_opener(self.handler) self.opener = urllib.request.build_opener(self.handler)
if headers is not None: if headers is not None:
self.opener.addheaders = [('User-agent', headers)] self.opener.addheaders = [('User-agent', headers)]
"""
try: try:
test_verify = simplejson.load(self.opener.open("http://twitter.com/account/verify_credentials.json")) test_verify = simplejson.load(self.opener.open("http://twitter.com/account/verify_credentials.json"))
self.authenticated = True self.authenticated = True
except HTTPError as e: except HTTPError as e:
raise TangoError("Authentication failed with your provided credentials. Try again? (%s failure)" % repr(e.code), e.code) raise TwythonError("Authentication failed with your provided credentials. Try again? (%s failure)" % repr(e.code), e.code)
"""
# OAuth functions; shortcuts for verifying the credentials. # OAuth functions; shortcuts for verifying the credentials.
def fetch_response_oauth(self, oauth_request): def fetch_response_oauth(self, oauth_request):
@ -89,7 +91,7 @@ class setup:
try: try:
return urllib.request.urlopen(shortener + "?" + urllib.urlencode({query: url_to_shorten})).read() return urllib.request.urlopen(shortener + "?" + urllib.urlencode({query: url_to_shorten})).read()
except HTTPError as e: except HTTPError as e:
raise TangoError("shortenURL() failed with a %s error code." % repr(e.code)) raise TwythonError("shortenURL() failed with a %s error code." % repr(e.code))
def constructApiURL(self, base_url, params): def constructApiURL(self, base_url, params):
return base_url + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in params.items()]) return base_url + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in params.items()])
@ -102,15 +104,15 @@ class setup:
if self.authenticated is True: if self.authenticated is True:
return simplejson.load(self.opener.open("http://twitter.com/account/rate_limit_status.json")) return simplejson.load(self.opener.open("http://twitter.com/account/rate_limit_status.json"))
else: else:
raise TangoError("You need to be authenticated to check a rate limit status on an account.") raise TwythonError("You need to be authenticated to check a rate limit status on an account.")
except HTTPError as e: except HTTPError as e:
raise TangoError("It seems that there's something wrong. Twitter gave you a %s error code; are you doing something you shouldn't be?" % repr(e.code), e.code) raise TwythonError("It seems that there's something wrong. Twitter gave you a %s error code; are you doing something you shouldn't be?" % repr(e.code), e.code)
def getPublicTimeline(self): def getPublicTimeline(self):
try: try:
return simplejson.load(urllib.request.urlopen("http://twitter.com/statuses/public_timeline.json")) return simplejson.load(urllib.request.urlopen("http://twitter.com/statuses/public_timeline.json"))
except HTTPError as e: except HTTPError as e:
raise TangoError("getPublicTimeline() failed with a %s error code." % repr(e.code)) raise TwythonError("getPublicTimeline() failed with a %s error code." % repr(e.code))
def getFriendsTimeline(self, **kwargs): def getFriendsTimeline(self, **kwargs):
if self.authenticated is True: if self.authenticated is True:
@ -118,9 +120,9 @@ class setup:
friendsTimelineURL = self.constructApiURL("http://twitter.com/statuses/friends_timeline.json", kwargs) friendsTimelineURL = self.constructApiURL("http://twitter.com/statuses/friends_timeline.json", kwargs)
return simplejson.load(self.opener.open(friendsTimelineURL)) return simplejson.load(self.opener.open(friendsTimelineURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getFriendsTimeline() failed with a %s error code." % repr(e.code)) raise TwythonError("getFriendsTimeline() failed with a %s error code." % repr(e.code))
else: else:
raise TangoError("getFriendsTimeline() requires you to be authenticated.") raise TwythonError("getFriendsTimeline() requires you to be authenticated.")
def getUserTimeline(self, id = None, **kwargs): def getUserTimeline(self, id = None, **kwargs):
if id is not None and ("user_id" in kwargs) is False and ("screen_name" in kwargs) is False: if id is not None and ("user_id" in kwargs) is False and ("screen_name" in kwargs) is False:
@ -136,7 +138,7 @@ class setup:
else: else:
return simplejson.load(urllib.request.urlopen(userTimelineURL)) return simplejson.load(urllib.request.urlopen(userTimelineURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? If so, you'll need to authenticate and be their friend to get their timeline." raise TwythonError("Failed with a %s error code. Does this user hide/protect their updates? If so, you'll need to authenticate and be their friend to get their timeline."
% repr(e.code), e.code) % repr(e.code), e.code)
def getUserMentions(self, **kwargs): def getUserMentions(self, **kwargs):
@ -145,9 +147,9 @@ class setup:
mentionsFeedURL = self.constructApiURL("http://twitter.com/statuses/mentions.json", kwargs) mentionsFeedURL = self.constructApiURL("http://twitter.com/statuses/mentions.json", kwargs)
return simplejson.load(self.opener.open(mentionsFeedURL)) return simplejson.load(self.opener.open(mentionsFeedURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getUserMentions() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getUserMentions() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("getUserMentions() requires you to be authenticated.") raise TwythonError("getUserMentions() requires you to be authenticated.")
def showStatus(self, id): def showStatus(self, id):
try: try:
@ -156,28 +158,28 @@ class setup:
else: else:
return simplejson.load(urllib.request.urlopen("http://twitter.com/statuses/show/%s.json" % id)) return simplejson.load(urllib.request.urlopen("http://twitter.com/statuses/show/%s.json" % id))
except HTTPError as e: except HTTPError as e:
raise TangoError("Failed with a %s error code. Does this user hide/protect their updates? You'll need to authenticate and be friends to get their timeline." raise TwythonError("Failed with a %s error code. Does this user hide/protect their updates? You'll need to authenticate and be friends to get their timeline."
% repr(e.code), e.code) % repr(e.code), e.code)
def updateStatus(self, status, in_reply_to_status_id = None): def updateStatus(self, status, in_reply_to_status_id = None):
if self.authenticated is True: if self.authenticated is True:
if len(list(status)) > 140: if len(list(status)) > 140:
raise TangoError("This status message is over 140 characters. Trim it down!") raise TwythonError("This status message is over 140 characters. Trim it down!")
try: try:
return simplejson.load(self.opener.open("http://twitter.com/statuses/update.json?", urllib.parse.urlencode({"status": status, "in_reply_to_status_id": in_reply_to_status_id}))) return simplejson.load(self.opener.open("http://twitter.com/statuses/update.json?", urllib.parse.urlencode({"status": status, "in_reply_to_status_id": in_reply_to_status_id})))
except HTTPError as e: except HTTPError as e:
raise TangoError("updateStatus() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("updateStatus() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("updateStatus() requires you to be authenticated.") raise TwythonError("updateStatus() requires you to be authenticated.")
def destroyStatus(self, id): def destroyStatus(self, id):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/status/destroy/%s.json", "POST" % id)) return simplejson.load(self.opener.open("http://twitter.com/status/destroy/%s.json", "POST" % id))
except HTTPError as e: except HTTPError as e:
raise TangoError("destroyStatus() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("destroyStatus() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("destroyStatus() requires you to be authenticated.") raise TwythonError("destroyStatus() requires you to be authenticated.")
def endSession(self): def endSession(self):
if self.authenticated is True: if self.authenticated is True:
@ -185,9 +187,9 @@ class setup:
self.opener.open("http://twitter.com/account/end_session.json", "") self.opener.open("http://twitter.com/account/end_session.json", "")
self.authenticated = False self.authenticated = False
except HTTPError as e: except HTTPError as e:
raise TangoError("endSession failed with a %s error code." % repr(e.code), e.code) raise TwythonError("endSession failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("You can't end a session when you're not authenticated to begin with.") raise TwythonError("You can't end a session when you're not authenticated to begin with.")
def getDirectMessages(self, since_id = None, max_id = None, count = None, page = "1"): def getDirectMessages(self, since_id = None, max_id = None, count = None, page = "1"):
if self.authenticated is True: if self.authenticated is True:
@ -202,9 +204,9 @@ class setup:
try: try:
return simplejson.load(self.opener.open(apiURL)) return simplejson.load(self.opener.open(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getDirectMessages() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getDirectMessages() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("getDirectMessages() requires you to be authenticated.") raise TwythonError("getDirectMessages() requires you to be authenticated.")
def getSentMessages(self, since_id = None, max_id = None, count = None, page = "1"): def getSentMessages(self, since_id = None, max_id = None, count = None, page = "1"):
if self.authenticated is True: if self.authenticated is True:
@ -219,9 +221,9 @@ class setup:
try: try:
return simplejson.load(self.opener.open(apiURL)) return simplejson.load(self.opener.open(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getSentMessages() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getSentMessages() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("getSentMessages() requires you to be authenticated.") raise TwythonError("getSentMessages() requires you to be authenticated.")
def sendDirectMessage(self, user, text): def sendDirectMessage(self, user, text):
if self.authenticated is True: if self.authenticated is True:
@ -229,20 +231,20 @@ class setup:
try: try:
return self.opener.open("http://twitter.com/direct_messages/new.json", urllib.parse.urlencode({"user": user, "text": text})) return self.opener.open("http://twitter.com/direct_messages/new.json", urllib.parse.urlencode({"user": user, "text": text}))
except HTTPError as e: except HTTPError as e:
raise TangoError("sendDirectMessage() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("sendDirectMessage() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("Your message must not be longer than 140 characters") raise TwythonError("Your message must not be longer than 140 characters")
else: else:
raise TangoError("You must be authenticated to send a new direct message.") raise TwythonError("You must be authenticated to send a new direct message.")
def destroyDirectMessage(self, id): def destroyDirectMessage(self, id):
if self.authenticated is True: if self.authenticated is True:
try: try:
return self.opener.open("http://twitter.com/direct_messages/destroy/%s.json" % id, "") return self.opener.open("http://twitter.com/direct_messages/destroy/%s.json" % id, "")
except HTTPError as e: except HTTPError as e:
raise TangoError("destroyDirectMessage() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("destroyDirectMessage() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("You must be authenticated to destroy a direct message.") raise TwythonError("You must be authenticated to destroy a direct message.")
def createFriendship(self, id = None, user_id = None, screen_name = None, follow = "false"): def createFriendship(self, id = None, user_id = None, screen_name = None, follow = "false"):
if self.authenticated is True: if self.authenticated is True:
@ -258,10 +260,10 @@ class setup:
except HTTPError as e: except HTTPError as e:
# Rate limiting is done differently here for API reasons... # Rate limiting is done differently here for API reasons...
if e.code == 403: if e.code == 403:
raise TangoError("You've hit the update limit for this method. Try again in 24 hours.") raise TwythonError("You've hit the update limit for this method. Try again in 24 hours.")
raise TangoError("createFriendship() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("createFriendship() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("createFriendship() requires you to be authenticated.") raise TwythonError("createFriendship() requires you to be authenticated.")
def destroyFriendship(self, id = None, user_id = None, screen_name = None): def destroyFriendship(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True: if self.authenticated is True:
@ -275,36 +277,36 @@ class setup:
try: try:
return simplejson.load(self.opener.open(apiURL)) return simplejson.load(self.opener.open(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("destroyFriendship() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("destroyFriendship() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("destroyFriendship() requires you to be authenticated.") raise TwythonError("destroyFriendship() requires you to be authenticated.")
def checkIfFriendshipExists(self, user_a, user_b): def checkIfFriendshipExists(self, user_a, user_b):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/friendships/exists.json", urllib.parse.urlencode({"user_a": user_a, "user_b": user_b}))) return simplejson.load(self.opener.open("http://twitter.com/friendships/exists.json", urllib.parse.urlencode({"user_a": user_a, "user_b": user_b})))
except HTTPError as e: except HTTPError as e:
raise TangoError("checkIfFriendshipExists() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("checkIfFriendshipExists() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("checkIfFriendshipExists(), oddly, requires that you be authenticated.") raise TwythonError("checkIfFriendshipExists(), oddly, requires that you be authenticated.")
def updateDeliveryDevice(self, device_name = "none"): def updateDeliveryDevice(self, device_name = "none"):
if self.authenticated is True: if self.authenticated is True:
try: try:
return self.opener.open("http://twitter.com/account/update_delivery_device.json?", urllib.parse.urlencode({"device": device_name})) return self.opener.open("http://twitter.com/account/update_delivery_device.json?", urllib.parse.urlencode({"device": device_name}))
except HTTPError as e: except HTTPError as e:
raise TangoError("updateDeliveryDevice() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("updateDeliveryDevice() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("updateDeliveryDevice() requires you to be authenticated.") raise TwythonError("updateDeliveryDevice() requires you to be authenticated.")
def updateProfileColors(self, **kwargs): def updateProfileColors(self, **kwargs):
if self.authenticated is True: if self.authenticated is True:
try: try:
return self.opener.open(self.constructApiURL("http://twitter.com/account/update_profile_colors.json?", kwargs)) return self.opener.open(self.constructApiURL("http://twitter.com/account/update_profile_colors.json?", kwargs))
except HTTPError as e: except HTTPError as e:
raise TangoError("updateProfileColors() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("updateProfileColors() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("updateProfileColors() requires you to be authenticated.") raise TwythonError("updateProfileColors() requires you to be authenticated.")
def updateProfile(self, name = None, email = None, url = None, location = None, description = None): def updateProfile(self, name = None, email = None, url = None, location = None, description = None):
if self.authenticated is True: if self.authenticated is True:
@ -315,7 +317,7 @@ class setup:
updateProfileQueryString += "name=" + name updateProfileQueryString += "name=" + name
useAmpersands = True useAmpersands = True
else: else:
raise TangoError("Twitter has a character limit of 20 for all usernames. Try again.") raise TwythonError("Twitter has a character limit of 20 for all usernames. Try again.")
if email is not None and "@" in email: if email is not None and "@" in email:
if len(list(email)) < 40: if len(list(email)) < 40:
if useAmpersands is True: if useAmpersands is True:
@ -324,7 +326,7 @@ class setup:
updateProfileQueryString += "email=" + email updateProfileQueryString += "email=" + email
useAmpersands = True useAmpersands = True
else: else:
raise TangoError("Twitter has a character limit of 40 for all email addresses, and the email address must be valid. Try again.") raise TwythonError("Twitter has a character limit of 40 for all email addresses, and the email address must be valid. Try again.")
if url is not None: if url is not None:
if len(list(url)) < 100: if len(list(url)) < 100:
if useAmpersands is True: if useAmpersands is True:
@ -333,7 +335,7 @@ class setup:
updateProfileQueryString += urllib.parse.urlencode({"url": url}) updateProfileQueryString += urllib.parse.urlencode({"url": url})
useAmpersands = True useAmpersands = True
else: else:
raise TangoError("Twitter has a character limit of 100 for all urls. Try again.") raise TwythonError("Twitter has a character limit of 100 for all urls. Try again.")
if location is not None: if location is not None:
if len(list(location)) < 30: if len(list(location)) < 30:
if useAmpersands is True: if useAmpersands is True:
@ -342,7 +344,7 @@ class setup:
updateProfileQueryString += urllib.parse.urlencode({"location": location}) updateProfileQueryString += urllib.parse.urlencode({"location": location})
useAmpersands = True useAmpersands = True
else: else:
raise TangoError("Twitter has a character limit of 30 for all locations. Try again.") raise TwythonError("Twitter has a character limit of 30 for all locations. Try again.")
if description is not None: if description is not None:
if len(list(description)) < 160: if len(list(description)) < 160:
if useAmpersands is True: if useAmpersands is True:
@ -350,42 +352,42 @@ class setup:
else: else:
updateProfileQueryString += urllib.parse.urlencode({"description": description}) updateProfileQueryString += urllib.parse.urlencode({"description": description})
else: else:
raise TangoError("Twitter has a character limit of 160 for all descriptions. Try again.") raise TwythonError("Twitter has a character limit of 160 for all descriptions. Try again.")
if updateProfileQueryString != "": if updateProfileQueryString != "":
try: try:
return self.opener.open("http://twitter.com/account/update_profile.json?", updateProfileQueryString) return self.opener.open("http://twitter.com/account/update_profile.json?", updateProfileQueryString)
except HTTPError as e: except HTTPError as e:
raise TangoError("updateProfile() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("updateProfile() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("updateProfile() requires you to be authenticated.") raise TwythonError("updateProfile() requires you to be authenticated.")
def getFavorites(self, page = "1"): def getFavorites(self, page = "1"):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/favorites.json?page=" + page)) return simplejson.load(self.opener.open("http://twitter.com/favorites.json?page=" + page))
except HTTPError as e: except HTTPError as e:
raise TangoError("getFavorites() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getFavorites() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("getFavorites() requires you to be authenticated.") raise TwythonError("getFavorites() requires you to be authenticated.")
def createFavorite(self, id): def createFavorite(self, id):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/favorites/create/" + id + ".json", "")) return simplejson.load(self.opener.open("http://twitter.com/favorites/create/" + id + ".json", ""))
except HTTPError as e: except HTTPError as e:
raise TangoError("createFavorite() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("createFavorite() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("createFavorite() requires you to be authenticated.") raise TwythonError("createFavorite() requires you to be authenticated.")
def destroyFavorite(self, id): def destroyFavorite(self, id):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/favorites/destroy/" + id + ".json", "")) return simplejson.load(self.opener.open("http://twitter.com/favorites/destroy/" + id + ".json", ""))
except HTTPError as e: except HTTPError as e:
raise TangoError("destroyFavorite() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("destroyFavorite() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("destroyFavorite() requires you to be authenticated.") raise TwythonError("destroyFavorite() requires you to be authenticated.")
def notificationFollow(self, id = None, user_id = None, screen_name = None): def notificationFollow(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True: if self.authenticated is True:
@ -399,9 +401,9 @@ class setup:
try: try:
return simplejson.load(self.opener.open(apiURL, "")) return simplejson.load(self.opener.open(apiURL, ""))
except HTTPError as e: except HTTPError as e:
raise TangoError("notificationFollow() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("notificationFollow() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("notificationFollow() requires you to be authenticated.") raise TwythonError("notificationFollow() requires you to be authenticated.")
def notificationLeave(self, id = None, user_id = None, screen_name = None): def notificationLeave(self, id = None, user_id = None, screen_name = None):
if self.authenticated is True: if self.authenticated is True:
@ -415,9 +417,9 @@ class setup:
try: try:
return simplejson.load(self.opener.open(apiURL, "")) return simplejson.load(self.opener.open(apiURL, ""))
except HTTPError as e: except HTTPError as e:
raise TangoError("notificationLeave() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("notificationLeave() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("notificationLeave() requires you to be authenticated.") raise TwythonError("notificationLeave() requires you to be authenticated.")
def getFriendsIDs(self, id = None, user_id = None, screen_name = None, page = "1"): def getFriendsIDs(self, id = None, user_id = None, screen_name = None, page = "1"):
apiURL = "" apiURL = ""
@ -430,7 +432,7 @@ class setup:
try: try:
return simplejson.load(urllib.request.urlopen(apiURL)) return simplejson.load(urllib.request.urlopen(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getFriendsIDs() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getFriendsIDs() failed with a %s error code." % repr(e.code), e.code)
def getFollowersIDs(self, id = None, user_id = None, screen_name = None, page = "1"): def getFollowersIDs(self, id = None, user_id = None, screen_name = None, page = "1"):
apiURL = "" apiURL = ""
@ -443,25 +445,25 @@ class setup:
try: try:
return simplejson.load(urllib.request.urlopen(apiURL)) return simplejson.load(urllib.request.urlopen(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getFollowersIDs() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getFollowersIDs() failed with a %s error code." % repr(e.code), e.code)
def createBlock(self, id): def createBlock(self, id):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/create/" + id + ".json", "")) return simplejson.load(self.opener.open("http://twitter.com/blocks/create/" + id + ".json", ""))
except HTTPError as e: except HTTPError as e:
raise TangoError("createBlock() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("createBlock() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("createBlock() requires you to be authenticated.") raise TwythonError("createBlock() requires you to be authenticated.")
def destroyBlock(self, id): def destroyBlock(self, id):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/destroy/" + id + ".json", "")) return simplejson.load(self.opener.open("http://twitter.com/blocks/destroy/" + id + ".json", ""))
except HTTPError as e: except HTTPError as e:
raise TangoError("destroyBlock() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("destroyBlock() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("destroyBlock() requires you to be authenticated.") raise TwythonError("destroyBlock() requires you to be authenticated.")
def checkIfBlockExists(self, id = None, user_id = None, screen_name = None): def checkIfBlockExists(self, id = None, user_id = None, screen_name = None):
apiURL = "" apiURL = ""
@ -474,32 +476,32 @@ class setup:
try: try:
return simplejson.load(urllib.request.urlopen(apiURL)) return simplejson.load(urllib.request.urlopen(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("checkIfBlockExists() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("checkIfBlockExists() failed with a %s error code." % repr(e.code), e.code)
def getBlocking(self, page = "1"): def getBlocking(self, page = "1"):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking.json?page=" + page)) return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking.json?page=" + page))
except HTTPError as e: except HTTPError as e:
raise TangoError("getBlocking() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getBlocking() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("getBlocking() requires you to be authenticated") raise TwythonError("getBlocking() requires you to be authenticated")
def getBlockedIDs(self): def getBlockedIDs(self):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking/ids.json")) return simplejson.load(self.opener.open("http://twitter.com/blocks/blocking/ids.json"))
except HTTPError as e: except HTTPError as e:
raise TangoError("getBlockedIDs() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getBlockedIDs() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("getBlockedIDs() requires you to be authenticated.") raise TwythonError("getBlockedIDs() requires you to be authenticated.")
def searchTwitter(self, search_query, **kwargs): def searchTwitter(self, search_query, **kwargs):
searchURL = self.constructApiURL("http://search.twitter.com/search.json", kwargs) + "&" + urllib.parse.urlencode({"q": search_query}) searchURL = self.constructApiURL("http://search.twitter.com/search.json", kwargs) + "&" + urllib.parse.urlencode({"q": search_query})
try: try:
return simplejson.load(urllib.request.urlopen(searchURL)) return simplejson.load(urllib.request.urlopen(searchURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getSearchTimeline() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getSearchTimeline() failed with a %s error code." % repr(e.code), e.code)
def getCurrentTrends(self, excludeHashTags = False): def getCurrentTrends(self, excludeHashTags = False):
apiURL = "http://search.twitter.com/trends/current.json" apiURL = "http://search.twitter.com/trends/current.json"
@ -508,7 +510,7 @@ class setup:
try: try:
return simplejson.load(urllib.urlopen(apiURL)) return simplejson.load(urllib.urlopen(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getCurrentTrends() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getCurrentTrends() failed with a %s error code." % repr(e.code), e.code)
def getDailyTrends(self, date = None, exclude = False): def getDailyTrends(self, date = None, exclude = False):
apiURL = "http://search.twitter.com/trends/daily.json" apiURL = "http://search.twitter.com/trends/daily.json"
@ -524,7 +526,7 @@ class setup:
try: try:
return simplejson.load(urllib.urlopen(apiURL)) return simplejson.load(urllib.urlopen(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getDailyTrends() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getDailyTrends() failed with a %s error code." % repr(e.code), e.code)
def getWeeklyTrends(self, date = None, exclude = False): def getWeeklyTrends(self, date = None, exclude = False):
apiURL = "http://search.twitter.com/trends/daily.json" apiURL = "http://search.twitter.com/trends/daily.json"
@ -540,43 +542,43 @@ class setup:
try: try:
return simplejson.load(urllib.urlopen(apiURL)) return simplejson.load(urllib.urlopen(apiURL))
except HTTPError as e: except HTTPError as e:
raise TangoError("getWeeklyTrends() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getWeeklyTrends() failed with a %s error code." % repr(e.code), e.code)
def getSavedSearches(self): def getSavedSearches(self):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches.json")) return simplejson.load(self.opener.open("http://twitter.com/saved_searches.json"))
except HTTPError as e: except HTTPError as e:
raise TangoError("getSavedSearches() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("getSavedSearches() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("getSavedSearches() requires you to be authenticated.") raise TwythonError("getSavedSearches() requires you to be authenticated.")
def showSavedSearch(self, id): def showSavedSearch(self, id):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/show/" + id + ".json")) return simplejson.load(self.opener.open("http://twitter.com/saved_searches/show/" + id + ".json"))
except HTTPError as e: except HTTPError as e:
raise TangoError("showSavedSearch() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("showSavedSearch() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("showSavedSearch() requires you to be authenticated.") raise TwythonError("showSavedSearch() requires you to be authenticated.")
def createSavedSearch(self, query): def createSavedSearch(self, query):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/create.json?query=" + query, "")) return simplejson.load(self.opener.open("http://twitter.com/saved_searches/create.json?query=" + query, ""))
except HTTPError as e: except HTTPError as e:
raise TangoError("createSavedSearch() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("createSavedSearch() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("createSavedSearch() requires you to be authenticated.") raise TwythonError("createSavedSearch() requires you to be authenticated.")
def destroySavedSearch(self, id): def destroySavedSearch(self, id):
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://twitter.com/saved_searches/destroy/" + id + ".json", "")) return simplejson.load(self.opener.open("http://twitter.com/saved_searches/destroy/" + id + ".json", ""))
except HTTPError as e: except HTTPError as e:
raise TangoError("destroySavedSearch() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("destroySavedSearch() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("destroySavedSearch() requires you to be authenticated.") raise TwythonError("destroySavedSearch() requires you to be authenticated.")
# The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set. # The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set.
def updateProfileBackgroundImage(self, filename, tile="true"): def updateProfileBackgroundImage(self, filename, tile="true"):
@ -589,9 +591,9 @@ class setup:
r = urllib.request.Request("http://twitter.com/account/update_profile_background_image.json?tile=" + tile, body, headers) r = urllib.request.Request("http://twitter.com/account/update_profile_background_image.json?tile=" + tile, body, headers)
return self.opener.open(r).read() return self.opener.open(r).read()
except HTTPError as e: except HTTPError as e:
raise TangoError("updateProfileBackgroundImage() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("updateProfileBackgroundImage() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("You realize you need to be authenticated to change a background image, right?") raise TwythonError("You realize you need to be authenticated to change a background image, right?")
def updateProfileImage(self, filename): def updateProfileImage(self, filename):
if self.authenticated is True: if self.authenticated is True:
@ -603,9 +605,9 @@ class setup:
r = urllib.request.Request("http://twitter.com/account/update_profile_image.json", body, headers) r = urllib.request.Request("http://twitter.com/account/update_profile_image.json", body, headers)
return self.opener.open(r).read() return self.opener.open(r).read()
except HTTPError as e: except HTTPError as e:
raise TangoError("updateProfileImage() failed with a %s error code." % repr(e.code), e.code) raise TwythonError("updateProfileImage() failed with a %s error code." % repr(e.code), e.code)
else: else:
raise TangoError("You realize you need to be authenticated to change a profile image, right?") raise TwythonError("You realize you need to be authenticated to change a profile image, right?")
def encode_multipart_formdata(self, fields, files): def encode_multipart_formdata(self, fields, files):
BOUNDARY = mimetools.choose_boundary() BOUNDARY = mimetools.choose_boundary()