desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Set the subscriber_count of this list. Args: subscriber_count: The subscriber_count of this list.'
def SetSubscriber_count(self, subscriber_count):
self._subscriber_count = subscriber_count
'Get the following status of this list. Returns: The following status of this list'
def GetFollowing(self):
return self._following
'Set the following status of this list. Args: following: The following of this list.'
def SetFollowing(self, following):
self._following = following
'Get the user of this list. Returns: The owner of this list'
def GetUser(self):
return self._user
'Set the user of this list. Args: user: The owner of this list.'
def SetUser(self, user):
self._user = user
'A string representation of this twitter.List instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.List instance.'
def __str__(self):
return self.AsJsonString()
'A JSON string representation of this twitter.List instance. Returns: A JSON string representation of this twitter.List instance'
def AsJsonString(self):
return simplejson.dumps(self.AsDict(), sort_keys=True)
'A dict representation of this twitter.List instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.List instance'
def AsDict(self):
data = {} if self.id: data['id'] = self.id if self.name: data['name'] = self.name if self.slug: data['slug'] = self.slug if self.description: data['description'] = self.description if self.full_name: data['full_name'] = self.full_name if self.mode: data['mode'] = self.mode if self.uri: data['uri'] = self.uri if (self.member_count is not None): data['member_count'] = self.member_count if (self.subscriber_count is not None): data['subscriber_count'] = self.subscriber_count if (self.following is not None): data['following'] = self.following if (self.user is not None): data['user'] = self.user.AsDict() return data
'Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.List instance'
@staticmethod def NewFromJsonDict(data):
if ('user' in data): user = User.NewFromJsonDict(data['user']) else: user = None return List(id=data.get('id', None), name=data.get('name', None), slug=data.get('slug', None), description=data.get('description', None), full_name=data.get('full_name', None), mode=data.get('mode', None), uri=data.get('uri', None), member_count=data.get('member_count', None), subscriber_count=data.get('subscriber_count', None), following=data.get('following', None), user=user)
'An object to hold a Twitter direct message. This class is normally instantiated by the twitter.Api class and returned in a sequence. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" Args: id: The unique id of this direct message. [Optional] created_at: The time this direct message was posted. [Optional] sender_id: The id of the twitter user that sent this message. [Optional] sender_screen_name: The name of the twitter user that sent this message. [Optional] recipient_id: The id of the twitter that received this message. [Optional] recipient_screen_name: The name of the twitter that received this message. [Optional] text: The text of this direct message. [Optional]'
def __init__(self, id=None, created_at=None, sender_id=None, sender_screen_name=None, recipient_id=None, recipient_screen_name=None, text=None):
self.id = id self.created_at = created_at self.sender_id = sender_id self.sender_screen_name = sender_screen_name self.recipient_id = recipient_id self.recipient_screen_name = recipient_screen_name self.text = text
'Get the unique id of this direct message. Returns: The unique id of this direct message'
def GetId(self):
return self._id
'Set the unique id of this direct message. Args: id: The unique id of this direct message'
def SetId(self, id):
self._id = id
'Get the time this direct message was posted. Returns: The time this direct message was posted'
def GetCreatedAt(self):
return self._created_at
'Set the time this direct message was posted. Args: created_at: The time this direct message was created'
def SetCreatedAt(self, created_at):
self._created_at = created_at
'Get the time this direct message was posted, in seconds since the epoch. Returns: The time this direct message was posted, in seconds since the epoch.'
def GetCreatedAtInSeconds(self):
return calendar.timegm(rfc822.parsedate(self.created_at))
'Get the unique sender id of this direct message. Returns: The unique sender id of this direct message'
def GetSenderId(self):
return self._sender_id
'Set the unique sender id of this direct message. Args: sender_id: The unique sender id of this direct message'
def SetSenderId(self, sender_id):
self._sender_id = sender_id
'Get the unique sender screen name of this direct message. Returns: The unique sender screen name of this direct message'
def GetSenderScreenName(self):
return self._sender_screen_name
'Set the unique sender screen name of this direct message. Args: sender_screen_name: The unique sender screen name of this direct message'
def SetSenderScreenName(self, sender_screen_name):
self._sender_screen_name = sender_screen_name
'Get the unique recipient id of this direct message. Returns: The unique recipient id of this direct message'
def GetRecipientId(self):
return self._recipient_id
'Set the unique recipient id of this direct message. Args: recipient_id: The unique recipient id of this direct message'
def SetRecipientId(self, recipient_id):
self._recipient_id = recipient_id
'Get the unique recipient screen name of this direct message. Returns: The unique recipient screen name of this direct message'
def GetRecipientScreenName(self):
return self._recipient_screen_name
'Set the unique recipient screen name of this direct message. Args: recipient_screen_name: The unique recipient screen name of this direct message'
def SetRecipientScreenName(self, recipient_screen_name):
self._recipient_screen_name = recipient_screen_name
'Get the text of this direct message. Returns: The text of this direct message.'
def GetText(self):
return self._text
'Set the text of this direct message. Args: text: The text of this direct message'
def SetText(self, text):
self._text = text
'A string representation of this twitter.DirectMessage instance. The return value is the same as the JSON string representation. Returns: A string representation of this twitter.DirectMessage instance.'
def __str__(self):
return self.AsJsonString()
'A JSON string representation of this twitter.DirectMessage instance. Returns: A JSON string representation of this twitter.DirectMessage instance'
def AsJsonString(self):
return simplejson.dumps(self.AsDict(), sort_keys=True)
'A dict representation of this twitter.DirectMessage instance. The return value uses the same key names as the JSON representation. Return: A dict representing this twitter.DirectMessage instance'
def AsDict(self):
data = {} if self.id: data['id'] = self.id if self.created_at: data['created_at'] = self.created_at if self.sender_id: data['sender_id'] = self.sender_id if self.sender_screen_name: data['sender_screen_name'] = self.sender_screen_name if self.recipient_id: data['recipient_id'] = self.recipient_id if self.recipient_screen_name: data['recipient_screen_name'] = self.recipient_screen_name if self.text: data['text'] = self.text return data
'Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.DirectMessage instance'
@staticmethod def NewFromJsonDict(data):
return DirectMessage(created_at=data.get('created_at', None), recipient_id=data.get('recipient_id', None), sender_id=data.get('sender_id', None), text=data.get('text', None), sender_screen_name=data.get('sender_screen_name', None), id=data.get('id', None), recipient_screen_name=data.get('recipient_screen_name', None))
'Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Hashtag instance'
@staticmethod def NewFromJsonDict(data):
return Hashtag(text=data.get('text', None))
'Create a new instance based on a JSON dict Args: data: A JSON dict timestamp: Gets set as the timestamp property of the new object Returns: A twitter.Trend object'
@staticmethod def NewFromJsonDict(data, timestamp=None):
return Trend(name=data.get('name', None), query=data.get('query', None), url=data.get('url', None), timestamp=timestamp)
'Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.Url instance'
@staticmethod def NewFromJsonDict(data):
return Url(url=data.get('url', None), expanded_url=data.get('expanded_url', None))
'Instantiate a new twitter.Api object. Args: consumer_key: Your Twitter user\'s consumer_key. consumer_secret: Your Twitter user\'s consumer_secret. access_token_key: The oAuth access token key value you retrieved from running get_access_token.py. access_token_secret: The oAuth access token\'s secret, also retrieved from the get_access_token.py run. input_encoding: The encoding used to encode input strings. [Optional] request_header: A dictionary of additional HTTP request headers. [Optional] cache: The cache instance to use. Defaults to DEFAULT_CACHE. Use None to disable caching. [Optional] shortner: The shortner instance to use. Defaults to None. See shorten_url.py for an example shortner. [Optional] base_url: The base URL to use to contact the Twitter API. Defaults to https://api.twitter.com. [Optional] use_gzip_compression: Set to True to tell enable gzip compression for any call made to Twitter. Defaults to False. [Optional] debugHTTP: Set to True to enable debug output from urllib2 when performing any HTTP requests. Defaults to False. [Optional]'
def __init__(self, consumer_key=None, consumer_secret=None, access_token_key=None, access_token_secret=None, input_encoding=None, request_headers=None, cache=DEFAULT_CACHE, shortner=None, base_url=None, use_gzip_compression=False, debugHTTP=False):
self.SetCache(cache) self._urllib = urllib2 self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT self._input_encoding = input_encoding self._use_gzip = use_gzip_compression self._debugHTTP = debugHTTP self._oauth_consumer = None self._shortlink_size = 19 self._InitializeRequestHeaders(request_headers) self._InitializeUserAgent() self._InitializeDefaultParameters() if (base_url is None): self.base_url = 'https://api.twitter.com/1.1' else: self.base_url = base_url if ((consumer_key is not None) and ((access_token_key is None) or (access_token_secret is None))): print >>sys.stderr, 'Twitter now requires an oAuth Access Token for API calls.' print >>sys.stderr, 'If your using this library from a command line utility, please' print >>sys.stderr, 'run the the included get_access_token.py tool to generate one.' raise TwitterError('Twitter requires oAuth Access Token for all API access') self.SetCredentials(consumer_key, consumer_secret, access_token_key, access_token_secret)
'Set the consumer_key and consumer_secret for this instance Args: consumer_key: The consumer_key of the twitter account. consumer_secret: The consumer_secret for the twitter account. access_token_key: The oAuth access token key value you retrieved from running get_access_token.py. access_token_secret: The oAuth access token\'s secret, also retrieved from the get_access_token.py run.'
def SetCredentials(self, consumer_key, consumer_secret, access_token_key=None, access_token_secret=None):
self._consumer_key = consumer_key self._consumer_secret = consumer_secret self._access_token_key = access_token_key self._access_token_secret = access_token_secret self._oauth_consumer = None if ((consumer_key is not None) and (consumer_secret is not None) and (access_token_key is not None) and (access_token_secret is not None)): self._signature_method_plaintext = oauth.SignatureMethod_PLAINTEXT() self._signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() self._oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret) self._oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
'Clear the any credentials for this instance'
def ClearCredentials(self):
self._consumer_key = None self._consumer_secret = None self._access_token_key = None self._access_token_secret = None self._oauth_consumer = None
'Return twitter search results for a given term. Args: term: Term to search by. Optional if you include geocode. since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) or equal to the specified ID. [Optional] until: Returns tweets generated before the given date. Date should be formatted as YYYY-MM-DD. [Optional] geocode: Geolocation information in the form (latitude, longitude, radius) [Optional] count: Number of results to return. Default is 15 [Optional] lang: Language for results as ISO 639-1 code. Default is None (all languages) [Optional] locale: Language of the search query. Currently only \'ja\' is effective. This is intended for language-specific consumers and the default should work in the majority of cases. result_type: Type of result which should be returned. Default is "mixed". Other valid options are "recent" and "popular". [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discrete structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.Status instances, one for each message containing the term'
def GetSearch(self, term=None, geocode=None, since_id=None, max_id=None, until=None, count=15, lang=None, locale=None, result_type='mixed', include_entities=None):
parameters = {} if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError('since_id must be an integer') if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError('max_id must be an integer') if until: parameters['until'] = until if lang: parameters['lang'] = lang if locale: parameters['locale'] = locale if ((term is None) and (geocode is None)): return [] if (term is not None): parameters['q'] = term if (geocode is not None): parameters['geocode'] = ','.join(map(str, geocode)) if include_entities: parameters['include_entities'] = 1 try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') if (result_type in ['mixed', 'popular', 'recent']): parameters['result_type'] = result_type url = ('%s/search/tweets.json' % self.base_url) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data['statuses']]
'Return twitter user search results for a given term. Args: term: Term to search by. page: Page of results to return. Default is 1 [Optional] count: Number of results to return. Default is 20 [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discrete structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.User instances, one for each message containing the term'
def GetUsersSearch(self, term=None, page=1, count=20, include_entities=None):
parameters = {} if (term is not None): parameters['q'] = term if include_entities: parameters['include_entities'] = 1 try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') url = ('%s/users/search.json' % self.base_url) json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [User.NewFromJsonDict(x) for x in data]
'Get the current top trending topics (global) Args: exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains a trend.'
def GetTrendsCurrent(self, exclude=None):
return self.GetTrendsWoeid(id=1, exclude=exclude)
'Return the top 10 trending topics for a specific WOEID, if trending information is available for it. Args: woeid: the Yahoo! Where On Earth ID for a location. exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains a trend.'
def GetTrendsWoeid(self, id, exclude=None):
url = ('%s/trends/place.json' % self.base_url) parameters = {'id': id} if exclude: parameters['exclude'] = exclude json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] timestamp = data[0]['as_of'] for trend in data[0]['trends']: trends.append(Trend.NewFromJsonDict(trend, timestamp=timestamp)) return trends
'Fetch a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow. The home timeline is central to how most users interact with the Twitter service. The twitter.Api instance must be authenticated. Args: count: Specifies the number of statuses to retrieve. May not be greater than 200. Defaults to 20. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. [Optional] trim_user: When True, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. [Optional] exclude_replies: This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. [Optional] contributor_details: This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included. [Optional] include_entities: The entities node will be disincluded when set to false. This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A sequence of twitter.Status instances, one for each message'
def GetHomeTimeline(self, count=None, since_id=None, max_id=None, trim_user=False, exclude_replies=False, contributor_details=False, include_entities=True):
url = ('%s/statuses/home_timeline.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('API must be authenticated.') parameters = {} if (count is not None): try: if (int(count) > 200): raise TwitterError("'count' may not be greater than 200") except ValueError: raise TwitterError("'count' must be an integer") parameters['count'] = count if since_id: try: parameters['since_id'] = long(since_id) except ValueError: raise TwitterError("'since_id' must be an integer") if max_id: try: parameters['max_id'] = long(max_id) except ValueError: raise TwitterError("'max_id' must be an integer") if trim_user: parameters['trim_user'] = 1 if exclude_replies: parameters['exclude_replies'] = 1 if contributor_details: parameters['contributor_details'] = 1 if (not include_entities): parameters['include_entities'] = 'false' json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data]
'Fetch the sequence of public Status messages for a single user. The twitter.Api instance must be authenticated if the user is private. Args: user_id: Specifies the ID of the user for whom to return the user_timeline. Helpful for disambiguating when a valid user ID is also a valid screen name. [Optional] screen_name: Specifies the screen name of the user for whom to return the user_timeline. Helpful for disambiguating when a valid screen name is also a user ID. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) or equal to the specified ID. [Optional] count: Specifies the number of statuses to retrieve. May not be greater than 200. [Optional] include_rts: If True, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets. [Optional] trim_user: If True, statuses will only contain the numerical user ID only. Otherwise a full user object will be returned for each status. [Optional] exclude_replies: If True, this will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. This parameter is only supported for JSON and XML responses. [Optional] Returns: A sequence of Status instances, one for each message up to count'
def GetUserTimeline(self, user_id=None, screen_name=None, since_id=None, max_id=None, count=None, include_rts=None, trim_user=None, exclude_replies=None):
parameters = {} url = ('%s/statuses/user_timeline.json' % self.base_url) if user_id: parameters['user_id'] = user_id elif screen_name: parameters['screen_name'] = screen_name if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError('since_id must be an integer') if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError('max_id must be an integer') if count: try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') if include_rts: parameters['include_rts'] = 1 if trim_user: parameters['trim_user'] = 1 if exclude_replies: parameters['exclude_replies'] = 1 json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data]
'Returns a single status message, specified by the id parameter. The twitter.Api instance must be authenticated. Args: id: The numeric ID of the status you are trying to retrieve. trim_user: When set to True, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. [Optional] include_my_retweet: When set to True, any Tweets returned that have been retweeted by the authenticating user will include an additional current_user_retweet node, containing the ID of the source status for the retweet. [Optional] include_entities: If False, the entities node will be disincluded. This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. [Optional] Returns: A twitter.Status instance representing that status message'
def GetStatus(self, id, trim_user=False, include_my_retweet=True, include_entities=True):
url = ('%s/statuses/show.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('API must be authenticated.') parameters = {} try: parameters['id'] = long(id) except ValueError: raise TwitterError("'id' must be an integer.") if trim_user: parameters['trim_user'] = 1 if include_my_retweet: parameters['include_my_retweet'] = 1 if (not include_entities): parameters['include_entities'] = 'none' json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data)
'Destroys the status specified by the required ID parameter. The twitter.Api instance must be authenticated and the authenticating user must be the author of the specified status. Args: id: The numerical ID of the status you\'re trying to destroy. Returns: A twitter.Status instance representing the destroyed status message'
def DestroyStatus(self, id, trim_user=False):
if (not self._oauth_consumer): raise TwitterError('API must be authenticated.') try: post_data = {'id': long(id)} except: raise TwitterError('id must be an integer') url = ('%s/statuses/destroy/%s.json' % (self.base_url, id)) if trim_user: post_data['trim_user'] = 1 json = self._FetchUrl(url, post_data=post_data) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data)
'Post a twitter status message from the authenticated user. The twitter.Api instance must be authenticated. https://dev.twitter.com/docs/api/1.1/post/statuses/update Args: status: The message text to be posted. Must be less than or equal to 140 characters. in_reply_to_status_id: The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored. [Optional] latitude: Latitude coordinate of the tweet in degrees. Will only work in conjunction with longitude argument. Both longitude and latitude will be ignored by twitter if the user has a false geo_enabled setting. [Optional] longitude: Longitude coordinate of the tweet in degrees. Will only work in conjunction with latitude argument. Both longitude and latitude will be ignored by twitter if the user has a false geo_enabled setting. [Optional] place_id: A place in the world. These IDs can be retrieved from GET geo/reverse_geocode. [Optional] display_coordinates: Whether or not to put a pin on the exact coordinates a tweet has been sent from. [Optional] trim_user: If True the returned payload will only contain the user IDs, otherwise the payload will contain the full user data item. [Optional] Returns: A twitter.Status instance representing the message posted.'
def PostUpdate(self, status, in_reply_to_status_id=None, latitude=None, longitude=None, place_id=None, display_coordinates=False, trim_user=False):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') url = ('%s/statuses/update.json' % self.base_url) if (isinstance(status, unicode) or (self._input_encoding is None)): u_status = status else: u_status = unicode(status, self._input_encoding) data = {'status': status} if in_reply_to_status_id: data['in_reply_to_status_id'] = in_reply_to_status_id if ((latitude is not None) and (longitude is not None)): data['lat'] = str(latitude) data['long'] = str(longitude) if (place_id is not None): data['place_id'] = str(place_id) if display_coordinates: data['display_coordinates'] = 'true' if trim_user: data['trim_user'] = 'true' json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data)
'Post one or more twitter status messages from the authenticated user. Unlike api.PostUpdate, this method will post multiple status updates if the message is longer than 140 characters. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. May be longer than 140 characters. continuation: The character string, if any, to be appended to all but the last message. Note that Twitter strips trailing \'...\' strings from messages. Consider using the unicode \u2026 character (horizontal ellipsis) instead. [Defaults to None] **kwargs: See api.PostUpdate for a list of accepted parameters. Returns: A of list twitter.Status instance representing the messages posted.'
def PostUpdates(self, status, continuation=None, **kwargs):
results = list() if (continuation is None): continuation = '' line_length = (CHARACTER_LIMIT - len(continuation)) lines = textwrap.wrap(status, line_length) for line in lines[0:(-1)]: results.append(self.PostUpdate((line + continuation), **kwargs)) results.append(self.PostUpdate(lines[(-1)], **kwargs)) return results
'Retweet a tweet with the Retweet API. The twitter.Api instance must be authenticated. Args: original_id: The numerical id of the tweet that will be retweeted trim_user: If True the returned payload will only contain the user IDs, otherwise the payload will contain the full user data item. [Optional] Returns: A twitter.Status instance representing the original tweet with retweet details embedded.'
def PostRetweet(self, original_id, trim_user=False):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') try: if (int(original_id) <= 0): raise TwitterError("'original_id' must be a positive number") except ValueError: raise TwitterError("'original_id' must be an integer") url = ('%s/statuses/retweet/%s.json' % (self.base_url, original_id)) data = {'id': original_id} if trim_user: data['trim_user'] = 'true' json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data)
'Fetch the sequence of retweets made by the authenticated user. The twitter.Api instance must be authenticated. Args: count: The number of status messages to retrieve. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. [Optional] trim_user: If True the returned payload will only contain the user IDs, otherwise the payload will contain the full user data item. [Optional] Returns: A sequence of twitter.Status instances, one for each message up to count'
def GetUserRetweets(self, count=None, since_id=None, max_id=None, trim_user=False):
return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user, exclude_replies=True, include_rts=True)
'Get a sequence of status messages representing the 20 most recent replies (status updates prefixed with @twitterID) to the authenticating user. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. [Optional] trim_user: If True the returned payload will only contain the user IDs, otherwise the payload will contain the full user data item. [Optional] Returns: A sequence of twitter.Status instances, one for each reply to the user.'
def GetReplies(self, since_id=None, count=None, max_id=None, trim_user=False):
return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user, exclude_replies=False, include_rts=False)
'Returns up to 100 of the first retweets of the tweet identified by statusid Args: statusid: The ID of the tweet for which retweets should be searched for count: The number of status messages to retrieve. [Optional] trim_user: If True the returned payload will only contain the user IDs, otherwise the payload will contain the full user data item. [Optional] Returns: A list of twitter.Status instances, which are retweets of statusid'
def GetRetweets(self, statusid, count=None, trim_user=False):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instsance must be authenticated.') url = ('%s/statuses/retweets/%s.json' % (self.base_url, statusid)) parameters = {} if trim_user: parameters['trim_user'] = 'true' if count: try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(s) for s in data]
'Returns up to 100 of the most recent tweets of the user that have been retweeted by others. Args: count: The number of retweets to retrieve, up to 100. If omitted, 20 is assumed. since_id: Returns results with an ID greater than (newer than) this ID. max_id: Returns results with an ID less than or equal to this ID. trim_user: When True, the user object for each tweet will only be an ID. include_entities: When True, the tweet entities will be included. include_user_entities: When True, the user entities will be included.'
def GetRetweetsOfMe(self, count=None, since_id=None, max_id=None, trim_user=False, include_entities=True, include_user_entities=True):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') url = ('%s/statuses/retweets_of_me.json' % self.base_url) parameters = {} if (count is not None): try: if (int(count) > 100): raise TwitterError("'count' may not be greater than 100") except ValueError: raise TwitterError("'count' must be an integer") if count: parameters['count'] = count if since_id: parameters['since_id'] = since_id if max_id: parameters['max_id'] = max_id if trim_user: parameters['trim_user'] = trim_user if (not include_entities): parameters['include_entities'] = include_entities if (not include_user_entities): parameters['include_user_entities'] = include_user_entities json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(s) for s in data]
'Fetch the sequence of twitter.User instances, one for each friend. The twitter.Api instance must be authenticated. Args: user_id: The twitter id of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [Optional] screen_name: The twitter name of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [Optional] cursor: Should be set to -1 for the initial call and then is used to control what result page Twitter returns [Optional(ish)] skip_status: If True the statuses will not be returned in the user items. [Optional] include_user_entities: When True, the user entities will be included. Returns: A sequence of twitter.User instances, one for each friend'
def GetFriends(self, user_id=None, screen_name=None, cursor=(-1), skip_status=False, include_user_entities=False):
if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') url = ('%s/friends/list.json' % self.base_url) result = [] parameters = {} if (user_id is not None): parameters['user_id'] = user_id if (screen_name is not None): parameters['screen_name'] = screen_name if skip_status: parameters['skip_status'] = True if include_user_entities: parameters['include_user_entities'] = True while True: parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [User.NewFromJsonDict(x) for x in data['users']] if ('next_cursor' in data): if ((data['next_cursor'] == 0) or (data['next_cursor'] == data['previous_cursor'])): break else: cursor = data['next_cursor'] else: break return result
'Returns a list of twitter user id\'s for every person the specified user is following. Args: user_id: The id of the user to retrieve the id list for [Optional] screen_name: The screen_name of the user to retrieve the id list for [Optional] cursor: Specifies the Twitter API Cursor location to start at. Note: there are pagination limits. [Optional] stringify_ids: if True then twitter will return the ids as strings instead of integers. [Optional] count: The number of status messages to retrieve. [Optional] Returns: A list of integers, one for each user id.'
def GetFriendIDs(self, user_id=None, screen_name=None, cursor=(-1), stringify_ids=False, count=None):
url = ('%s/friends/ids.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') parameters = {} if (user_id is not None): parameters['user_id'] = user_id if (screen_name is not None): parameters['screen_name'] = screen_name if stringify_ids: parameters['stringify_ids'] = True if (count is not None): parameters['count'] = count result = [] while True: parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [x for x in data['ids']] if ('next_cursor' in data): if ((data['next_cursor'] == 0) or (data['next_cursor'] == data['previous_cursor'])): break else: cursor = data['next_cursor'] else: break return result
'Returns a list of twitter user id\'s for every person that is following the specified user. Args: user_id: The id of the user to retrieve the id list for [Optional] screen_name: The screen_name of the user to retrieve the id list for [Optional] cursor: Specifies the Twitter API Cursor location to start at. Note: there are pagination limits. [Optional] stringify_ids: if True then twitter will return the ids as strings instead of integers. [Optional] count: The number of user id\'s to retrieve per API request. Please be aware that this might get you rate-limited if set to a small number. By default Twitter will retrieve 5000 UIDs per call. [Optional] total_count: The total amount of UIDs to retrieve. Good if the account has many followers and you don\'t want to get rate limited. The data returned might contain more UIDs if total_count is not a multiple of count (5000 by default). [Optional] Returns: A list of integers, one for each user id.'
def GetFollowerIDs(self, user_id=None, screen_name=None, cursor=(-1), stringify_ids=False, count=None, total_count=None):
url = ('%s/followers/ids.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') parameters = {} if (user_id is not None): parameters['user_id'] = user_id if (screen_name is not None): parameters['screen_name'] = screen_name if stringify_ids: parameters['stringify_ids'] = True if (count is not None): parameters['count'] = count result = [] while True: if (total_count and (total_count < count)): parameters['count'] = total_count parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [x for x in data['ids']] if ('next_cursor' in data): if ((data['next_cursor'] == 0) or (data['next_cursor'] == data['previous_cursor'])): break else: cursor = data['next_cursor'] total_count -= len(data['ids']) if (total_count < 1): break else: break return result
'Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Args: user_id: The twitter id of the user whose followers you are fetching. If not specified, defaults to the authenticated user. [Optional] screen_name: The twitter name of the user whose followers you are fetching. If not specified, defaults to the authenticated user. [Optional] cursor: Should be set to -1 for the initial call and then is used to control what result page Twitter returns [Optional(ish)] skip_status: If True the statuses will not be returned in the user items. [Optional] include_user_entities: When True, the user entities will be included. Returns: A sequence of twitter.User instances, one for each follower'
def GetFollowers(self, user_id=None, screen_name=None, cursor=(-1), skip_status=False, include_user_entities=False):
if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') url = ('%s/followers/list.json' % self.base_url) result = [] parameters = {} if (user_id is not None): parameters['user_id'] = user_id if (screen_name is not None): parameters['screen_name'] = screen_name if skip_status: parameters['skip_status'] = True if include_user_entities: parameters['include_user_entities'] = True while True: parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [User.NewFromJsonDict(x) for x in data['users']] if ('next_cursor' in data): if ((data['next_cursor'] == 0) or (data['next_cursor'] == data['previous_cursor'])): break else: cursor = data['next_cursor'] else: break return result
'Fetch extended information for the specified users. Users may be specified either as lists of either user_ids, screen_names, or twitter.User objects. The list of users that are queried is the union of all specified parameters. The twitter.Api instance must be authenticated. Args: user_id: A list of user_ids to retrieve extended information. [Optional] screen_name: A list of screen_names to retrieve extended information. [Optional] users: A list of twitter.User objects to retrieve extended information. [Optional] include_entities: The entities node that may appear within embedded statuses will be disincluded when set to False. [Optional] Returns: A list of twitter.User objects for the requested users'
def UsersLookup(self, user_id=None, screen_name=None, users=None, include_entities=True):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') if ((not user_id) and (not screen_name) and (not users)): raise TwitterError('Specify at least one of user_id, screen_name, or users.') url = ('%s/users/lookup.json' % self.base_url) parameters = {} uids = list() if user_id: uids.extend(user_id) if users: uids.extend([u.id for u in users]) if len(uids): parameters['user_id'] = ','.join([('%s' % u) for u in uids]) if screen_name: parameters['screen_name'] = ','.join(screen_name) if (not include_entities): parameters['include_entities'] = 'false' json = self._FetchUrl(url, parameters=parameters) try: data = self._ParseAndCheckTwitter(json) except TwitterError as e: (_, e, _) = sys.exc_info() t = e.args[0] if ((len(t) == 1) and ('code' in t[0]) and (t[0]['code'] == 34)): data = [] else: raise return [User.NewFromJsonDict(u) for u in data]
'Returns a single user. The twitter.Api instance must be authenticated. Args: user_id: The id of the user to retrieve. [Optional] screen_name: The screen name of the user for whom to return results for. Either a user_id or screen_name is required for this method. [Optional] include_entities: if set to False, the \'entities\' node will not be included. [Optional] Returns: A twitter.User instance representing that user'
def GetUser(self, user_id=None, screen_name=None, include_entities=True):
url = ('%s/users/show.json' % self.base_url) parameters = {} if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') if user_id: parameters['user_id'] = user_id elif screen_name: parameters['screen_name'] = screen_name else: raise TwitterError('Specify at least one of user_id or screen_name.') if (not include_entities): parameters['include_entities'] = 'false' json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data)
'Returns a list of the direct messages sent to the authenticating user. The twitter.Api instance must be authenticated. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. [Optional] count: Specifies the number of direct messages to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of Tweets to return because suspended or deleted content is removed after the count has been applied. [Optional] include_entities: The entities node will not be included when set to False. [Optional] skip_status: When set to True statuses will not be included in the returned user objects. [Optional] Returns: A sequence of twitter.DirectMessage instances'
def GetDirectMessages(self, since_id=None, max_id=None, count=None, include_entities=True, skip_status=False):
url = ('%s/direct_messages.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') parameters = {} if since_id: parameters['since_id'] = since_id if max_id: parameters['max_id'] = max_id if count: try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') if (not include_entities): parameters['include_entities'] = 'false' if skip_status: parameters['skip_status'] = 1 json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [DirectMessage.NewFromJsonDict(x) for x in data]
'Returns a list of the direct messages sent by the authenticating user. The twitter.Api instance must be authenticated. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns results with an ID less than (that is, older than) or equal to the specified ID. [Optional] count: Specifies the number of direct messages to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of Tweets to return because suspended or deleted content is removed after the count has been applied. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional] include_entities: The entities node will not be included when set to False. [Optional] Returns: A sequence of twitter.DirectMessage instances'
def GetSentDirectMessages(self, since_id=None, max_id=None, count=None, page=None, include_entities=True):
url = ('%s/direct_messages/sent.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') parameters = {} if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page if max_id: parameters['max_id'] = max_id if count: try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') if (not include_entities): parameters['include_entities'] = 'false' json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [DirectMessage.NewFromJsonDict(x) for x in data]
'Post a twitter direct message from the authenticated user The twitter.Api instance must be authenticated. user_id or screen_name must be specified. Args: text: The message text to be posted. Must be less than 140 characters. user_id: The ID of the user who should receive the direct message. [Optional] screen_name: The screen name of the user who should receive the direct message. [Optional] Returns: A twitter.DirectMessage instance representing the message posted'
def PostDirectMessage(self, text, user_id=None, screen_name=None):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') url = ('%s/direct_messages/new.json' % self.base_url) data = {'text': text} if user_id: data['user_id'] = user_id elif screen_name: data['screen_name'] = screen_name else: raise TwitterError('Specify at least one of user_id or screen_name.') json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data)
'Destroys the direct message specified in the required ID parameter. The twitter.Api instance must be authenticated, and the authenticating user must be the recipient of the specified direct message. Args: id: The id of the direct message to be destroyed Returns: A twitter.DirectMessage instance representing the message destroyed'
def DestroyDirectMessage(self, id, include_entities=True):
url = ('%s/direct_messages/destroy.json' % self.base_url) data = {'id': id} if (not include_entities): data['include_entities'] = 'false' json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data)
'Befriends the user specified by the user_id or screen_name. The twitter.Api instance must be authenticated. Args: user_id: A user_id to follow [Optional] screen_name: A screen_name to follow [Optional] follow: Set to False to disable notifications for the target user Returns: A twitter.User instance representing the befriended user.'
def CreateFriendship(self, user_id=None, screen_name=None, follow=True):
url = ('%s/friendships/create.json' % self.base_url) data = {} if user_id: data['user_id'] = user_id elif screen_name: data['screen_name'] = screen_name else: raise TwitterError('Specify at least one of user_id or screen_name.') if follow: data['follow'] = 'true' else: data['follow'] = 'false' json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data)
'Discontinues friendship with a user_id or screen_name. The twitter.Api instance must be authenticated. Args: user_id: A user_id to unfollow [Optional] screen_name: A screen_name to unfollow [Optional] Returns: A twitter.User instance representing the discontinued friend.'
def DestroyFriendship(self, user_id=None, screen_name=None):
url = ('%s/friendships/destroy.json' % self.base_url) data = {} if user_id: data['user_id'] = user_id elif screen_name: data['screen_name'] = screen_name else: raise TwitterError('Specify at least one of user_id or screen_name.') json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data)
'Favorites the specified status object or id as the authenticating user. Returns the favorite status when successful. The twitter.Api instance must be authenticated. Args: id: The id of the twitter status to mark as a favorite. [Optional] status: The twitter.Status object to mark as a favorite. [Optional] include_entities: The entities node will be omitted when set to False. Returns: A twitter.Status instance representing the newly-marked favorite.'
def CreateFavorite(self, status=None, id=None, include_entities=True):
url = ('%s/favorites/create.json' % self.base_url) data = {} if id: data['id'] = id elif status: data['id'] = status.id else: raise TwitterError('Specify id or status') if (not include_entities): data['include_entities'] = 'false' json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data)
'Un-Favorites the specified status object or id as the authenticating user. Returns the un-favorited status when successful. The twitter.Api instance must be authenticated. Args: id: The id of the twitter status to unmark as a favorite. [Optional] status: The twitter.Status object to unmark as a favorite. [Optional] include_entities: The entities node will be omitted when set to False. Returns: A twitter.Status instance representing the newly-unmarked favorite.'
def DestroyFavorite(self, status=None, id=None, include_entities=True):
url = ('%s/favorites/destroy.json' % self.base_url) data = {} if id: data['id'] = id elif status: data['id'] = status.id else: raise TwitterError('Specify id or status') if (not include_entities): data['include_entities'] = 'false' json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return Status.NewFromJsonDict(data)
'Return a list of Status objects representing favorited tweets. By default, returns the (up to) 20 most recent tweets for the authenticated user. Args: user: The twitter name or id of the user whose favorites you are fetching. If not specified, defaults to the authenticated user. [Optional] page: Specifies the page of results to retrieve. Note: there are pagination limits. [Optional]'
def GetFavorites(self, user_id=None, screen_name=None, count=None, since_id=None, max_id=None, include_entities=True):
parameters = {} url = ('%s/favorites/list.json' % self.base_url) if user_id: parameters['user_id'] = user_id elif screen_name: parameters['screen_name'] = user_id if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError('since_id must be an integer') if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError('max_id must be an integer') if count: try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') if include_entities: parameters['include_entities'] = True json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data]
'Returns the 20 most recent mentions (status containing @screen_name) for the authenticating user. Args: count: Specifies the number of tweets to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occurred since the since_id, the since_id will be forced to the oldest ID available. [Optional] max_id: Returns only statuses with an ID less than (that is, older than) the specified ID. [Optional] trim_user: When set to True, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. contributor_details: If set to True, this parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included. include_entities: The entities node will be disincluded when set to False. Returns: A sequence of twitter.Status instances, one for each mention of the user.'
def GetMentions(self, count=None, since_id=None, max_id=None, trim_user=False, contributor_details=False, include_entities=True):
url = ('%s/statuses/mentions_timeline.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') parameters = {} if count: try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError('since_id must be an integer') if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError('max_id must be an integer') if trim_user: parameters['trim_user'] = 1 if contributor_details: parameters['contributor_details'] = 'true' if (not include_entities): parameters['include_entities'] = 'false' json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [Status.NewFromJsonDict(x) for x in data]
'Creates a new list with the give name for the authenticated user. The twitter.Api instance must be authenticated. Args: name: New name for the list mode: \'public\' or \'private\'. Defaults to \'public\'. [Optional] description: Description of the list. [Optional] Returns: A twitter.List instance representing the new list'
def CreateList(self, name, mode=None, description=None):
url = ('%s/lists/create.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') parameters = {'name': name} if (mode is not None): parameters['mode'] = mode if (description is not None): parameters['description'] = description json = self._FetchUrl(url, post_data=parameters) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data)
'Destroys the list identified by list_id or owner_screen_name/owner_id and slug. The twitter.Api instance must be authenticated. Args: owner_screen_name: The screen_name of the user who owns the list being requested by a slug. owner_id: The user ID of the user who owns the list being requested by a slug. list_id: The numerical id of the list. slug: You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you\'ll also have to specify the list owner using the owner_id or owner_screen_name parameters. Returns: A twitter.List instance representing the removed list.'
def DestroyList(self, owner_screen_name=False, owner_id=False, list_id=None, slug=None):
url = ('%s/lists/destroy.json' % self.base_url) data = {} if list_id: try: data['list_id'] = long(list_id) except: raise TwitterError('list_id must be an integer') elif slug: data['slug'] = slug if owner_id: try: data['owner_id'] = long(owner_id) except: raise TwitterError('owner_id must be an integer') elif owner_screen_name: data['owner_screen_name'] = owner_screen_name else: raise TwitterError('Identify list by list_id or owner_screen_name/owner_id and slug') else: raise TwitterError('Identify list by list_id or owner_screen_name/owner_id and slug') json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data)
'Creates a subscription to a list by the authenticated user The twitter.Api instance must be authenticated. Args: owner_screen_name: The screen_name of the user who owns the list being requested by a slug. owner_id: The user ID of the user who owns the list being requested by a slug. list_id: The numerical id of the list. slug: You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you\'ll also have to specify the list owner using the owner_id or owner_screen_name parameters. Returns: A twitter.List instance representing the list subscribed to'
def CreateSubscription(self, owner_screen_name=False, owner_id=False, list_id=None, slug=None):
url = ('%s/lists/subscribers/create.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') data = {} if list_id: try: data['list_id'] = long(list_id) except: raise TwitterError('list_id must be an integer') elif slug: data['slug'] = slug if owner_id: try: data['owner_id'] = long(owner_id) except: raise TwitterError('owner_id must be an integer') elif owner_screen_name: data['owner_screen_name'] = owner_screen_name else: raise TwitterError('Identify list by list_id or owner_screen_name/owner_id and slug') else: raise TwitterError('Identify list by list_id or owner_screen_name/owner_id and slug') json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data)
'Destroys the subscription to a list for the authenticated user The twitter.Api instance must be authenticated. Args: owner_screen_name: The screen_name of the user who owns the list being requested by a slug. owner_id: The user ID of the user who owns the list being requested by a slug. list_id: The numerical id of the list. slug: You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you\'ll also have to specify the list owner using the owner_id or owner_screen_name parameters. Returns: A twitter.List instance representing the removed list.'
def DestroySubscription(self, owner_screen_name=False, owner_id=False, list_id=None, slug=None):
url = ('%s/lists/subscribers/destroy.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') data = {} if list_id: try: data['list_id'] = long(list_id) except: raise TwitterError('list_id must be an integer') elif slug: data['slug'] = slug if owner_id: try: data['owner_id'] = long(owner_id) except: raise TwitterError('owner_id must be an integer') elif owner_screen_name: data['owner_screen_name'] = owner_screen_name else: raise TwitterError('Identify list by list_id or owner_screen_name/owner_id and slug') else: raise TwitterError('Identify list by list_id or owner_screen_name/owner_id and slug') json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return List.NewFromJsonDict(data)
'Obtain a collection of the lists the specified user is subscribed to, 20 lists per page by default. Does not include the user\'s own lists. The twitter.Api instance must be authenticated. Args: user_id: The ID of the user for whom to return results for. [Optional] screen_name: The screen name of the user for whom to return results for. [Optional] count: The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. cursor: "page" value that Twitter will use to start building the list sequence from. -1 to start at the beginning. Twitter will return in the result the values for next_cursor and previous_cursor. [Optional] Returns: A sequence of twitter.List instances, one for each list'
def GetSubscriptions(self, user_id=None, screen_name=None, count=20, cursor=(-1)):
if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') url = ('%s/lists/subscriptions.json' % self.base_url) parameters = {} try: parameters['cursor'] = int(cursor) except: raise TwitterError('cursor must be an integer') try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') if (user_id is not None): try: parameters['user_id'] = long(user_id) except: raise TwitterError('user_id must be an integer') elif (screen_name is not None): parameters['screen_name'] = screen_name else: raise TwitterError('Specify user_id or screen_name') json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) return [List.NewFromJsonDict(x) for x in data['lists']]
'Fetch the sequence of lists for a user. The twitter.Api instance must be authenticated. Args: user_id: The ID of the user for whom to return results for. [Optional] screen_name: The screen name of the user for whom to return results for. [Optional] count: The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. [Optional] cursor: "page" value that Twitter will use to start building the list sequence from. -1 to start at the beginning. Twitter will return in the result the values for next_cursor and previous_cursor. [Optional] Returns: A sequence of twitter.List instances, one for each list'
def GetLists(self, user_id=None, screen_name=None, count=None, cursor=(-1)):
if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') url = ('%s/lists/ownerships.json' % self.base_url) result = [] parameters = {} if (user_id is not None): try: parameters['user_id'] = long(user_id) except: raise TwitterError('user_id must be an integer') elif (screen_name is not None): parameters['screen_name'] = screen_name else: raise TwitterError('Specify user_id or screen_name') if (count is not None): parameters['count'] = count while True: parameters['cursor'] = cursor json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) result += [List.NewFromJsonDict(x) for x in data['lists']] if ('next_cursor' in data): if ((data['next_cursor'] == 0) or (data['next_cursor'] == data['previous_cursor'])): break else: cursor = data['next_cursor'] else: break return result
'Returns a twitter.User instance if the authenticating user is valid. Returns: A twitter.User instance representing that user if the credentials are valid, None otherwise.'
def VerifyCredentials(self):
if (not self._oauth_consumer): raise TwitterError('Api instance must first be given user credentials.') url = ('%s/account/verify_credentials.json' % self.base_url) try: json = self._FetchUrl(url, no_cache=True) except urllib2.HTTPError as http_error: if (http_error.code == httplib.UNAUTHORIZED): return None else: raise http_error data = self._ParseAndCheckTwitter(json) return User.NewFromJsonDict(data)
'Override the default cache. Set to None to prevent caching. Args: cache: An instance that supports the same API as the twitter._FileCache'
def SetCache(self, cache):
if (cache == DEFAULT_CACHE): self._cache = _FileCache() else: self._cache = cache
'Override the default urllib implementation. Args: urllib: An instance that supports the same API as the urllib2 module'
def SetUrllib(self, urllib):
self._urllib = urllib
'Override the default cache timeout. Args: cache_timeout: Time, in seconds, that responses should be reused.'
def SetCacheTimeout(self, cache_timeout):
self._cache_timeout = cache_timeout
'Override the default user agent Args: user_agent: A string that should be send to the server as the User-agent'
def SetUserAgent(self, user_agent):
self._request_headers['User-Agent'] = user_agent
'Set the X-Twitter HTTP headers that will be sent to the server. Args: client: The client name as a string. Will be sent to the server as the \'X-Twitter-Client\' header. url: The URL of the meta.xml as a string. Will be sent to the server as the \'X-Twitter-Client-URL\' header. version: The client version as a string. Will be sent to the server as the \'X-Twitter-Client-Version\' header.'
def SetXTwitterHeaders(self, client, url, version):
self._request_headers['X-Twitter-Client'] = client self._request_headers['X-Twitter-Client-URL'] = url self._request_headers['X-Twitter-Client-Version'] = version
'Suggest the "from source" value to be displayed on the Twitter web site. The value of the \'source\' parameter must be first recognized by the Twitter server. New source values are authorized on a case by case basis by the Twitter development team. Args: source: The source name as a string. Will be sent to the server as the \'source\' parameter.'
def SetSource(self, source):
self._default_params['source'] = source
'Fetch the rate limit status for the currently authorized user. Args: resources: A comma seperated list of resource families you want to know the current rate limit disposition of. [Optional] Returns: A dictionary containing the time the limit will reset (reset_time), the number of remaining hits allowed before the reset (remaining_hits), the number of hits allowed in a 60-minute period (hourly_limit), and the time of the reset in seconds since The Epoch (reset_time_in_seconds).'
def GetRateLimitStatus(self, resources=None):
parameters = {} if (resources is not None): parameters['resources'] = resources url = ('%s/application/rate_limit_status.json' % self.base_url) json = self._FetchUrl(url, parameters=parameters, no_cache=True) data = self._ParseAndCheckTwitter(json) return data
'Determines the minimum number of seconds that a program must wait before hitting the server again without exceeding the rate_limit imposed for the currently authenticated user. Returns: The minimum second interval that a program must use so as to not exceed the rate_limit imposed for the user.'
def MaximumHitFrequency(self):
rate_status = self.GetRateLimitStatus() reset_time = rate_status.get('reset_time', None) limit = rate_status.get('remaining_hits', None) if reset_time: reset = datetime.datetime(*rfc822.parsedate(reset_time)[:7]) delta = ((reset + datetime.timedelta(hours=1)) - datetime.datetime.utcnow()) if (not limit): return int(delta.seconds) max_frequency = (int((delta.seconds / limit)) + 1) return max_frequency return 60
'Return a string in key=value&key=value form Values of None are not included in the output string. Args: parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form'
def _EncodeParameters(self, parameters):
if (parameters is None): return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for (k, v) in parameters.items() if (v is not None)]))
'Return a string in key=value&key=value form Values are assumed to be encoded in the format specified by self._encoding, and are subsequently URL encoded. Args: post_data: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form'
def _EncodePostData(self, post_data):
if (post_data is None): return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for (k, v) in post_data.items()]))
'Try and parse the JSON returned from Twitter and return an empty dictionary if there is any error. This is a purely defensive check because during some Twitter network outages it will return an HTML failwhale page.'
def _ParseAndCheckTwitter(self, json):
try: data = simplejson.loads(json) self._CheckForTwitterError(data) except ValueError: if ('<title>Twitter / Over capacity</title>' in json): raise TwitterError('Capacity Error') if ('<title>Twitter / Error</title>' in json): raise TwitterError('Technical Error') raise TwitterError('json decoding') return data
'Raises a TwitterError if twitter returns an error message. Args: data: A python dict created from the Twitter json response Raises: TwitterError wrapping the twitter error message if one exists.'
def _CheckForTwitterError(self, data):
if ('error' in data): raise TwitterError(data['error']) if ('errors' in data): raise TwitterError(data['errors'])
'Fetch a URL, optionally caching for a specified time. Args: url: The URL to retrieve post_data: A dict of (str, unicode) key/value pairs. If set, POST will be used. parameters: A dict whose key/value pairs should encoded and added to the query string. [Optional] no_cache: If true, overrides the cache on the current request use_gzip_compression: If True, tells the server to gzip-compress the response. It does not apply to POST requests. Defaults to None, which will get the value to use from the instance variable self._use_gzip [Optional] Returns: A string containing the body of the response.'
def _FetchUrl(self, url, post_data=None, parameters=None, no_cache=None, use_gzip_compression=None):
extra_params = {} if self._default_params: extra_params.update(self._default_params) if parameters: extra_params.update(parameters) if post_data: http_method = 'POST' else: http_method = 'GET' if self._debugHTTP: _debug = 1 else: _debug = 0 http_handler = self._urllib.HTTPHandler(debuglevel=_debug) https_handler = self._urllib.HTTPSHandler(debuglevel=_debug) http_proxy = os.environ.get('http_proxy') https_proxy = os.environ.get('https_proxy') if ((http_proxy is None) or (https_proxy is None)): proxy_status = False else: proxy_status = True opener = self._urllib.OpenerDirector() opener.add_handler(http_handler) opener.add_handler(https_handler) if (proxy_status is True): proxy_handler = self._urllib.ProxyHandler({'http': str(http_proxy), 'https': str(https_proxy)}) opener.add_handler(proxy_handler) if (use_gzip_compression is None): use_gzip = self._use_gzip else: use_gzip = use_gzip_compression if (use_gzip and (not post_data)): opener.addheaders.append(('Accept-Encoding', 'gzip')) if (self._oauth_consumer is not None): if (post_data and (http_method == 'POST')): parameters = post_data.copy() req = oauth.Request.from_consumer_and_token(self._oauth_consumer, token=self._oauth_token, http_method=http_method, http_url=url, parameters=parameters) req.sign_request(self._signature_method_hmac_sha1, self._oauth_consumer, self._oauth_token) headers = req.to_header() if (http_method == 'POST'): encoded_post_data = req.to_postdata() else: encoded_post_data = None url = req.to_url() else: url = self._BuildUrl(url, extra_params=extra_params) encoded_post_data = self._EncodePostData(post_data) if (encoded_post_data or no_cache or (not self._cache) or (not self._cache_timeout)): response = opener.open(url, encoded_post_data) url_data = self._DecompressGzippedResponse(response) opener.close() else: if self._consumer_key: key = ((self._consumer_key + ':') + url) else: key = url last_cached = self._cache.GetCachedTime(key) if ((not last_cached) or (time.time() >= (last_cached + self._cache_timeout))): try: response = opener.open(url, encoded_post_data) url_data = self._DecompressGzippedResponse(response) self._cache.Set(key, url_data) except urllib2.HTTPError as e: print e opener.close() else: url_data = self._cache.Get(key) return url_data
'Attempt to find the username in a cross-platform fashion.'
def _GetUsername(self):
try: return (os.getenv('USER') or os.getenv('LOGNAME') or os.getenv('USERNAME') or os.getlogin() or 'nobody') except (AttributeError, IOError, OSError) as e: return 'nobody'
'Parse the first line of a GNTP message to get security and other info values @param data: GNTP Message @return: GNTP Message information in a dictionary'
def parse_info(self, data):
match = re.match((('GNTP/(?P<version>\\d+\\.\\d+) (?P<messagetype>REGISTER|NOTIFY|SUBSCRIBE|\\-OK|\\-ERROR)' + ' (?P<encryptionAlgorithmID>[A-Z0-9]+(:(?P<ivValue>[A-F0-9]+))?) ?') + '((?P<keyHashAlgorithmID>[A-Z0-9]+):(?P<keyHash>[A-F0-9]+).(?P<salt>[A-F0-9]+))?\r\n'), data, re.IGNORECASE) if (not match): raise ParseError('ERROR_PARSING_INFO_LINE') info = match.groupdict() if (info['encryptionAlgorithmID'] == 'NONE'): info['encryptionAlgorithmID'] = None return info
'Set a password for a GNTP Message @param password: Null to clear password @param encryptAlgo: Currently only supports MD5 @todo: Support other hash functions'
def set_password(self, password, encryptAlgo='MD5'):
self.password = password if (not password): self.info['encryptionAlgorithmID'] = None self.info['keyHashAlgorithm'] = None return password = password.encode('utf8') seed = time.ctime() salt = hashlib.md5(seed).hexdigest() saltHash = hashlib.md5(seed).digest() keyBasis = (password + saltHash) key = hashlib.md5(keyBasis).digest() keyHash = hashlib.md5(key).hexdigest() self.info['keyHashAlgorithmID'] = encryptAlgo.upper() self.info['keyHash'] = keyHash.upper() self.info['salt'] = salt.upper()
'Helper function to decode hex string to `proper` hex string @param value: Value to decode @return: Hex string'
def _decode_hex(self, value):
result = '' for i in range(0, len(value), 2): tmp = int(value[i:(i + 2)], 16) result += chr(tmp) return result
'Validate GNTP Message against stored password'
def validate_password(self, password):
self.password = password if (password == None): raise Exception() keyHash = self.info.get('keyHash', None) if ((keyHash is None) and (self.password is None)): return True if (keyHash is None): raise AuthError('Invalid keyHash') if (self.password is None): raise AuthError('Missing password') password = self.password.encode('utf8') saltHash = self._decode_hex(self.info['salt']) keyBasis = (password + saltHash) key = hashlib.md5(keyBasis).digest() keyHash = hashlib.md5(key).hexdigest() if (not (keyHash.upper() == self.info['keyHash'].upper())): raise AuthError('Invalid Hash') return True
'Verify required headers'
def validate(self):
for header in self.requiredHeaders: if (not self.headers.get(header, False)): raise ParseError(('Missing Notification Header: ' + header))
'Generate info line for GNTP Message @return: Info line string'
def format_info(self):
info = (u'GNTP/%s %s' % (self.info.get('version'), self.info.get('messagetype'))) if self.info.get('encryptionAlgorithmID', None): info += (' %s:%s' % (self.info.get('encryptionAlgorithmID'), self.info.get('ivValue'))) else: info += ' NONE' if self.info.get('keyHashAlgorithmID', None): info += (' %s:%s.%s' % (self.info.get('keyHashAlgorithmID'), self.info.get('keyHash'), self.info.get('salt'))) return info
'Helper function to parse blocks of GNTP headers into a dictionary @param data: @return: Dictionary of headers'
def parse_dict(self, data):
dict = {} for line in data.split('\r\n'): match = re.match('([\\w-]+):(.+)', line) if (not match): continue key = match.group(1).strip() val = match.group(2).strip() dict[key] = val return dict
'Decode GNTP Message @param data:'
def decode(self, data, password=None):
self.password = password self.raw = data parts = self.raw.split('\r\n\r\n') self.info = self.parse_info(data) self.headers = self.parse_dict(parts[0])
'Encode a GNTP Message @return: GNTP Message ready to be sent'
def encode(self):
self.validate() SEP = u': ' EOL = u'\r\n' message = (self.format_info() + EOL) for (k, v) in self.headers.iteritems(): message += (((k.encode('utf8') + SEP) + str(v).encode('utf8')) + EOL) message += EOL return message
'@param data: (Optional) See decode() @param password: (Optional) Password to use while encoding/decoding messages'
def __init__(self, data=None, password=None):
_GNTPBase.__init__(self, 'REGISTER') self.notifications = [] self.resources = {} self.requiredHeaders = ['Application-Name', 'Notifications-Count'] self.requiredNotification = ['Notification-Name'] if data: self.decode(data, password) else: self.set_password(password) self.headers['Application-Name'] = 'pygntp' self.headers['Notifications-Count'] = 0 self.add_origin_info()
'Validate required headers and validate notification headers'
def validate(self):
for header in self.requiredHeaders: if (not self.headers.get(header, False)): raise ParseError(('Missing Registration Header: ' + header)) for notice in self.notifications: for header in self.requiredNotification: if (not notice.get(header, False)): raise ParseError(('Missing Notification Header: ' + header))
'Decode existing GNTP Registration message @param data: Message to decode.'
def decode(self, data, password):
self.raw = data parts = self.raw.split('\r\n\r\n') self.info = self.parse_info(data) self.validate_password(password) self.headers = self.parse_dict(parts[0]) for (i, part) in enumerate(parts): if (i == 0): continue if (part.strip() == ''): continue notice = self.parse_dict(part) if notice.get('Notification-Name', False): self.notifications.append(notice) elif notice.get('Identifier', False): notice['Data'] = self._decode_binary(part, notice) self.resources[notice.get('Identifier')] = notice
'Add new Notification to Registration message @param name: Notification Name @param enabled: Default Notification to Enabled'
def add_notification(self, name, enabled=True):
notice = {} notice['Notification-Name'] = name notice['Notification-Enabled'] = str(enabled) self.notifications.append(notice) self.headers['Notifications-Count'] = len(self.notifications)