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

5
6
7
import os
import mimetypes

Josh Roesslein's avatar
Josh Roesslein committed
8
9
from . binder import bind_api
from . error import TweepError
10
from . auth import BasicAuthHandler, OAuthHandler
Josh Roesslein's avatar
Josh Roesslein committed
11
from tweepy.parsers import *
12

13
"""Twitter API"""
14
15
class API(object):

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

26
27
28
    # not a good idea to touch these
    self._username = None

29
30
31
32
33
34
35
36
37
  @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')

38
  """Get public timeline"""
39
40
  public_timeline = bind_api(
      path = '/statuses/public_timeline.json',
41
42
43
44
45
46
47
48
49
50
51
      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
  )
52
53
54
55
56
57
58
59
60

  """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
61
62
63
64
65
66
67
68
  """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
69
70
71
72
73
74
75
  """Show status"""
  get_status = bind_api(
      path = '/statuses/show.json',
      parser = parse_status,
      allowed_param = ['id']
  )

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
  """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
  )

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

101
102
  """Get authenticated user"""
  def me(self):
103
104
105
106
107
108
109
110
111
112
113
114
    # 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)
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  """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
  )

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
162
163
164
  """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
  )

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
  """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',
186
      parser = parse_json,
187
188
189
190
191
192
193
194
195
196
197
      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']
  )

198
199
200
  """Get list of IDs of users the specified user is following"""
  friends_ids = bind_api(
      path = '/friends/ids.json',
201
      parser = parse_json,
202
203
204
205
206
207
      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',
208
      parser = parse_json,
209
210
211
      allowed_param = ['id', 'user_id', 'screen_name', 'page']
  )

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

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

  """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
  )

248
249
  """Update profile image"""
  def update_profile_image(self, filename):
250
    headers, post_data = _pack_image(filename, 700)
251
252
253
    bind_api(
        path = '/account/update_profile_image.json',
        method = 'POST',
254
        parser = parse_none,
255
        require_auth = True
256
    )(self, post_data=post_data, headers=headers)
257
258

  """Update profile background image"""
259
  def update_profile_background_image(self, filename, *args, **kargs):
260
    headers, post_data = _pack_image(filename, 800)
261
262
263
    bind_api(
        path = '/account/update_profile_background_image.json',
        method = 'POST',
264
265
        parser = parse_none,
        allowed_param = ['tile'],
266
        require_auth = True
267
    )(self, post_data=post_data, headers=headers)
268
269
270
271
272
273
274
275
276
277

  """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
  )

278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
  """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
  )
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320

  """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
  )

321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
  """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):
341
342
343
344
345
346
347
348
349
350
    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
351

352
353
354
355
356
357
358
359
  """Get list of users that are blocked"""
  blocks = bind_api(
      path = '/blocks/blocking.json',
      parser = parse_users,
      allowed_param = ['page'],
      require_auth = True
  )

360
  """Get list of ids of users that are blocked"""
361
362
  blocks_ids = bind_api(
      path = '/blocks/blocking/ids.json',
363
      parser = parse_json,
364
365
366
      require_auth = True
  )

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
396
397
398
399
400
  """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)

401
402
403
404
405
406
  def test(self):
    return bind_api(
        path = '/help/test.json',
        parser = parse_return_true
    )(self)

Josh Roesslein's avatar
Josh Roesslein committed
407
408
409
410
411
412
413
414
415
416
  """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)

417
418
419
420
421
422
423
  def trends(self):
    return bind_api(
        host = 'search.' + self.host,
        path = '/trends.json',
        parser = parse_trend_results
    )(self)

Josh Roesslein's avatar
Josh Roesslein committed
424
425

""" Pack image file into multipart-formdata request"""
426
427
428
429
430
431
432
433
434
435
436
437
438
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')
439
440
441
  file_type = file_type[0]
  if file_type != 'image/gif' and file_type != 'image/jpeg' and file_type != 'image/png':
    raise TweepError('Invalid file type for image: %s' % file_type)
442
443
444

  # build the mulitpart-formdata body
  fp = open(filename, 'rb')
445
  BOUNDARY = 'Tw3ePy'
446
447
448
449
450
451
452
453
454
  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()
455
  body = '\r\n'.join(body)
456

457
458
459
460
461
462
463
  # build headers
  headers = {
    'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
    'Content-Length': len(body)
  }

  return headers, body
464