Skip to content
This repository was archived by the owner on Aug 7, 2024. It is now read-only.

Adding Collections #261

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions twitter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,5 @@
from status import Status
from user import User, UserStatus
from list import List
from collection import Collection
from api import Api
238 changes: 237 additions & 1 deletion twitter/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import StringIO

from twitter import (__version__, _FileCache, simplejson, DirectMessage, List,
Status, Trend, TwitterError, User)
Collection, Status, Trend, TwitterError, User)

CHARACTER_LIMIT = 140

Expand Down Expand Up @@ -2434,6 +2434,56 @@ def GetListsList(self,
data = self._ParseAndCheckTwitter(json.content)
return [List.NewFromJsonDict(x) for x in data]


def GetList(self,
list_id,
slug,
owner_id=None,
owner_screen_name=None):

'''Returns a single list, specified by the id parameter.

The twitter.Api instance must be authenticated.

Args:
list_id:
Specifies the ID of the list to retrieve.
slug:
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.
hashtags. [Optional]
Returns:
A twitter.List instance representing that list
'''
url = '%s/lists/show.json' % (self.base_url)

if not self.__auth:
raise TwitterError("API must be authenticated.")

parameters = { 'slug': slug,
'list_id': list_id,
}
url = '%s/lists/show.json' % (self.base_url)

parameters['slug'] = slug
parameters['list_id'] = list_id

if list_id is None:
if slug is None:
raise TwitterError('list_id or slug required')
if owner_id is None and not owner_screen_name:
raise TwitterError('if list_id is not given you have to include an owner to help identify the proper list')

if owner_id:
parameters['owner_id'] = owner_id
if owner_screen_name:
parameters['owner_screen_name'] = owner_screen_name

json = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(json.content)

return List.NewFromJsonDict(data)

def GetListTimeline(self,
list_id,
slug,
Expand Down Expand Up @@ -3058,6 +3108,192 @@ def GetUserStream(self, replies='all', withuser='user', track=None, locations=No
data = simplejson.loads(line)
yield data

def GetCollections(self, user_id=None, screen_name=None, count=None, cursor=-1):
'''Fetch collections 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.Collection instances, one for each list
'''
if not self.__auth:
raise TwitterError("twitter.Api instance must be authenticated")

url = '%s/collections/list.json' % self.base_url
result = []
parameters = {}
if user_id is not None:
try:
parameters['user_id'] = long(user_id)
except ValueError:
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._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(json.content)
if data['objects'].get('timelines', None):
result += [Collection.NewFromJsonDict(x, y) for x,y in data['objects']['timelines'].iteritems()]
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

def CreateCollection(self, name, description=None):
'''Creates a new collection with the give name for the authenticated user.

The twitter.Api instance must be authenticated.

Args:
name:
New name for the collection
description:
Description of the collection. [Optional]

Returns:
A twitter.Collection instance representing the new list
'''
url = '%s/collections/create.json' % self.base_url

if not self.__auth:
raise TwitterError("The twitter.Api instance must be authenticated.")
data = {'name': name}
if description is not None:
data['description'] = description

json = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(json.content)
return [Collection.NewFromJsonDict(x, y) for x,y in data['objects']['timelines'].iteritems()][0]

def DestroyCollection(self, id, trim_user=False):
'''Destroys the collection 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 collection you're trying to destroy.

Returns:
A twitter.Collection instance representing the destroyed collection
'''
if not self.__auth:
raise TwitterError("API must be authenticated.")

try:
post_data = {'id': id}
except ValueError:
raise TwitterError("id must be an integer")
url = '%s/collections/destroy.json?id=%s' % (self.base_url, id)
if trim_user:
post_data['trim_user'] = 1
json = self._RequestUrl(url, 'POST', data=post_data)
data = self._ParseAndCheckTwitter(json.content)

return data

def GetCollectionsEntries(self, id, count=None):
'''Fetch collections for a user.

The twitter.Api instance must be authenticated.

Args:
id:
The ID of Collection to return results for.
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]

Returns:
A sequence of XXX instances, one for each list
'''
if not self.__auth:
raise TwitterError("twitter.Api instance must be authenticated")

url = '%s/collections/entries.json' % self.base_url
result = []
parameters = {}
if id is not None:
try:
parameters['id'] = id
except ValueError:
raise TwitterError('user_id must be an integer')
else:
raise TwitterError('Specify id')
if count is not None:
parameters['count'] = count

cursor = None
while True:
parameters['cursor'] = cursor
json = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(json.content)

if data['response'].get('timeline', None):
result += [int(x['tweet']['id']) for x in data['response']['timeline']]

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

def AddToCollection(self, collection, tweet):
'''Add tweet to collection

The twitter.Api instance must be authenticated.

Args:
collection:
id of collection
tweet:
id of tweet

Returns:
A response object
'''
url = '%s/collections/entries/add.json' % self.base_url

if not self.__auth:
raise TwitterError("The twitter.Api instance must be authenticated.")
data = {'id': collection, 'tweet_id': tweet}

json = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(json.content)
return data

def VerifyCredentials(self):
'''Returns a twitter.User instance if the authenticating user is valid.

Expand Down
Loading