desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Post a twitter status message from the authenticated user with multiple pictures attached. Args: status: the text of your update media: location of multiple media elements(PNG, JPG, GIF) possibly_sensitive: set true is content is "advanced" in_reply_to_status_id: ID of a status that this is in reply to lat: location i...
def PostMultipleMedia(self, status, media, possibly_sensitive=None, in_reply_to_status_id=None, latitude=None, longitude=None, place_id=None, display_coordinates=False):
warnings.warn('This method is deprecated. Please use PostUpdate instead, passing a list of media that you would like to associate with the update.', PythonTwitterDeprecationWarning330) if (type(media) is not list): raise TwitterError('Must ...
'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. Args: status: The message text to be posted. May be longer than 140 characters. continuation: The character string, if any, to be appe...
def PostUpdates(self, status, continuation=None, **kwargs):
results = list() if (continuation is None): continuation = '' char_limit = (CHARACTER_LIMIT - len(continuation)) tweets = self._TweetTextWrap(status=status, char_lim=char_limit) if (len(tweets) == 1): results.append(self.PostUpdate(status=tweets[0], **kwargs)) return results ...
'Retweet a tweet with the Retweet API. Args: status_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 w...
def PostRetweet(self, status_id, trim_user=False):
try: if (int(status_id) <= 0): raise TwitterError({'message': "'status_id' must be a positive number"}) except ValueError: raise TwitterError({'message': "'status_id' must be an integer"}) url = ('%s/statuses/retweet/%s.json' % (self.base_url, status_id...
'Fetch the sequence of retweets made by the authenticated user. 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 ...
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 th...
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 (int): The ID of the tweet for which retweets should be searched for count (int, optional): The number of status messages to retrieve. trim_user (bool, optional): If True the returned payload will only contain the user IDs, othe...
def GetRetweets(self, statusid, count=None, trim_user=False):
url = ('%s/statuses/retweets/%s.json' % (self.base_url, statusid)) parameters = {'trim_user': enf_type('trim_user', bool, trim_user)} if count: parameters['count'] = enf_type('count', int, count) resp = self._RequestUrl(url, 'GET', data=parameters) data = self._ParseAndCheckTwitter(resp.cont...
'Returns a collection of up to 100 user IDs belonging to users who have retweeted the tweet specified by the status_id parameter. Args: status_id: the tweet\'s numerical ID cursor: breaks the ids into pages of no more than 100. stringify_ids: returns the IDs as unicode strings. [Optional] Returns: A list of user IDs'
def GetRetweeters(self, status_id, cursor=None, count=100, stringify_ids=False):
url = ('%s/statuses/retweeters/ids.json' % self.base_url) parameters = {'id': enf_type('id', int, status_id), 'stringify_ids': enf_type('stringify_ids', bool, stringify_ids)} result = [] total_count = 0 while True: if cursor: try: parameters['cursor'] = int(cursor...
'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. Defaults to 20. [Optional] since_id: Returns results with an ID greater than (newer than) this ID. [Optional] max_id: Returns results with an ID less than or equal to ...
def GetRetweetsOfMe(self, count=None, since_id=None, max_id=None, trim_user=False, include_entities=True, include_user_entities=True):
url = ('%s/statuses/retweets_of_me.json' % self.base_url) parameters = {} if (count is not None): try: if (int(count) > 100): raise TwitterError({'message': "'count' may not be greater than 100"}) except ValueError: raise TwitterError...
'Fetch a page of the users (as twitter.User instances) blocked or muted by the currently authenticated user. Args: endpoint (str): Either "mute" or "block". action (str): Either \'list\' or \'ids\' depending if you want to return fully-hydrated twitter.User objects or a list of user IDs as ints. cursor (int, optional):...
def _GetBlocksMutesPaged(self, endpoint, action, cursor=(-1), skip_status=False, include_entities=False, stringify_ids=False):
urls = {'mute': {'list': ('%s/mutes/users/list.json' % self.base_url), 'ids': ('%s/mutes/users/ids.json' % self.base_url)}, 'block': {'list': ('%s/blocks/list.json' % self.base_url), 'ids': ('%s/blocks/ids.json' % self.base_url)}} url = urls[endpoint][action] result = [] parameters = {} if skip_stat...
'Fetch the sequence of all users (as twitter.User instances), blocked by the currently authenticated user. Args: skip_status (bool, optional): If True the statuses will not be returned in the user items. include_entities (bool, optional): When True, the user entities will be included. Returns: A list of twitter.User in...
def GetBlocks(self, skip_status=False, include_entities=False):
result = [] cursor = (-1) while True: (next_cursor, previous_cursor, users) = self.GetBlocksPaged(cursor=cursor, skip_status=skip_status, include_entities=include_entities) result += users if ((next_cursor == 0) or (next_cursor == previous_cursor)): break else: ...
'Fetch a page of the users (as twitter.User instances) blocked by the currently authenticated user. Args: cursor (int, optional): Should be set to -1 if you want the first page, thereafter denotes the page of blocked users that you want to return. skip_status (bool, optional): If True the statuses will not be returned ...
def GetBlocksPaged(self, cursor=(-1), skip_status=False, include_entities=False):
return self._GetBlocksMutesPaged(endpoint='block', action='list', cursor=cursor, skip_status=skip_status, include_entities=include_entities)
'Fetch the sequence of all user IDs blocked by the currently authenticated user. Args: stringify_ids (bool, optional): If True user IDs will be returned as strings rather than integers. Returns: A list of user IDs for all blocked users.'
def GetBlocksIDs(self, stringify_ids=False):
result = [] cursor = (-1) while True: (next_cursor, previous_cursor, user_ids) = self.GetBlocksIDsPaged(cursor=cursor, stringify_ids=stringify_ids) result += user_ids if ((next_cursor == 0) or (next_cursor == previous_cursor)): break else: cursor = nex...
'Fetch a page of the user IDs blocked by the currently authenticated user. Args: cursor (int, optional): Should be set to -1 if you want the first page, thereafter denotes the page of blocked users that you want to return. stringify_ids (bool, optional): If True user IDs will be returned as strings rather than integers...
def GetBlocksIDsPaged(self, cursor=(-1), stringify_ids=False):
return self._GetBlocksMutesPaged(endpoint='block', action='ids', cursor=cursor, stringify_ids=False)
'Fetch the sequence of all users (as twitter.User instances), muted by the currently authenticated user. Args: skip_status (bool, optional): If True the statuses will not be returned in the user items. include_entities (bool, optional): When True, the user entities will be included. Returns: A list of twitter.User inst...
def GetMutes(self, skip_status=False, include_entities=False):
result = [] cursor = (-1) while True: (next_cursor, previous_cursor, users) = self.GetMutesPaged(cursor=cursor, skip_status=skip_status, include_entities=include_entities) result += users if ((next_cursor == 0) or (next_cursor == previous_cursor)): break else: ...
'Fetch a page of the users (as twitter.User instances) muted by the currently authenticated user. Args: cursor (int, optional): Should be set to -1 if you want the first page, thereafter denotes the page of muted users that you want to return. skip_status (bool, optional): If True the statuses will not be returned in t...
def GetMutesPaged(self, cursor=(-1), skip_status=False, include_entities=False):
return self._GetBlocksMutesPaged(endpoint='mute', action='list', cursor=cursor, skip_status=skip_status, include_entities=include_entities)
'Fetch the sequence of all user IDs muted by the currently authenticated user. Args: stringify_ids (bool, optional): If True user IDs will be returned as strings rather than integers. Returns: A list of user IDs for all muted users.'
def GetMutesIDs(self, stringify_ids=False):
result = [] cursor = (-1) while True: (next_cursor, previous_cursor, user_ids) = self.GetMutesIDsPaged(cursor=cursor, stringify_ids=stringify_ids) result += user_ids if ((next_cursor == 0) or (next_cursor == previous_cursor)): break else: cursor = next...
'Fetch a page of the user IDs muted by the currently authenticated user. Args: cursor (int, optional): Should be set to -1 if you want the first page, thereafter denotes the page of muted users that you want to return. stringify_ids (bool, optional): If True user IDs will be returned as strings rather than integers. Re...
def GetMutesIDsPaged(self, cursor=(-1), stringify_ids=False):
return self._GetBlocksMutesPaged(endpoint='mute', action='ids', cursor=cursor, stringify_ids=stringify_ids)
'Create or destroy a block or mute on behalf of the authenticated user. Args: action (str): Either \'create\' or \'destroy\'. endpoint (str): Either \'block\' or \'mute\'. user_id (int, optional) The numerical ID of the user to block/mute. screen_name (str, optional): The screen name of the user to block/mute. include_...
def _BlockMute(self, action, endpoint, user_id=None, screen_name=None, include_entities=True, skip_status=False):
urls = {'block': {'create': ('%s/blocks/create.json' % self.base_url), 'destroy': ('%s/blocks/destroy.json' % self.base_url)}, 'mute': {'create': ('%s/mutes/users/create.json' % self.base_url), 'destroy': ('%s/mutes/users/destroy.json' % self.base_url)}} url = urls[endpoint][action] post_data = {} if us...
'Blocks the user specified by either user_id or screen_name. Args: user_id (int, optional) The numerical ID of the user to block. screen_name (str, optional): The screen name of the user to block. include_entities (bool, optional): The entities node will not be included if set to False. skip_status (bool, optional): Wh...
def CreateBlock(self, user_id=None, screen_name=None, include_entities=True, skip_status=False):
return self._BlockMute(action='create', endpoint='block', user_id=user_id, screen_name=screen_name, include_entities=include_entities, skip_status=skip_status)
'Unlocks the user specified by either user_id or screen_name. Args: user_id (int, optional) The numerical ID of the user to block. screen_name (str, optional): The screen name of the user to block. include_entities (bool, optional): The entities node will not be included if set to False. skip_status (bool, optional): W...
def DestroyBlock(self, user_id=None, screen_name=None, include_entities=True, skip_status=False):
return self._BlockMute(action='destroy', endpoint='block', user_id=user_id, screen_name=screen_name, include_entities=include_entities, skip_status=skip_status)
'Mutes the user specified by either user_id or screen_name. Args: user_id (int, optional) The numerical ID of the user to mute. screen_name (str, optional): The screen name of the user to mute. include_entities (bool, optional): The entities node will not be included if set to False. skip_status (bool, optional): When ...
def CreateMute(self, user_id=None, screen_name=None, include_entities=True, skip_status=False):
return self._BlockMute(action='create', endpoint='mute', user_id=user_id, screen_name=screen_name, include_entities=include_entities, skip_status=skip_status)
'Unlocks the user specified by either user_id or screen_name. Args: user_id (int, optional) The numerical ID of the user to mute. screen_name (str, optional): The screen name of the user to mute. include_entities (bool, optional): The entities node will not be included if set to False. skip_status (bool, optional): Whe...
def DestroyMute(self, user_id=None, screen_name=None, include_entities=True, skip_status=False):
return self._BlockMute(action='destroy', endpoint='mute', user_id=user_id, screen_name=screen_name, include_entities=include_entities, skip_status=skip_status)
'This is the lowest level paging logic for fetching IDs. It is used solely by GetFollowerIDsPaged and GetFriendIDsPaged. It is not intended for other use. See GetFollowerIDsPaged or GetFriendIDsPaged for an explanation of the input arguments.'
def _GetIDsPaged(self, url, user_id, screen_name, cursor, stringify_ids, count):
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 (count is not None): parameters['count'] = count parameters['stringify_ids'] = stringify_ids parameters['curs...
'Make a cursor driven call to return a list of one page followers. The caller is responsible for handling the cursor value and looping to gather all of the data 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 t...
def GetFollowerIDsPaged(self, user_id=None, screen_name=None, cursor=(-1), stringify_ids=False, count=5000):
url = ('%s/followers/ids.json' % self.base_url) return self._GetIDsPaged(url=url, user_id=user_id, screen_name=screen_name, cursor=cursor, stringify_ids=stringify_ids, count=count)
'Make a cursor driven call to return the list of all friends The caller is responsible for handling the cursor value and looping to gather all of the data 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 n...
def GetFriendIDsPaged(self, user_id=None, screen_name=None, cursor=(-1), stringify_ids=False, count=5000):
url = ('%s/friends/ids.json' % self.base_url) return self._GetIDsPaged(url, user_id, screen_name, cursor, stringify_ids, count)
'Common method for GetFriendIDs and GetFollowerIDs'
def _GetFriendFollowerIDs(self, url=None, user_id=None, screen_name=None, cursor=None, count=None, stringify_ids=False, total_count=None):
count = 5000 cursor = (-1) result = [] if total_count: total_count = enf_type('total_count', int, total_count) if (total_count and (total_count < count)): count = total_count while True: if ((total_count is not None) and ((len(result) + count) > total_count)): ...
'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: the...
def GetFollowerIDs(self, user_id=None, screen_name=None, cursor=None, stringify_ids=False, count=None, total_count=None):
url = ('%s/followers/ids.json' % self.base_url) return self._GetFriendFollowerIDs(url=url, user_id=user_id, screen_name=screen_name, cursor=cursor, stringify_ids=stringify_ids, count=count, total_count=total_count)
'Fetch a sequence of user ids, one for each friend. Returns a list of all the given user\'s friends\' IDs. If no user_id or screen_name is given, the friends will be those of the authenticated 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 ret...
def GetFriendIDs(self, user_id=None, screen_name=None, cursor=None, count=None, stringify_ids=False, total_count=None):
url = ('%s/friends/ids.json' % self.base_url) return self._GetFriendFollowerIDs(url, user_id, screen_name, cursor, count, stringify_ids, total_count)
'Make a cursor driven call to return the list of 1 page of friends or followers. Args: url: Endpoint from which to get data. Either base_url+\'/followers/list.json\' or base_url+\'/friends/list.json\'. user_id: The twitter id of the user whose followers you are fetching. If not specified, defaults to the authenticated ...
def _GetFriendsFollowersPaged(self, url=None, user_id=None, screen_name=None, cursor=(-1), count=200, skip_status=False, include_user_entities=True):
if (user_id and screen_name): warnings.warn('If both user_id and screen_name are specified, Twitter will return the followers of the user specified by screen_name, however this behavior is undocumented by Twitter and might chan...
'Make a cursor driven call to return the list of all followers 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 authen...
def GetFollowersPaged(self, user_id=None, screen_name=None, cursor=(-1), count=200, skip_status=False, include_user_entities=True):
url = ('%s/followers/list.json' % self.base_url) return self._GetFriendsFollowersPaged(url, user_id, screen_name, cursor, count, skip_status, include_user_entities)
'Make a cursor driven call to return the list of all friends. 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 authenticat...
def GetFriendsPaged(self, user_id=None, screen_name=None, cursor=(-1), count=200, skip_status=False, include_user_entities=True):
url = ('%s/friends/list.json' % self.base_url) return self._GetFriendsFollowersPaged(url, user_id, screen_name, cursor, count, skip_status, include_user_entities)
'Fetch the sequence of twitter.User instances, one for each friend or follower. Args: url: URL to get. Either base_url + (\'/followers/list.json\' or \'/friends/list.json\'). user_id: The twitter id of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [Optional] screen_name:...
def _GetFriendsFollowers(self, url=None, user_id=None, screen_name=None, cursor=None, count=None, total_count=None, skip_status=False, include_user_entities=True):
if ((cursor is not None) or (count is not None)): warnings.warn("Use of 'cursor' and 'count' parameters are deprecated as of python-twitter 3.0. Please use GetFriendsPaged or GetFollowersPaged instead.", PythonTwitterDeprecationWarning330) count = 200 ...
'Fetch the sequence of twitter.User instances, one for each follower. If both user_id and screen_name are specified, this call will return the followers of the user specified by screen_name, however this behavior is undocumented by Twitter and may change without warning. Args: user_id: The twitter id of the user whose ...
def GetFollowers(self, user_id=None, screen_name=None, cursor=None, count=None, total_count=None, skip_status=False, include_user_entities=True):
url = ('%s/followers/list.json' % self.base_url) return self._GetFriendsFollowers(url, user_id, screen_name, cursor, count, total_count, skip_status, include_user_entities)
'Fetch the sequence of twitter.User instances, one for each friend. If both user_id and screen_name are specified, this call will return the followers of the user specified by screen_name, however this behavior is undocumented by Twitter and may change without warning. Args: user_id: The twitter id of the user whose fr...
def GetFriends(self, user_id=None, screen_name=None, cursor=None, count=None, total_count=None, skip_status=False, include_user_entities=True):
url = ('%s/friends/list.json' % self.base_url) return self._GetFriendsFollowers(url, user_id, screen_name, cursor, count, total_count, skip_status, include_user_entities)
'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. Args: user_id (int, list, optional): A list of user_ids to retrieve extended information. sc...
def UsersLookup(self, user_id=None, screen_name=None, users=None, include_entities=True):
if (not any([user_id, screen_name, users])): raise TwitterError('Specify at least one of user_id, screen_name, or users.') url = ('%s/users/lookup.json' % self.base_url) parameters = {'include_entities': include_entities} uids = list() if user_id: uids.extend(...
'Returns a single user. Args: user_id (int, optional): The id of the user to retrieve. screen_name (str, optional): The screen name of the user for whom to return results for. Either a user_id or screen_name is required for this method. include_entities (bool, optional): The entities node will be omitted when set to Fa...
def GetUser(self, user_id=None, screen_name=None, include_entities=True):
url = ('%s/users/show.json' % self.base_url) parameters = {'include_entities': include_entities} 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 o...
'Returns a list of the direct messages sent 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_...
def GetDirectMessages(self, since_id=None, max_id=None, count=None, include_entities=True, skip_status=False, full_text=False, page=None):
url = ('%s/direct_messages.json' % self.base_url) 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 ValueError: raise TwitterError({'me...
'Returns a list of the direct messages sent by 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 occured since the since_id, the since_i...
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) 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) ex...
'Post a twitter direct message from the authenticated user. 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 tw...
def PostDirectMessage(self, text, user_id=None, screen_name=None):
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({'message': 'Specify at least one of user_id or screen_name.'}) ...
'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: message_id: The id of the direct message to be destroyed Returns: A twitter.DirectMessage instance representing th...
def DestroyDirectMessage(self, message_id, include_entities=True):
url = ('%s/direct_messages/destroy.json' % self.base_url) data = {'id': enf_type('message_id', int, message_id), 'include_entities': enf_type('include_entities', bool, include_entities)} resp = self._RequestUrl(url, 'POST', data=data) data = self._ParseAndCheckTwitter(resp.content.decode('utf-8')) r...
'Befriends the user specified by the user_id or screen_name. 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):
return self._AddOrEditFriendship(user_id=user_id, screen_name=screen_name, follow=follow)
'Shared method for Create/Update Friendship.'
def _AddOrEditFriendship(self, user_id=None, screen_name=None, uri_end='create', follow_key='follow', follow=True):
url = ('%s/friendships/%s.json' % (self.base_url, uri_end)) data = {} if user_id: data['user_id'] = user_id elif screen_name: data['screen_name'] = screen_name else: raise TwitterError({'message': 'Specify at least one of user_id or screen_name.'}) fo...
'Updates a friendship with the user specified by the user_id or screen_name. Args: user_id: A user_id to update [Optional] screen_name: A screen_name to update [Optional] follow: Set to False to disable notifications for the target user device: Set to False to disable notifications for the target user Returns: A twitte...
def UpdateFriendship(self, user_id=None, screen_name=None, follow=True, **kwargs):
follow = kwargs.get('device', follow) return self._AddOrEditFriendship(user_id=user_id, screen_name=screen_name, follow=follow, follow_key='device', uri_end='update')
'Discontinues friendship with a user_id or screen_name. 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({'message': 'Specify at least one of user_id or screen_name.'}) resp = s...
'Returns information about the relationship between the two users. Args: source_id: The user_id of the subject user [Optional] source_screen_name: The screen_name of the subject user [Optional] target_id: The user_id of the target user [Optional] target_screen_name: The screen_name of the target user [Optional] Returns...
def ShowFriendship(self, source_user_id=None, source_screen_name=None, target_user_id=None, target_screen_name=None):
url = ('%s/friendships/show.json' % self.base_url) data = {} if source_user_id: data['source_id'] = source_user_id elif source_screen_name: data['source_screen_name'] = source_screen_name else: raise TwitterError({'message': 'Specify at least one of source_user...
'Lookup friendship status for user to authed user. 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. Up to 100 users may be specified. Args: user_id (int, User, or list of ints or Users, optional...
def LookupFriendship(self, user_id=None, screen_name=None):
url = ('%s/friendships/lookup.json' % self.base_url) parameters = {} if user_id: if (isinstance(user_id, list) or isinstance(user_id, tuple)): uids = list() for user in user_id: if isinstance(user, User): uids.append(user.id) ...
'Returns a collection of user IDs belonging to users who have pending request to follow the authenticated user. Args: cursor: breaks the ids into pages of no more than 5000. stringify_ids: returns the IDs as unicode strings. [Optional] Returns: A list of user IDs'
def IncomingFriendship(self, cursor=None, stringify_ids=None):
url = ('%s/friendships/incoming.json' % self.base_url) parameters = {} if stringify_ids: parameters['stringify_ids'] = 'true' result = [] total_count = 0 while True: if cursor: try: parameters['count'] = int(cursor) except ValueError: ...
'Returns a collection of user IDs for every protected user for whom the authenticated user has a pending follow request. Args: cursor: breaks the ids into pages of no more than 5000. stringify_ids: returns the IDs as unicode strings. [Optional] Returns: A list of user IDs'
def OutgoingFriendship(self, cursor=None, stringify_ids=None):
url = ('%s/friendships/outgoing.json' % self.base_url) parameters = {} if stringify_ids: parameters['stringify_ids'] = 'true' result = [] total_count = 0 while True: if cursor: try: parameters['count'] = int(cursor) except ValueError: ...
'Favorites the specified status object or id as the authenticating user. Returns the favorite status when successful. Args: status_id (int, optional): The id of the twitter status to mark as a favorite. status (twitter.Status, optional): The twitter.Status object to mark as a favorite. include_entities (bool, optional)...
def CreateFavorite(self, status=None, status_id=None, include_entities=True):
url = ('%s/favorites/create.json' % self.base_url) data = {} if status_id: data['id'] = status_id elif status: data['id'] = status.id else: raise TwitterError({'message': 'Specify status_id or status'}) data['include_entities'] = enf_type('include_entities', bool...
'Un-Favorites the specified status object or id as the authenticating user. Returns the un-favorited status when successful. Args: status_id (int, optional): The id of the twitter status to mark as a favorite. status (twitter.Status, optional): The twitter.Status object to mark as a favorite. include_entities (bool, op...
def DestroyFavorite(self, status=None, status_id=None, include_entities=True):
url = ('%s/favorites/destroy.json' % self.base_url) data = {} if status_id: data['id'] = status_id elif status: data['id'] = status.id else: raise TwitterError({'message': 'Specify status_id or status'}) data['include_entities'] = enf_type('include_entities', boo...
'Return a list of Status objects representing favorited tweets. Returns up to 200 most recent tweets for the authenticated user. Args: user_id (int, optional): Specifies the ID of the user for whom to return the favorites. Helpful for disambiguating when a valid user ID is also a valid screen name. screen_name (str, op...
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'] = enf_type('user_id', int, user_id) elif screen_name: parameters['screen_name'] = screen_name if since_id: parameters['since_id'] = enf_type('since_id', int, since_id) if ma...
'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 a...
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) parameters = {} if count: parameters['count'] = enf_type('count', int, count) if since_id: parameters['since_id'] = enf_type('since_id', int, since_id) if max_id: parameters['max_id'] = enf_type('max_id', int, max_i...
'Creates a new list with the give name for the authenticated user. Args: name (str): New name for the list mode (str, optional): \'public\' or \'private\'. Defaults to \'public\'. description (str, optional): Description of the list. Returns: twitter.list.List: A twitter.List instance representing the new list'
def CreateList(self, name, mode=None, description=None):
url = ('%s/lists/create.json' % self.base_url) parameters = {'name': name} if (mode is not None): parameters['mode'] = mode if (description is not None): parameters['description'] = description resp = self._RequestUrl(url, 'POST', data=parameters) data = self._ParseAndCheckTwitte...
'Destroys the list identified by list_id or slug and one of owner_screen_name or owner_id. Args: owner_screen_name (str, optional): The screen_name of the user who owns the list being requested by a slug. owner_id (int, optional): The user ID of the user who owns the list being requested by a slug. list_id (int, option...
def DestroyList(self, owner_screen_name=None, owner_id=None, list_id=None, slug=None):
url = ('%s/lists/destroy.json' % self.base_url) parameters = {} parameters.update(self._IDList(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name)) resp = self._RequestUrl(url, 'POST', data=parameters) data = self._ParseAndCheckTwitter(resp.content.decode('utf-8')) ...
'Creates a subscription to a list by the authenticated user. Args: owner_screen_name (str, optional): The screen_name of the user who owns the list being requested by a slug. owner_id (int, optional): The user ID of the user who owns the list being requested by a slug. list_id (int, optional): The numerical id of the l...
def CreateSubscription(self, owner_screen_name=None, owner_id=None, list_id=None, slug=None):
url = ('%s/lists/subscribers/create.json' % self.base_url) parameters = {} parameters.update(self._IDList(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name)) resp = self._RequestUrl(url, 'POST', data=parameters) data = self._ParseAndCheckTwitter(resp.content.decode('...
'Destroys the subscription to a list for the authenticated user. Args: owner_screen_name (str, optional): The screen_name of the user who owns the list being requested by a slug. owner_id (int, optional): The user ID of the user who owns the list being requested by a slug. list_id (int, optional): The numerical id of t...
def DestroySubscription(self, owner_screen_name=None, owner_id=None, list_id=None, slug=None):
url = ('%s/lists/subscribers/destroy.json' % self.base_url) parameters = {} parameters.update(self._IDList(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name)) resp = self._RequestUrl(url, 'POST', data=parameters) data = self._ParseAndCheckTwitter(resp.content.decode(...
'Check if the specified user is a subscriber of the specified list. Returns the user if they are subscriber. Args: owner_screen_name (str, optional): The screen_name of the user who owns the list being requested by a slug. owner_id (int, optional): The user ID of the user who owns the list being requested by a slug. li...
def ShowSubscription(self, owner_screen_name=None, owner_id=None, list_id=None, slug=None, user_id=None, screen_name=None, include_entities=False, skip_status=False):
url = ('%s/lists/subscribers/show.json' % self.base_url) parameters = {} parameters.update(self._IDList(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name)) if user_id: parameters['user_id'] = enf_type('user_id', int, user_id) elif screen_name: paramet...
'Obtain a collection of the lists the specified user is subscribed to. If neither user_id or screen_name is specified, the data returned will be for the authenticated user. The list will contain a maximum of 20 lists per page by default. Does not include the user\'s own lists. Args: user_id (int, optional): The ID of t...
def GetSubscriptions(self, user_id=None, screen_name=None, count=20, cursor=(-1)):
url = ('%s/lists/subscriptions.json' % self.base_url) parameters = {} parameters['cursor'] = enf_type('cursor', int, cursor) parameters['count'] = enf_type('count', int, count) if (user_id is not None): parameters['user_id'] = enf_type('user_id', int, user_id) elif (screen_name is not No...
'Obtain the lists the specified user is a member of. If no user_id or screen_name is specified, the data returned will be for the authenticated user. Returns a maximum of 20 lists per page by default. Args: user_id (int, optional): The ID of the user for whom to return results for. screen_name (str, optional): The scre...
def GetMemberships(self, user_id=None, screen_name=None, count=20, cursor=(-1), filter_to_owned_lists=False):
url = ('%s/lists/memberships.json' % self.base_url) parameters = {} if (cursor is not None): parameters['cursor'] = enf_type('cursor', int, cursor) if (count is not None): parameters['count'] = enf_type('count', int, count) if filter_to_owned_lists: parameters['filter_to_owne...
'Returns all lists the user subscribes to, including their own. If no user_id or screen_name is specified, the data returned will be for the authenticated user. Args: screen_name (str, optional): Specifies the screen name of the user for whom to return the user_timeline. Helpful for disambiguating when a valid screen n...
def GetListsList(self, screen_name=None, user_id=None, reverse=False):
url = ('%s/lists/list.json' % self.base_url) parameters = {} if user_id: parameters['user_id'] = enf_type('user_id', int, user_id) elif screen_name: parameters['screen_name'] = screen_name if reverse: parameters['reverse'] = enf_type('reverse', bool, reverse) resp = self....
'Fetch the sequence of Status messages for a given List ID. Args: list_id (int, optional): Specifies the ID of the list to retrieve. slug (str, optional): The slug name for the list to retrieve. If you specify None for the list_id, then you have to provide either a owner_screen_name or owner_id. owner_id (int, optional...
def GetListTimeline(self, list_id=None, slug=None, owner_id=None, owner_screen_name=None, since_id=None, max_id=None, count=None, include_rts=True, include_entities=True):
url = ('%s/lists/statuses.json' % self.base_url) parameters = {} parameters.update(self._IDList(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name)) if since_id: parameters['since_id'] = enf_type('since_id', int, since_id) if max_id: parameters['max_id...
'Fetch the sequence of twitter.User instances, one for each member of the given list_id or slug. Args: list_id (int, optional): Specifies the ID of the list to retrieve. slug (str, optional): The slug name for the list to retrieve. If you specify None for the list_id, then you have to provide either a owner_screen_name...
def GetListMembersPaged(self, list_id=None, slug=None, owner_id=None, owner_screen_name=None, cursor=(-1), count=100, skip_status=False, include_entities=True):
url = ('%s/lists/members.json' % self.base_url) parameters = {} parameters.update(self._IDList(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name)) if count: parameters['count'] = enf_type('count', int, count) if cursor: parameters['cursor'] = enf_type...
'Fetch the sequence of twitter.User instances, one for each member of the given list_id or slug. Args: list_id (int, optional): Specifies the ID of the list to retrieve. slug (str, optional): The slug name for the list to retrieve. If you specify None for the list_id, then you have to provide either a owner_screen_name...
def GetListMembers(self, list_id=None, slug=None, owner_id=None, owner_screen_name=None, skip_status=False, include_entities=False):
cursor = (-1) result = [] while True: (next_cursor, previous_cursor, users) = self.GetListMembersPaged(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name, cursor=cursor, skip_status=skip_status, include_entities=include_entities) result += users if ((n...
'Add a new member (or list of members) to the specified list. Args: list_id (int, optional): The numerical id of the list. slug (str, optional): 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_scre...
def CreateListsMember(self, list_id=None, slug=None, user_id=None, screen_name=None, owner_screen_name=None, owner_id=None):
is_list = False parameters = {} parameters.update(self._IDList(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name)) if user_id: if (isinstance(user_id, list) or isinstance(user_id, tuple)): is_list = True uids = [str(enf_type('user_id', int...
'Destroys the subscription to a list for the authenticated user. Args: list_id (int, optional): The numerical id of the list. slug (str, optional): 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_s...
def DestroyListsMember(self, list_id=None, slug=None, owner_screen_name=None, owner_id=None, user_id=None, screen_name=None):
is_list = False parameters = {} parameters.update(self._IDList(list_id=list_id, slug=slug, owner_id=owner_id, owner_screen_name=owner_screen_name)) if user_id: if (isinstance(user_id, list) or isinstance(user_id, tuple)): is_list = True uids = [str(enf_type('user_id', int...
'Fetch the sequence of lists for a user. If no user_id or screen_name is passed, the data returned will be for the authenticated user. Args: user_id (int, optional): The ID of the user for whom to return results for. screen_name (str, optional): The screen name of the user for whom to return results for. count (int, op...
def GetListsPaged(self, user_id=None, screen_name=None, cursor=(-1), count=20):
url = ('%s/lists/ownerships.json' % self.base_url) parameters = {} if (user_id is not None): parameters['user_id'] = enf_type('user_id', int, user_id) elif (screen_name is not None): parameters['screen_name'] = screen_name if (count is not None): parameters['count'] = enf_typ...
'Fetch the sequence of lists for a user. If no user_id or screen_name is passed, the data returned will be for the authenticated user. 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 res...
def GetLists(self, user_id=None, screen_name=None):
result = [] cursor = (-1) while True: (next_cursor, prev_cursor, lists) = self.GetListsPaged(user_id=user_id, screen_name=screen_name, cursor=cursor) result += lists if ((next_cursor == 0) or (next_cursor == prev_cursor)): break else: cursor = next_cur...
'Update\'s the authenticated user\'s profile data. Args: name: Full name associated with the profile. Maximum of 20 characters. [Optional] profileURL: URL associated with the profile. Will be prepended with "http://" if not present. Maximum of 100 characters. [Optional] location: The city or country describing where th...
def UpdateProfile(self, name=None, profileURL=None, location=None, description=None, profile_link_color=None, include_entities=False, skip_status=False):
url = ('%s/account/update_profile.json' % self.base_url) data = {} if name: data['name'] = name if profileURL: data['url'] = profileURL if location: data['location'] = location if description: data['description'] = description if profile_link_color: da...
'Deprecated function. Used to update the background of a User\'s Twitter profile. Removed in approx. July, 2015'
def UpdateBackgroundImage(self, image, tile=False, include_entities=False, skip_status=False):
warnings.warn('This method has been deprecated by Twitter as of July 2015 and will be removed in future versions of python-twitter.', PythonTwitterDeprecationWarning330) url = ('%s/account/update_profile_background_image.json' % self.base_url) with op...
'Update a User\'s profile image. Change may not be immediately reflected due to image processing on Twitter\'s side. Args: image (str): Location of local image file to use. include_entities (bool, optional): Include the entities node in the return data. skip_status (bool, optional): Include the User\'s last Status in t...
def UpdateImage(self, image, include_entities=False, skip_status=False):
url = ('%s/account/update_profile_image.json' % self.base_url) with open(image, 'rb') as image_file: encoded_image = base64.b64encode(image_file.read()) data = {'image': encoded_image} if include_entities: data['include_entities'] = 1 if skip_status: data['skip_status'] = 1 ...
'Updates the authenticated users profile banner. Args: image: Location of image in file system 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 ...
def UpdateBanner(self, image, include_entities=False, skip_status=False):
url = ('%s/account/update_profile_banner.json' % self.base_url) with open(image, 'rb') as image_file: encoded_image = base64.b64encode(image_file.read()) data = {'banner': encoded_image} if include_entities: data['include_entities'] = 1 if skip_status: data['skip_status'] = 1...
'Returns a small sample of public statuses. Args: delimited: Specifies a message length. [Optional] stall_warnings: Set to True to have Twitter deliver stall warnings. [Optional] Returns: A Twitter stream'
def GetStreamSample(self, delimited=False, stall_warnings=True):
url = ('%s/statuses/sample.json' % self.stream_url) parameters = {'delimited': bool(delimited), 'stall_warnings': bool(stall_warnings)} resp = self._RequestStream(url, 'GET', data=parameters) for line in resp.iter_lines(): if line: data = self._ParseAndCheckTwitter(line.decode('utf-8...
'Returns a filtered view of public statuses. Args: follow: A list of user IDs to track. [Optional] track: A list of expressions to track. [Optional] locations: A list of Longitude,Latitude pairs (as strings) specifying bounding boxes for the tweets\' origin. [Optional] delimited: Specifies a message length. [Optional] ...
def GetStreamFilter(self, follow=None, track=None, locations=None, languages=None, delimited=None, stall_warnings=None, filter_level=None):
if all(((follow is None), (track is None), (locations is None))): raise ValueError({'message': 'No filter parameters specified.'}) url = ('%s/statuses/filter.json' % self.stream_url) data = {} if (follow is not None): data['follow'] = ','.join(follow) if (track is not None):...
'Returns the data from the user stream. Args: replies: Specifies whether to return additional @replies in the stream. Defaults to \'all\'. withuser: Specifies whether to return information for just the authenticating user, or include messages from accounts the user follows. [Optional] track: A list of expressions to tr...
def GetUserStream(self, replies='all', withuser='user', track=None, locations=None, delimited=None, stall_warnings=None, stringify_friend_ids=False, filter_level=None):
url = 'https://userstream.twitter.com/1.1/user.json' data = {} if stringify_friend_ids: data['stringify_friend_ids'] = 'true' if (replies is not None): data['replies'] = replies if (withuser is not None): data['with'] = withuser if (track is not None): data['track...
'Returns a twitter.User instance if the authenticating user is valid. Args: include_entities: Specifies whether to return additional @replies in the stream. skip_status: When set to either true, t or 1 statuses will not be included in the returned user object. include_email: Use of this parameter requires whitelisting....
def VerifyCredentials(self, include_entities=None, skip_status=None, include_email=None):
url = ('%s/account/verify_credentials.json' % self.base_url) data = {'include_entities': enf_type('include_entities', bool, include_entities), 'skip_status': enf_type('skip_status', bool, skip_status), 'include_email': enf_type('include_email', bool, include_email)} resp = self._RequestUrl(url, 'GET', 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 strin...
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...
def SetSource(self, source):
self._default_params['source'] = source
'Make a call to the Twitter API to get the rate limit status for the currently authenticated user or application. Returns: None.'
def InitializeRateLimit(self):
_sleep = self.sleep_on_rate_limit if self.sleep_on_rate_limit: self.sleep_on_rate_limit = False url = ('%s/application/rate_limit_status.json' % self.base_url) resp = self._RequestUrl(url, 'GET') data = self._ParseAndCheckTwitter(resp.content.decode('utf-8')) self.sleep_on_rate_limit = _...
'Checks a URL to see the rate limit status for that endpoint. Args: url (str): URL to check against the current rate limits. Returns: namedtuple: EndpointRateLimit namedtuple.'
def CheckRateLimit(self, url):
if (not self.rate_limit.__dict__.get('resources', None)): self.InitializeRateLimit() if url: limit = self.rate_limit.get_limit(url) return limit
'Return a string in key=value&key=value form. Values of None are not included in the output string. Args: parameters (dict): dictionary of query parameters to be converted into a string for encoding and sending to Twitter. Returns: A URL-encoded string in "key=value&key=value" form'
@staticmethod def _EncodeParameters(parameters):
if (parameters is None): return None if (not isinstance(parameters, dict)): raise TwitterError('`parameters` must be a dict.') else: return urlencode(dict(((k, v) for (k, v) in parameters.items() if (v is not None))))
'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_data):
try: data = json.loads(json_data) except ValueError: if ('<title>Twitter / Over capacity</title>' in json_data): raise TwitterError({'message': 'Capacity Error'}) if ('<title>Twitter / Error</title>' in json_data): raise TwitterError({'message': ...
'Raises a TwitterError if twitter returns an error message. Args: data (dict): A python dict created from the Twitter json response Raises: (twitter.TwitterError): TwitterError wrapping the twitter error message if one exists.'
@staticmethod def _CheckForTwitterError(data):
if ('error' in data): raise TwitterError(data['error']) if ('errors' in data): raise TwitterError(data['errors'])
'Request a url. Args: url: The web location we want to retrieve. verb: Either POST or GET. data: A dict of (str, unicode) key/value pairs. Returns: A JSON object.'
def _RequestUrl(self, url, verb, data=None, json=None, enforce_auth=True):
if enforce_auth: if (not self.__auth): raise TwitterError('The twitter.Api instance must be authenticated.') if (url and self.sleep_on_rate_limit): limit = self.CheckRateLimit(url) if (limit.remaining == 0): try: ...
'Request a stream of data. Args: url: The web location we want to retrieve. verb: Either POST or GET. data: A dict of (str, unicode) key/value pairs. Returns: A twitter stream.'
def _RequestStream(self, url, verb, data=None):
if (verb == 'POST'): try: return requests.post(url, data=data, stream=True, auth=self.__auth, timeout=self._timeout, proxies=self.proxies) except requests.RequestException as e: raise TwitterError(str(e)) if (verb == 'GET'): url = self._BuildUrl(url, extra_params=...
'timeline_owner : twitter handle of user account. tweet - 140 chars from feed; object does all computation on construction properties: RT, MT - boolean URLs - list of URL Hashtags - list of tags'
def __init__(self, timeline_owner, tweet):
self.Owner = timeline_owner self.tweet = tweet self.UserHandles = ParseTweet.getUserHandles(tweet) self.Hashtags = ParseTweet.getHashtags(tweet) self.URLs = ParseTweet.getURLs(tweet) self.RT = ParseTweet.getAttributeRT(tweet) self.MT = ParseTweet.getAttributeMT(tweet) self.Emoticon = Par...
'for display method'
def __str__(self):
return ('owner %s, urls: %d, hashtags %d, user_handles %d, len_tweet %d, RT = %s, MT = %s' % (self.Owner, len(self.URLs), len(self.Hashtags), len(self.UserHandles), len(self.tweet), self.RT, self.MT))
'see if tweet is contains any emoticons, +ve, -ve or neutral'
@staticmethod def getAttributeEmoticon(tweet):
emoji = list() for tok in re.split(ParseTweet.regexp['SPACES'], tweet.strip()): if (tok in Emoticons.POSITIVE): emoji.append(tok) continue if (tok in Emoticons.NEGATIVE): emoji.append(tok) return emoji
'see if tweet is a RT'
@staticmethod def getAttributeRT(tweet):
return (re.search(ParseTweet.regexp['RT'], tweet.strip()) is not None)
'see if tweet is a MT'
@staticmethod def getAttributeMT(tweet):
return (re.search(ParseTweet.regexp['MT'], tweet.strip()) is not None)
'given a tweet we try and extract all user handles in order of occurrence'
@staticmethod def getUserHandles(tweet):
return re.findall(ParseTweet.regexp['ALNUM'], tweet)
'return all hashtags'
@staticmethod def getHashtags(tweet):
return re.findall(ParseTweet.regexp['HASHTAG'], tweet)
'URL : [http://]?[\w\.?/]+'
@staticmethod def getURLs(tweet):
return re.findall(ParseTweet.regexp['URL'], tweet)
'Instantiate a new ShortenURL object. TinyURL, which is used for this example, does not require a userid or password, so you can try this out without specifying either. Args: userid: userid for any required authorization call [optional] password: password for any required authorization call [optional]'
def __init__(self, userid=None, password=None):
self.userid = userid self.password = password
'Call TinyURL API and returned shortened URL result. Args: long_url: URL string to shorten Returns: The shortened URL as a string Note: long_url is required and no checks are made to ensure completeness'
def Shorten(self, long_url):
result = None f = urlopen('http://tinyurl.com/api-create.php?url={0}'.format(long_url)) try: result = f.read() finally: f.close() if isinstance(result, bytes): return result.decode('utf8') else: return result
'Returns True if the user is superadmin and is active'
def has_perm(self, perm, obj=None):
return (self.is_active and self.is_superuser)
'Returns True if the user is superadmin and is active'
def has_perms(self, perm_list, obj=None):
return (self.is_active and self.is_superuser)