api.py 12 KB
Newer Older
1
2
3
4
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE

Josh Roesslein's avatar
Josh Roesslein committed
5
6
7
from . binder import bind_api
from . parsers import *
from . error import TweepError
8
from . auth import BasicAuthHandler, OAuthHandler
9

10
"""Twitter API"""
11
12
class API(object):

13
  def __init__(self, auth_handler=None, host='twitter.com', cache=None,
14
                secure=False, api_root='', validate=True):
15
    # you may access these freely
16
    self.auth_handler = auth_handler
17
    self.host = host
18
    self.api_root = api_root
19
    self.cache = cache
20
    self.secure = secure
21
    self.validate = validate
22

23
24
25
    # not a good idea to touch these
    self._username = None

26
27
28
29
30
31
32
33
34
  @staticmethod
  def new(auth='basic', *args, **kargs):
    if auth == 'basic':
      return API(BasicAuthHandler(*args, **kargs))
    elif auth == 'oauth':
      return API(OAuthHandler(*args, **kargs))
    else:
      raise TweepError('Invalid auth type')

35
  """Get public timeline"""
36
37
  public_timeline = bind_api(
      path = '/statuses/public_timeline.json',
38
39
40
41
42
43
44
45
46
47
48
      parser = parse_statuses,
      allowed_param = []
  )

  """Get friends timeline"""
  friends_timeline = bind_api(
      path = '/statuses/friends_timeline.json',
      parser = parse_statuses,
      allowed_param = ['since_id', 'max_id', 'count', 'page'],
      require_auth = True
  )
49
50
51
52
53
54
55
56
57

  """Get user timeline"""
  user_timeline = bind_api(
      path = '/statuses/user_timeline.json',
      parser = parse_statuses,
      allowed_param = ['id', 'user_id', 'screen_name', 'since_id',
                        'max_id', 'count', 'page']
  )

Josh Roesslein's avatar
Josh Roesslein committed
58
59
60
61
62
63
64
65
  """Get mentions"""
  mentions = bind_api(
      path = '/statuses/mentions.json',
      parser = parse_statuses,
      allowed_param = ['since_id', 'max_id', 'count', 'page'],
      require_auth = True
  )

Josh Roesslein's avatar
Josh Roesslein committed
66
67
68
69
70
71
72
  """Show status"""
  get_status = bind_api(
      path = '/statuses/show.json',
      parser = parse_status,
      allowed_param = ['id']
  )

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  """Update status"""
  update_status = bind_api(
      path = '/statuses/update.json',
      method = 'POST',
      parser = parse_status,
      allowed_param = ['status', 'in_reply_to_status_id'],
      require_auth = True
  )

  """Destroy status"""
  destroy_status = bind_api(
      path = '/statuses/destroy.json',
      method = 'DELETE',
      parser = parse_status,
      allowed_param = ['id'],
      require_auth = True
  )

91
92
93
94
95
96
97
  """Show user"""
  get_user = bind_api(
      path = '/users/show.json',
      parser = parse_user,
      allowed_param = ['id', 'user_id', 'screen_name']
  )

98
99
  """Get authenticated user"""
  def me(self):
100
101
102
103
104
105
106
107
108
109
110
111
    # if username not fetched, go get it...
    if self._username is None:
      if self.auth_handler is None:
        raise TweepError('Authentication required')

      try:
        user = bind_api(path='/account/verify_credentials.json', parser=parse_user)(self)
      except TweepError, e:
        raise TweepError('Failed to fetch username: %s' % e)
      self._username = user.screen_name

    return self.get_user(screen_name=self._username)
112

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
  """Show friends"""
  friends = bind_api(
      path = '/statuses/friends.json',
      parser = parse_users,
      allowed_param = ['id', 'user_id', 'screen_name', 'page']
  )

  """Show followers"""
  followers = bind_api(
      path = '/statuses/followers.json',
      parser = parse_users,
      allowed_param = ['id', 'user_id', 'screen_name', 'page'],
      require_auth = True
  )

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
  """Get direct messages"""
  direct_messages = bind_api(
      path = '/direct_messages.json',
      parser = parse_directmessages,
      allowed_param = ['since_id', 'max_id', 'count', 'page'],
      require_auth = True
  )

  """Sent direct messages"""
  sent_direct_messages = bind_api(
      path = '/direct_messages/sent.json',
      parser = parse_directmessages,
      allowed_param = ['since_id', 'max_id', 'count', 'page'],
      require_auth = True
  )

  """Send direct message"""
  send_direct_message = bind_api(
      path = '/direct_messages/new.json',
      method = 'POST',
      parser = parse_dm,
      allowed_param = ['user', 'text'],
      require_auth = True
  )

  """Destroy direct message"""
  destroy_direct_message = bind_api(
      path = '/direct_messages/destroy.json',
      method = 'DELETE',
      parser = parse_dm,
      allowed_param = ['id'],
      require_auth = True
  )

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
  """Create friendship"""
  create_friendship = bind_api(
      path = '/friendships/create.json',
      method = 'POST',
      parser = parse_user,
      allowed_param = ['id', 'user_id', 'screen_name', 'follow'],
      require_auth = True
  )

  """Destroy friendship"""
  destroy_friendship = bind_api(
      path = '/friendships/destroy.json',
      method = 'DELETE',
      parser = parse_user,
      allowed_param = ['id', 'user_id', 'screen_name'],
      require_auth = True
  )

  """Check if friendship exists"""
  exists_friendship = bind_api(
      path = '/friendships/exists.json',
183
      parser = parse_json,
184
185
186
187
188
189
190
191
192
193
194
      allowed_param = ['user_a', 'user_b']
  )

  """Show friendship details"""
  show_friendship = bind_api(
      path = '/friendships/show.json',
      parser = parse_friendship,
      allowed_param = ['source_id', 'source_screen_name',
                        'target_id', 'target_screen_name']
  )

195
196
197
  """Get list of IDs of users the specified user is following"""
  friends_ids = bind_api(
      path = '/friends/ids.json',
198
      parser = parse_json,
199
200
201
202
203
204
      allowed_param = ['id', 'user_id', 'screen_name', 'page']
  )

  """Get list of IDs of users following the specified user"""
  followers_ids = bind_api(
      path = '/followers/ids.json',
205
      parser = parse_json,
206
207
208
      allowed_param = ['id', 'user_id', 'screen_name', 'page']
  )

209
  """Verify credentials"""
Josh Roesslein's avatar
Josh Roesslein committed
210
211
212
213
  def verify_credentials(self):
    try:
      return bind_api(
          path = '/account/verify_credentials.json',
214
          parser = parse_return_true,
Josh Roesslein's avatar
Josh Roesslein committed
215
216
217
          require_auth = True)(self)
    except TweepError:
      return False
218
219
220
221

  """Rate limit status"""
  rate_limit_status = bind_api(
      path = '/account/rate_limit_status.json',
222
      parser = parse_json
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
  )

  """Update delivery device"""
  set_delivery_device = bind_api(
      path = '/account/update_delivery_device.json',
      method = 'POST',
      allowed_param = ['device'],
      parser = parse_user,
      require_auth = True
  )

  """Update profile colors"""
  update_profile_colors = bind_api(
      path = '/account/update_profile_colors.json',
      method = 'POST',
      parser = parse_user,
      allowed_param = ['profile_background_color', 'profile_text_color',
                        'profile_link_color', 'profile_sidebar_fill_color',
                        'profile_sidebar_border_color'],
      require_auth = True
  )

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
  """Update profile image"""
  def update_profile_image(self, filename):
    bind_api(
        path = '/account/update_profile_image.json',
        method = 'POST',
        parser = parse_user,
        require_auth = True
    )(self, post_data = _pack_image(filename, 700))

  """Update profile background image"""
  def update_profile_image(self, filename, *args, **kargs):
    bind_api(
        path = '/account/update_profile_background_image.json',
        method = 'POST',
        parser = parse_user,
        allowed_param = ['tile']
        require_auth = True
    )(self, post_data = _pack_image(filename, 800))
263
264
265
266
267
268
269
270
271
272

  """Update profile"""
  update_profile = bind_api(
      path = '/account/update_profile.json',
      method = 'POST',
      parser = parse_user,
      allowed_param = ['name', 'email', 'url', 'location', 'description'],
      require_auth = True
  )

273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
  """Get favorites"""
  favorites = bind_api(
      path = '/favorites.json',
      parser = parse_statuses,
      allowed_param = ['id', 'page']
  )

  """Create favorite"""
  create_favorite = bind_api(
      path = '/favorites/create.json',
      method = 'POST',
      parser = parse_status,
      allowed_param = ['id'],
      require_auth = True
  )

  """Destroy favorite"""
  destroy_favorite = bind_api(
      path = '/favorites/destroy.json',
      method = 'DELETE',
      parser = parse_status,
      allowed_param = ['id'],
      require_auth = True
  )
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315

  """Enable device notifications"""
  enable_notifications = bind_api(
      path = '/notifications/follow.json',
      method = 'POST',
      parser = parse_user,
      allowed_param = ['id', 'user_id', 'screen_name'],
      require_auth = True
  )

  """Disable device notifications"""
  disable_notifications = bind_api(
      path = '/notifications/leave.json',
      method = 'POST',
      parser = parse_user,
      allowed_param = ['id', 'user_id', 'screen_name'],
      require_auth = True
  )

316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
  """Create a block"""
  create_block = bind_api(
      path = '/blocks/create.json',
      method = 'POST',
      parser = parse_user,
      allowed_param = ['id'],
      require_auth = True
  )

  """Destroy a block"""
  destroy_block = bind_api(
      path = '/blocks/destroy.json',
      method = 'DELETE',
      parser = parse_user,
      allowed_param = ['id'],
      require_auth = True
  )

  """Check if block exists"""
  def exists_block(self, **kargs):
336
337
338
339
340
341
342
343
344
345
    try:
      bind_api(
          path = '/blocks/exists.json',
          parser = parse_none,
          allowed_param = ['id', 'user_id', 'screen_name'],
          require_auth = True
    )(self, **kargs)
    except TweepError:
      return False
    return True
346

347
348
349
350
351
352
353
354
  """Get list of users that are blocked"""
  blocks = bind_api(
      path = '/blocks/blocking.json',
      parser = parse_users,
      allowed_param = ['page'],
      require_auth = True
  )

355
  """Get list of ids of users that are blocked"""
356
357
  blocks_ids = bind_api(
      path = '/blocks/blocking/ids.json',
358
      parser = parse_json,
359
360
361
      require_auth = True
  )

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
  """Get list of saved searches"""
  saved_searches = bind_api(
      path = '/saved_searches.json',
      parser = parse_saved_searches,
      require_auth = True
  )

  """Get a single saved search by id"""
  def get_saved_search(self, id):
    return bind_api(
        path = '/saved_searches/show/%s.json' % id,
        parser = parse_saved_search,
        require_auth = True
    )(self)

  """Create new saved search"""
  create_saved_search = bind_api(
      path = '/saved_searches/create.json',
      method = 'POST',
      parser = parse_saved_search,
      allowed_param = ['query'],
      require_auth = True
  )

  """Destroy a saved search"""
  def destroy_saved_search(self, id):
    return bind_api(
        path = '/saved_searches/destroy/%s.json' % id,
        method = 'DELETE',
        parser = parse_saved_search,
        allowed_param = ['id'],
        require_auth = True
    )(self)

396
397
398
399
400
401
  def test(self):
    return bind_api(
        path = '/help/test.json',
        parser = parse_return_true
    )(self)

Josh Roesslein's avatar
Josh Roesslein committed
402
403
404
405
406
407
408
409
410
411
  """Search API"""

  def search(self, *args, **kargs):
    return bind_api(
        host = 'search.' + self.host,
        path = '/search.json',
        parser = parse_search_results,
        allowed_param = ['q', 'lang', 'rpp', 'page', 'since_id', 'geocode', 'show_user'],
    )(self, *args, **kargs)

412
413
414
415
416
417
418
  def trends(self):
    return bind_api(
        host = 'search.' + self.host,
        path = '/trends.json',
        parser = parse_trend_results
    )(self)

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def _pack_image(filename, max_size):
  """Pack image from file into multipart-formdata post body"""
  # image must be less than 700kb in size
  try:
    if os.path.getsize(filename) > (max_size * 1024):
      raise TweepError('File is too big, must be less than 700kb.')
  except os.error, e:
      raise TweepError('Unable to access file')

  # image must be gif, jpeg, or png
  file_type = mimetypes.guess_type(filename)
  if file_type is None:
    raise TweepError('Could not determine file type')
  if file_type is not 'image/gif' and file_type is not 'image/jpeg'
      and file_type is not 'image/png':
    raise TweepError('Invalid file type for image')

  # build the mulitpart-formdata body
  fp = open(filename, 'rb')
  BOUNDARY = '--Tw3ePy'
  body = []
  body.append('--' + BOUNDARY)
  body.append('Content-Disposition: form-data; name="image"; filename="%s"' % filename)
  body.append('Content-Type: %s' % file_type)
  body.append('')
  body.append(fp.read())
  body.append('--' + BOUNDARY + '--')
  body.append('')
  fp.close()

  return '\r\n'.join(body)