added getUserProfile to retrieve all the information based on user screen_name or id

This commit is contained in:
Luis M. Morales S 2011-08-28 14:39:08 +02:00
parent d6d8823dc2
commit 1a8230bd3e
6 changed files with 443 additions and 368 deletions

5
.idea/encodings.xml generated Normal file
View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
</project>

8
.idea/misc.xml generated Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DependencyValidationManager">
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7.1 (C:/projects/critiqus/environment/Scripts/python.exe)" project-jdk-type="Python SDK" />
</project>

9
.idea/modules.xml generated Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/twython.iml" filepath="$PROJECT_DIR$/.idea/twython.iml" />
</modules>
</component>
</project>

9
.idea/twython.iml generated Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

7
.idea/vcs.xml generated Normal file
View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View file

@ -34,452 +34,489 @@ from urllib2 import HTTPError
# simplejson exists behind the scenes anyway. Past Python 2.6, this should # simplejson exists behind the scenes anyway. Past Python 2.6, this should
# never really cause any problems to begin with. # never really cause any problems to begin with.
try: try:
# Python 2.6 and up # Python 2.6 and up
import json as simplejson import json as simplejson
except ImportError: except ImportError:
try: try:
# Python 2.6 and below (2.4/2.5, 2.3 is not guranteed to work with this library to begin with) # Python 2.6 and below (2.4/2.5, 2.3 is not guranteed to work with this library to begin with)
import simplejson import simplejson
except ImportError: except ImportError:
try: try:
# This case gets rarer by the day, but if we need to, we can pull it from Django provided it's there. # This case gets rarer by the day, but if we need to, we can pull it from Django provided it's there.
from django.utils import simplejson from django.utils import simplejson
except: except:
# Seriously wtf is wrong with you if you get this Exception. # Seriously wtf is wrong with you if you get this Exception.
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/") raise Exception(
"Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
# Try and gauge the old OAuth2 library spec. Versions 1.5 and greater no longer have the callback # Try and gauge the old OAuth2 library spec. Versions 1.5 and greater no longer have the callback
# url as part of the request object; older versions we need to patch for Python 2.5... ugh. ;P # url as part of the request object; older versions we need to patch for Python 2.5... ugh. ;P
OAUTH_CALLBACK_IN_URL = False OAUTH_CALLBACK_IN_URL = False
OAUTH_LIB_SUPPORTS_CALLBACK = False OAUTH_LIB_SUPPORTS_CALLBACK = False
if float(oauth._version.manual_verstr) <= 1.4: if float(oauth._version.manual_verstr) <= 1.4:
OAUTH_CLIENT_INSPECTION = inspect.getargspec(oauth.Client.request) OAUTH_CLIENT_INSPECTION = inspect.getargspec(oauth.Client.request)
try: try:
OAUTH_LIB_SUPPORTS_CALLBACK = 'callback_url' in OAUTH_CLIENT_INSPECTION.args OAUTH_LIB_SUPPORTS_CALLBACK = 'callback_url' in OAUTH_CLIENT_INSPECTION.args
except AttributeError: except AttributeError:
# Python 2.5 doesn't return named tuples, so don't look for an args section specifically. # Python 2.5 doesn't return named tuples, so don't look for an args section specifically.
OAUTH_LIB_SUPPORTS_CALLBACK = 'callback_url' in OAUTH_CLIENT_INSPECTION OAUTH_LIB_SUPPORTS_CALLBACK = 'callback_url' in OAUTH_CLIENT_INSPECTION
else: else:
OAUTH_CALLBACK_IN_URL = True OAUTH_CALLBACK_IN_URL = True
class TwythonError(AttributeError): class TwythonError(AttributeError):
""" """
Generic error class, catch-all for most Twython issues. Generic error class, catch-all for most Twython issues.
Special cases are handled by APILimit and AuthError. Special cases are handled by APILimit and AuthError.
Note: To use these, the syntax has changed as of Twython 1.3. To catch these, Note: To use these, the syntax has changed as of Twython 1.3. To catch these,
you need to explicitly import them into your code, e.g: you need to explicitly import them into your code, e.g:
from twython import TwythonError, APILimit, AuthError from twython import TwythonError, APILimit, AuthError
""" """
def __init__(self, msg, error_code=None):
self.msg = msg
if error_code == 400:
raise APILimit(msg)
def __str__(self): def __init__(self, msg, error_code=None):
return repr(self.msg) self.msg = msg
if error_code == 400:
raise APILimit(msg)
def __str__(self):
return repr(self.msg)
class APILimit(TwythonError): class APILimit(TwythonError):
""" """
Raised when you've hit an API limit. Try to avoid these, read the API Raised when you've hit an API limit. Try to avoid these, read the API
docs if you're running into issues here, Twython does not concern itself with docs if you're running into issues here, Twython does not concern itself with
this matter beyond telling you that you've done goofed. this matter beyond telling you that you've done goofed.
""" """
def __init__(self, msg):
self.msg = msg
def __str__(self): def __init__(self, msg):
return repr(self.msg) self.msg = msg
def __str__(self):
return repr(self.msg)
class AuthError(TwythonError): class AuthError(TwythonError):
""" """
Raised when you try to access a protected resource and it fails due to some issue with Raised when you try to access a protected resource and it fails due to some issue with
your authentication. your authentication.
""" """
def __init__(self, msg):
self.msg = msg
def __str__(self): def __init__(self, msg):
return repr(self.msg) self.msg = msg
def __str__(self):
return repr(self.msg)
class Twython(object): class Twython(object):
def __init__(self, twitter_token = None, twitter_secret = None, oauth_token = None, oauth_token_secret = None, headers=None, callback_url=None, client_args={}): def __init__(self, twitter_token=None, twitter_secret=None, oauth_token=None, oauth_token_secret=None, headers=None,
"""setup(self, oauth_token = None, headers = None) callback_url=None, client_args={}):
"""setup(self, oauth_token = None, headers = None)
Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).
Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).
Parameters:
twitter_token - Given to you when you register your application with Twitter. Parameters:
twitter_secret - Given to you when you register your application with Twitter. twitter_token - Given to you when you register your application with Twitter.
oauth_token - If you've gone through the authentication process and have a token for this user, twitter_secret - Given to you when you register your application with Twitter.
pass it in and it'll be used for all requests going forward. oauth_token - If you've gone through the authentication process and have a token for this user,
oauth_token_secret - see oauth_token; it's the other half. pass it in and it'll be used for all requests going forward.
headers - User agent header, dictionary style ala {'User-Agent': 'Bert'} oauth_token_secret - see oauth_token; it's the other half.
client_args - additional arguments for HTTP client (see httplib2.Http.__init__), e.g. {'timeout': 10.0} headers - User agent header, dictionary style ala {'User-Agent': 'Bert'}
client_args - additional arguments for HTTP client (see httplib2.Http.__init__), e.g. {'timeout': 10.0}
** Note: versioning is not currently used by search.twitter functions; when Twitter moves their junk, it'll be supported.
""" ** Note: versioning is not currently used by search.twitter functions; when Twitter moves their junk, it'll be supported.
# Needed for hitting that there API. """
self.request_token_url = 'http://twitter.com/oauth/request_token' # Needed for hitting that there API.
self.access_token_url = 'http://twitter.com/oauth/access_token' self.request_token_url = 'http://twitter.com/oauth/request_token'
self.authorize_url = 'http://twitter.com/oauth/authorize' self.access_token_url = 'http://twitter.com/oauth/access_token'
self.authenticate_url = 'http://twitter.com/oauth/authenticate' self.authorize_url = 'http://twitter.com/oauth/authorize'
self.twitter_token = twitter_token self.authenticate_url = 'http://twitter.com/oauth/authenticate'
self.twitter_secret = twitter_secret self.twitter_token = twitter_token
self.oauth_token = oauth_token self.twitter_secret = twitter_secret
self.oauth_secret = oauth_token_secret self.oauth_token = oauth_token
self.callback_url = callback_url self.oauth_secret = oauth_token_secret
self.callback_url = callback_url
# If there's headers, set them, otherwise be an embarassing parent for their own good.
self.headers = headers # If there's headers, set them, otherwise be an embarassing parent for their own good.
if self.headers is None: self.headers = headers
self.headers = {'User-agent': 'Twython Python Twitter Library v1.3'} if self.headers is None:
self.headers = {'User-agent': 'Twython Python Twitter Library v1.3'}
consumer = None
token = None consumer = None
token = None
if self.twitter_token is not None and self.twitter_secret is not None:
consumer = oauth.Consumer(self.twitter_token, self.twitter_secret) if self.twitter_token is not None and self.twitter_secret is not None:
consumer = oauth.Consumer(self.twitter_token, self.twitter_secret)
if self.oauth_token is not None and self.oauth_secret is not None:
token = oauth.Token(oauth_token, oauth_token_secret) if self.oauth_token is not None and self.oauth_secret is not None:
token = oauth.Token(oauth_token, oauth_token_secret)
# Filter down through the possibilities here - if they have a token, if they're first stage, etc.
if consumer is not None and token is not None: # Filter down through the possibilities here - if they have a token, if they're first stage, etc.
self.client = oauth.Client(consumer, token, **client_args) if consumer is not None and token is not None:
elif consumer is not None: self.client = oauth.Client(consumer, token, **client_args)
self.client = oauth.Client(consumer, **client_args) elif consumer is not None:
else: self.client = oauth.Client(consumer, **client_args)
# If they don't do authentication, but still want to request unprotected resources, we need an opener. else:
self.client = httplib2.Http(**client_args) # If they don't do authentication, but still want to request unprotected resources, we need an opener.
self.client = httplib2.Http(**client_args)
def __getattr__(self, api_call):
""" def __getattr__(self, api_call):
The most magically awesome block of code you'll see in 2010. """
The most magically awesome block of code you'll see in 2010.
Rather than list out 9 million damn methods for this API, we just keep a table (see above) of
every API endpoint and their corresponding function id for this library. This pretty much gives Rather than list out 9 million damn methods for this API, we just keep a table (see above) of
unlimited flexibility in API support - there's a slight chance of a performance hit here, but if this is every API endpoint and their corresponding function id for this library. This pretty much gives
going to be your bottleneck... well, don't use Python. ;P unlimited flexibility in API support - there's a slight chance of a performance hit here, but if this is
going to be your bottleneck... well, don't use Python. ;P
For those who don't get what's going on here, Python classes have this great feature known as __getattr__().
It's called when an attribute that was called on an object doesn't seem to exist - since it doesn't exist, For those who don't get what's going on here, Python classes have this great feature known as __getattr__().
we can take over and find the API method in our table. We then return a function that downloads and parses It's called when an attribute that was called on an object doesn't seem to exist - since it doesn't exist,
what we're looking for, based on the keywords passed in. we can take over and find the API method in our table. We then return a function that downloads and parses
what we're looking for, based on the keywords passed in.
I'll hate myself for saying this, but this is heavily inspired by Ruby's "method_missing".
""" I'll hate myself for saying this, but this is heavily inspired by Ruby's "method_missing".
def get(self, **kwargs): """
# Go through and replace any mustaches that are in our API url.
fn = api_table[api_call] def get(self, **kwargs):
base = re.sub( # Go through and replace any mustaches that are in our API url.
'\{\{(?P<m>[a-zA-Z_]+)\}\}', fn = api_table[api_call]
lambda m: "%s" % kwargs.get(m.group(1), '1'), # The '1' here catches the API version. Slightly hilarious. base = re.sub(
base_url + fn['url'] '\{\{(?P<m>[a-zA-Z_]+)\}\}',
) lambda m: "%s" % kwargs.get(m.group(1), '1'),
# The '1' here catches the API version. Slightly hilarious.
# Then open and load that shiiit, yo. TODO: check HTTP method and junk, handle errors/authentication base_url + fn['url']
if fn['method'] == 'POST': )
resp, content = self.client.request(base, fn['method'], urllib.urlencode(dict([k, Twython.encode(v)] for k, v in kwargs.items())), headers = self.headers)
else: # Then open and load that shiiit, yo. TODO: check HTTP method and junk, handle errors/authentication
url = base + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in kwargs.iteritems()]) if fn['method'] == 'POST':
resp, content = self.client.request(url, fn['method'], headers = self.headers) resp, content = self.client.request(base, fn['method'], urllib.urlencode(
dict([k, Twython.encode(v)] for k, v in kwargs.items())), headers=self.headers)
return simplejson.loads(content) else:
url = base + "?" + "&".join(["%s=%s" % (key, value) for (key, value) in kwargs.iteritems()])
if api_call in api_table: resp, content = self.client.request(url, fn['method'], headers=self.headers)
return get.__get__(self)
else: return simplejson.loads(content)
raise TwythonError, api_call
if api_call in api_table:
def get_authentication_tokens(self): return get.__get__(self)
""" else:
get_auth_url(self) raise TwythonError, api_call
Returns an authorization URL for a user to hit. def get_authentication_tokens(self):
""" """
callback_url = self.callback_url or 'oob' get_auth_url(self)
request_args = {} Returns an authorization URL for a user to hit.
if OAUTH_LIB_SUPPORTS_CALLBACK: """
request_args['callback_url'] = callback_url callback_url = self.callback_url or 'oob'
resp, content = self.client.request(self.request_token_url, "GET", **request_args) request_args = {}
if OAUTH_LIB_SUPPORTS_CALLBACK:
if resp['status'] != '200': request_args['callback_url'] = callback_url
raise AuthError("Seems something couldn't be verified with your OAuth junk. Error: %s, Message: %s" % (resp['status'], content))
resp, content = self.client.request(self.request_token_url, "GET", **request_args)
try:
request_tokens = dict(urlparse.parse_qsl(content)) if resp['status'] != '200':
except: raise AuthError("Seems something couldn't be verified with your OAuth junk. Error: %s, Message: %s" % (
request_tokens = dict(cgi.parse_qsl(content)) resp['status'], content))
oauth_callback_confirmed = request_tokens.get('oauth_callback_confirmed')=='true' try:
request_tokens = dict(urlparse.parse_qsl(content))
if not OAUTH_LIB_SUPPORTS_CALLBACK and callback_url != 'oob' and oauth_callback_confirmed: except:
import warnings request_tokens = dict(cgi.parse_qsl(content))
warnings.warn("oauth2 library doesn't support OAuth 1.0a type callback, but remote requires it")
oauth_callback_confirmed = False oauth_callback_confirmed = request_tokens.get('oauth_callback_confirmed') == 'true'
auth_url_params = { if not OAUTH_LIB_SUPPORTS_CALLBACK and callback_url != 'oob' and oauth_callback_confirmed:
'oauth_token' : request_tokens['oauth_token'], import warnings
}
warnings.warn("oauth2 library doesn't support OAuth 1.0a type callback, but remote requires it")
# Use old-style callback argument oauth_callback_confirmed = False
if OAUTH_CALLBACK_IN_URL or (callback_url!='oob' and not oauth_callback_confirmed):
auth_url_params['oauth_callback'] = callback_url auth_url_params = {
'oauth_token': request_tokens['oauth_token'],
request_tokens['auth_url'] = self.authenticate_url + '?' + urllib.urlencode(auth_url_params) }
return request_tokens # Use old-style callback argument
if OAUTH_CALLBACK_IN_URL or (callback_url != 'oob' and not oauth_callback_confirmed):
def get_authorized_tokens(self): auth_url_params['oauth_callback'] = callback_url
"""
get_authorized_tokens request_tokens['auth_url'] = self.authenticate_url + '?' + urllib.urlencode(auth_url_params)
Returns authorized tokens after they go through the auth_url phase. return request_tokens
"""
resp, content = self.client.request(self.access_token_url, "GET") def get_authorized_tokens(self):
try: """
return dict(urlparse.parse_qsl(content)) get_authorized_tokens
except:
return dict(cgi.parse_qsl(content)) Returns authorized tokens after they go through the auth_url phase.
"""
# ------------------------------------------------------------------------------------------------------------------------ resp, content = self.client.request(self.access_token_url, "GET")
# The following methods are all different in some manner or require special attention with regards to the Twitter API. try:
# Because of this, we keep them separate from all the other endpoint definitions - ideally this should be change-able, return dict(urlparse.parse_qsl(content))
# but it's not high on the priority list at the moment. except:
# ------------------------------------------------------------------------------------------------------------------------ return dict(cgi.parse_qsl(content))
@staticmethod # ------------------------------------------------------------------------------------------------------------------------
def constructApiURL(base_url, params): # The following methods are all different in some manner or require special attention with regards to the Twitter API.
return base_url + "?" + "&".join(["%s=%s" %(Twython.unicode2utf8(key), urllib.quote_plus(Twython.unicode2utf8(value))) for (key, value) in params.iteritems()]) # Because of this, we keep them separate from all the other endpoint definitions - ideally this should be change-able,
# but it's not high on the priority list at the moment.
@staticmethod # ------------------------------------------------------------------------------------------------------------------------
def shortenURL(url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl"):
"""shortenURL(url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl") @staticmethod
def constructApiURL(base_url, params):
Shortens url specified by url_to_shorten. return base_url + "?" + "&".join(
["%s=%s" % (Twython.unicode2utf8(key), urllib.quote_plus(Twython.unicode2utf8(value))) for (key, value) in
Parameters: params.iteritems()])
url_to_shorten - URL to shorten.
shortener - In case you want to use a url shortening service other than is.gd. @staticmethod
""" def shortenURL(url_to_shorten, shortener="http://is.gd/api.php", query="longurl"):
try: """shortenURL(url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl")
content = urllib2.urlopen(shortener + "?" + urllib.urlencode({query: Twython.unicode2utf8(url_to_shorten)})).read()
return content Shortens url specified by url_to_shorten.
except HTTPError, e:
raise TwythonError("shortenURL() failed with a %s error code." % `e.code`) Parameters:
url_to_shorten - URL to shorten.
def bulkUserLookup(self, ids = None, screen_names = None, version = 1, **kwargs): shortener - In case you want to use a url shortening service other than is.gd.
""" bulkUserLookup(self, ids = None, screen_names = None, version = 1, **kwargs) """
try:
A method to do bulk user lookups against the Twitter API. Arguments (ids (numbers) / screen_names (strings)) should be flat Arrays that content = urllib2.urlopen(
contain their respective data sets. shortener + "?" + urllib.urlencode({query: Twython.unicode2utf8(url_to_shorten)})).read()
return content
Statuses for the users in question will be returned inline if they exist. Requires authentication! except HTTPError, e:
""" raise TwythonError("shortenURL() failed with a %s error code." % `e.code`)
if ids:
kwargs['user_id'] = ','.join(map(str, ids)) def bulkUserLookup(self, ids=None, screen_names=None, version=1, **kwargs):
if screen_names: """ bulkUserLookup(self, ids = None, screen_names = None, version = 1, **kwargs)
kwargs['screen_name'] = ','.join(screen_names)
A method to do bulk user lookups against the Twitter API. Arguments (ids (numbers) / screen_names (strings)) should be flat Arrays that
lookupURL = Twython.constructApiURL("http://api.twitter.com/%d/users/lookup.json" % version, kwargs) contain their respective data sets.
try:
resp, content = self.client.request(lookupURL, "POST", headers = self.headers) Statuses for the users in question will be returned inline if they exist. Requires authentication!
return simplejson.loads(content) """
except HTTPError, e: if ids:
raise TwythonError("bulkUserLookup() failed with a %s error code." % `e.code`, e.code) kwargs['user_id'] = ','.join(map(str, ids))
if screen_names:
def searchTwitter(self, **kwargs): kwargs['screen_name'] = ','.join(screen_names)
"""searchTwitter(search_query, **kwargs)
lookupURL = Twython.constructApiURL("http://api.twitter.com/%d/users/lookup.json" % version, kwargs)
Returns tweets that match a specified query. try:
resp, content = self.client.request(lookupURL, "POST", headers=self.headers)
Parameters: return simplejson.loads(content)
See the documentation at http://dev.twitter.com/doc/get/search. Pass in the API supported arguments as named parameters. except HTTPError, e:
raise TwythonError("bulkUserLookup() failed with a %s error code." % `e.code`, e.code)
e.g x.searchTwitter(q="jjndf", page="2")
""" def searchTwitter(self, **kwargs):
searchURL = Twython.constructApiURL("http://search.twitter.com/search.json", kwargs) """searchTwitter(search_query, **kwargs)
try:
resp, content = self.client.request(searchURL, "GET", headers = self.headers) Returns tweets that match a specified query.
return simplejson.loads(content)
except HTTPError, e: Parameters:
raise TwythonError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code) See the documentation at http://dev.twitter.com/doc/get/search. Pass in the API supported arguments as named parameters.
def searchTwitterGen(self, search_query, **kwargs): e.g x.searchTwitter(q="jjndf", page="2")
"""searchTwitterGen(search_query, **kwargs) """
searchURL = Twython.constructApiURL("http://search.twitter.com/search.json", kwargs)
Returns a generator of tweets that match a specified query. try:
resp, content = self.client.request(searchURL, "GET", headers=self.headers)
Parameters: return simplejson.loads(content)
See the documentation at http://dev.twitter.com/doc/get/search. Pass in the API supported arguments as named parameters. except HTTPError, e:
raise TwythonError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code)
e.g x.searchTwitter(q="jjndf", page="2")
""" def searchTwitterGen(self, search_query, **kwargs):
searchURL = Twython.constructApiURL("http://search.twitter.com/search.json?q=%s" % Twython.unicode2utf8(search_query), kwargs) """searchTwitterGen(search_query, **kwargs)
try:
resp, content = self.client.request(searchURL, "GET", headers = self.headers) Returns a generator of tweets that match a specified query.
data = simplejson.loads(content)
except HTTPError, e: Parameters:
raise TwythonError("searchTwitterGen() failed with a %s error code." % `e.code`, e.code) See the documentation at http://dev.twitter.com/doc/get/search. Pass in the API supported arguments as named parameters.
if not data['results']: e.g x.searchTwitter(q="jjndf", page="2")
raise StopIteration """
searchURL = Twython.constructApiURL(
for tweet in data['results']: "http://search.twitter.com/search.json?q=%s" % Twython.unicode2utf8(search_query), kwargs)
yield tweet try:
resp, content = self.client.request(searchURL, "GET", headers=self.headers)
if 'page' not in kwargs: data = simplejson.loads(content)
kwargs['page'] = 2 except HTTPError, e:
else: raise TwythonError("searchTwitterGen() failed with a %s error code." % `e.code`, e.code)
kwargs['page'] += 1
if not data['results']:
for tweet in self.searchTwitterGen(search_query, **kwargs): raise StopIteration
yield tweet
for tweet in data['results']:
def isListMember(self, list_id, id, username, version = 1): yield tweet
""" isListMember(self, list_id, id, version)
if 'page' not in kwargs:
Check if a specified user (id) is a member of the list in question (list_id). kwargs['page'] = 2
else:
**Note: This method may not work for private/protected lists, unless you're authenticated and have access to those lists. kwargs['page'] += 1
Parameters: for tweet in self.searchTwitterGen(search_query, **kwargs):
list_id - Required. The slug of the list to check against. yield tweet
id - Required. The ID of the user being checked in the list.
username - User who owns the list you're checking against (username) def isListMember(self, list_id, id, username, version=1):
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc. """ isListMember(self, list_id, id, version)
"""
try: Check if a specified user (id) is a member of the list in question (list_id).
resp, content = self.client.request("http://api.twitter.com/%d/%s/%s/members/%s.json" % (version, username, list_id, `id`), headers = self.headers)
return simplejson.loads(content) **Note: This method may not work for private/protected lists, unless you're authenticated and have access to those lists.
except HTTPError, e:
raise TwythonError("isListMember() failed with a %d error code." % e.code, e.code) Parameters:
list_id - Required. The slug of the list to check against.
def isListSubscriber(self, username, list_id, id, version = 1): id - Required. The ID of the user being checked in the list.
""" isListSubscriber(self, list_id, id, version) username - User who owns the list you're checking against (username)
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
Check if a specified user (id) is a subscriber of the list in question (list_id). """
try:
**Note: This method may not work for private/protected lists, unless you're authenticated and have access to those lists. resp, content = self.client.request(
"http://api.twitter.com/%d/%s/%s/members/%s.json" % (version, username, list_id, `id`),
Parameters: headers=self.headers)
list_id - Required. The slug of the list to check against. return simplejson.loads(content)
id - Required. The ID of the user being checked in the list. except HTTPError, e:
username - Required. The username of the owner of the list that you're seeing if someone is subscribed to. raise TwythonError("isListMember() failed with a %d error code." % e.code, e.code)
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
""" def isListSubscriber(self, username, list_id, id, version=1):
try: """ isListSubscriber(self, list_id, id, version)
resp, content = self.client.request("http://api.twitter.com/%d/%s/%s/following/%s.json" % (version, username, list_id, `id`), headers = self.headers)
return simplejson.loads(content) Check if a specified user (id) is a subscriber of the list in question (list_id).
except HTTPError, e:
raise TwythonError("isListMember() failed with a %d error code." % e.code, e.code) **Note: This method may not work for private/protected lists, unless you're authenticated and have access to those lists.
# The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set. Parameters:
def updateProfileBackgroundImage(self, filename, tile="true", version = 1): list_id - Required. The slug of the list to check against.
""" updateProfileBackgroundImage(filename, tile="true") id - Required. The ID of the user being checked in the list.
username - Required. The username of the owner of the list that you're seeing if someone is subscribed to.
Updates the authenticating user's profile background image. version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
Parameters: try:
image - Required. Must be a valid GIF, JPG, or PNG image of less than 800 kilobytes in size. Images with width larger than 2048 pixels will be forceably scaled down. resp, content = self.client.request(
tile - Optional (defaults to true). If set to true the background image will be displayed tiled. The image will not be tiled otherwise. "http://api.twitter.com/%d/%s/%s/following/%s.json" % (version, username, list_id, `id`),
** Note: It's sad, but when using this method, pass the tile value as a string, e.g tile="false" headers=self.headers)
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc. return simplejson.loads(content)
""" except HTTPError, e:
try: raise TwythonError("isListMember() failed with a %d error code." % e.code, e.code)
files = [("image", filename, open(filename, 'rb').read())]
fields = [] # The following methods are apart from the other Account methods, because they rely on a whole multipart-data posting function set.
content_type, body = Twython.encode_multipart_formdata(fields, files) def updateProfileBackgroundImage(self, filename, tile="true", version=1):
headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} """ updateProfileBackgroundImage(filename, tile="true")
r = urllib2.Request("http://api.twitter.com/%d/account/update_profile_background_image.json?tile=%s" % (version, tile), body, headers)
return urllib2.urlopen(r).read() Updates the authenticating user's profile background image.
except HTTPError, e:
raise TwythonError("updateProfileBackgroundImage() failed with a %d error code." % e.code, e.code) Parameters:
image - Required. Must be a valid GIF, JPG, or PNG image of less than 800 kilobytes in size. Images with width larger than 2048 pixels will be forceably scaled down.
def updateProfileImage(self, filename, version = 1): tile - Optional (defaults to true). If set to true the background image will be displayed tiled. The image will not be tiled otherwise.
""" updateProfileImage(filename) ** Note: It's sad, but when using this method, pass the tile value as a string, e.g tile="false"
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
Updates the authenticating user's profile image (avatar). """
try:
Parameters: files = [("image", filename, open(filename, 'rb').read())]
image - Required. Must be a valid GIF, JPG, or PNG image of less than 700 kilobytes in size. Images with width larger than 500 pixels will be scaled down. fields = []
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc. content_type, body = Twython.encode_multipart_formdata(fields, files)
""" headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
try: r = urllib2.Request(
files = [("image", filename, open(filename, 'rb').read())] "http://api.twitter.com/%d/account/update_profile_background_image.json?tile=%s" % (version, tile), body
fields = [] , headers)
content_type, body = Twython.encode_multipart_formdata(fields, files) return urllib2.urlopen(r).read()
headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} except HTTPError, e:
r = urllib2.Request("http://api.twitter.com/%d/account/update_profile_image.json" % version, body, headers) raise TwythonError("updateProfileBackgroundImage() failed with a %d error code." % e.code, e.code)
return urllib2.urlopen(r).read()
except HTTPError, e: def updateProfileImage(self, filename, version=1):
raise TwythonError("updateProfileImage() failed with a %d error code." % e.code, e.code) """ updateProfileImage(filename)
def getProfileImageUrl(self, username, size=None, version=1): Updates the authenticating user's profile image (avatar).
""" getProfileImageUrl(username)
Parameters:
Gets the URL for the user's profile image. image - Required. Must be a valid GIF, JPG, or PNG image of less than 700 kilobytes in size. Images with width larger than 500 pixels will be scaled down.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
Parameters: """
username - Required. User name of the user you want the image url of. try:
size - Optional. Image size. Valid options include 'normal', 'mini' and 'bigger'. Defaults to 'normal' if not given. files = [("image", filename, open(filename, 'rb').read())]
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc. fields = []
""" content_type, body = Twython.encode_multipart_formdata(fields, files)
url = "http://api.twitter.com/%s/users/profile_image/%s.json" % (version, username) headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
if size: r = urllib2.Request("http://api.twitter.com/%d/account/update_profile_image.json" % version, body, headers)
url = self.constructApiURL(url, {'size':size}) return urllib2.urlopen(r).read()
except HTTPError, e:
client = httplib2.Http() raise TwythonError("updateProfileImage() failed with a %d error code." % e.code, e.code)
client.follow_redirects = False
resp, content = client.request(url, 'GET') def getProfileImageUrl(self, username, size=None, version=1):
""" getProfileImageUrl(username)
if resp.status in (301,302,303,307):
return resp['location'] Gets the URL for the user's profile image.
elif resp.status == 200:
return simplejson.loads(content) Parameters:
username - Required. User name of the user you want the image url of.
raise TwythonError("getProfileImageUrl() failed with a %d error code." % resp.status, resp.status) size - Optional. Image size. Valid options include 'normal', 'mini' and 'bigger'. Defaults to 'normal' if not given.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
@staticmethod """
def encode_multipart_formdata(fields, files): url = "http://api.twitter.com/%s/users/profile_image/%s.json" % (version, username)
BOUNDARY = mimetools.choose_boundary() if size:
CRLF = '\r\n' url = self.constructApiURL(url, {'size': size})
L = []
for (key, value) in fields: client = httplib2.Http()
L.append('--' + BOUNDARY) client.follow_redirects = False
L.append('Content-Disposition: form-data; name="%s"' % key) resp, content = client.request(url, 'GET')
L.append('')
L.append(value) if resp.status in (301, 302, 303, 307):
for (key, filename, value) in files: return resp['location']
L.append('--' + BOUNDARY) elif resp.status == 200:
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) return simplejson.loads(content)
L.append('Content-Type: %s' % mimetypes.guess_type(filename)[0] or 'application/octet-stream')
L.append('') raise TwythonError("getProfileImageUrl() failed with a %d error code." % resp.status, resp.status)
L.append(value)
L.append('--' + BOUNDARY + '--') def getUserProfile(self, **kwargs):
L.append('') """getUserProfile(screen_name, **kwargs)
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY Returns user profile that match a specified screen_name.
return content_type, body
Parameters:
@staticmethod See the documentation at https://dev.twitter.com/docs/api/1/get/users/show. Pass in the API supported arguments as named parameters.
def unicode2utf8(text):
try: e.g x.searchTwitter(screen_name="lacion"[, user_id=123[, include_entities=True]])
if isinstance(text, unicode): """
text = text.encode('utf-8') userShowURL = Twython.constructApiURL("http://api.twitter.com/version/users/show.json", kwargs)
except: try:
pass resp, content = self.client.request(searchURL, "GET", headers=self.headers)
return text return simplejson.loads(content)
except HTTPError, e:
@staticmethod raise TwythonError("getUserProfile() failed with a %s error code." % `e.code`, e.code)
def encode(text):
if isinstance(text, (str,unicode)): @staticmethod
return Twython.unicode2utf8(text) def encode_multipart_formdata(fields, files):
return str(text) BOUNDARY = mimetools.choose_boundary()
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % mimetypes.guess_type(filename)[0] or 'application/octet-stream')
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
@staticmethod
def unicode2utf8(text):
try:
if isinstance(text, unicode):
text = text.encode('utf-8')
except:
pass
return text
@staticmethod
def encode(text):
if isinstance(text, (str, unicode)):
return Twython.unicode2utf8(text)
return str(text)