api.py 15.8 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

Josh Roesslein's avatar
Josh Roesslein committed
13

14
class API(object):
Josh Roesslein's avatar
Josh Roesslein committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    """Twitter API"""

    def __init__(self, auth_handler=None, host='twitter.com', cache=None,
            secure=False, api_root='', validate=True):
        # you may access these freely
        self.auth_handler = auth_handler
        self.host = host
        self.api_root = api_root
        self.cache = cache
        self.secure = secure
        self.validate = validate

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

    @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')

    """Get public timeline"""
    public_timeline = bind_api(
        path = '/statuses/public_timeline.json',
        parser = parse_statuses,
        allowed_param = []
    )

Josh Roesslein's avatar
Josh Roesslein committed
46
47
48
49
50
51
52
53
    """Get home timeline"""
    home_timeline = bind_api(
        path = '/statuses/home_timeline.json',
        parser = parse_statuses,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

Josh Roesslein's avatar
Josh Roesslein committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    """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
    )

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

    """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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    """Get Retweets posted by user"""
    retweeted_by_me = bind_api(
        path = '/statuses/retweeted_by_me.json',
        parser = parse_statuses,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

    """Get Retweets posted by user's friends"""
    retweeted_to_me = bind_api(
        path = '/statuses/retweeted_to_me.json',
        parser = parse_statuses,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

    """Get Retweets of the user's tweets posted by others"""
    retweets_of_me = bind_api(
        path = '/statuses/retweets_of_me.json',
        parser = parse_statuses,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

Josh Roesslein's avatar
Josh Roesslein committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
    """Show status"""
    get_status = bind_api(
        path = '/statuses/show.json',
        parser = parse_status,
        allowed_param = ['id']
    )

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

Josh Roesslein's avatar
Josh Roesslein committed
127
128
129
130
131
132
133
134
135
    """Retweet a tweet"""
    retweet = bind_api(
        path = '/statuses/retweet/id.json',
        method = 'POST',
        parser = parse_status,
        allowed_param = ['id'],
        require_auth = True
    )

136
137
138
139
140
141
142
143
144
    """Get the retweets of the specified tweet ID"""
    def retweets(self, id, *args, **kargs):
        return bind_api(
            path = '/statuses/retweets/%s.json' % id,
            parser = parse_retweets,
            allowed_param = ['count'],
            require_auth = True
        )(self, *args, **kargs)

Josh Roesslein's avatar
Josh Roesslein committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    """Show user"""
    get_user = bind_api(
        path = '/users/show.json',
        parser = parse_user,
        allowed_param = ['id', 'user_id', 'screen_name']
    )

    """Get authenticated user"""
    def me(self):
        # 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)

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

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

Josh Roesslein's avatar
Josh Roesslein committed
202
203
204
    """Send direct message"""
    send_direct_message = bind_api(
        path = '/direct_messages/new.json',
205
        method = 'POST',
Josh Roesslein's avatar
Josh Roesslein committed
206
207
        parser = parse_dm,
        allowed_param = ['user', 'text'],
208
        require_auth = True
Josh Roesslein's avatar
Josh Roesslein committed
209
    )
210

Josh Roesslein's avatar
Josh Roesslein committed
211
212
213
214
215
216
217
218
219
220
221
222
    """Destroy direct message"""
    destroy_direct_message = bind_api(
        path = '/direct_messages/destroy.json',
        method = 'DELETE',
        parser = parse_dm,
        allowed_param = ['id'],
        require_auth = True
    )

    """Create friendship"""
    create_friendship = bind_api(
        path = '/friendships/create.json',
223
        method = 'POST',
Josh Roesslein's avatar
Josh Roesslein committed
224
225
        parser = parse_user,
        allowed_param = ['id', 'user_id', 'screen_name', 'follow'],
226
        require_auth = True
Josh Roesslein's avatar
Josh Roesslein committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
    )

    """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',
        parser = parse_json,
        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']
    )

    """Get list of IDs of users the specified user is following"""
    friends_ids = bind_api(
        path = '/friends/ids.json',
        parser = parse_json,
        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',
        parser = parse_json,
        allowed_param = ['id', 'user_id', 'screen_name', 'page']
    )

    """Verify credentials"""
    def verify_credentials(self):
        try:
            return bind_api(
                path = '/account/verify_credentials.json',
                parser = parse_return_true,
                require_auth = True
            )(self)
        except TweepError:
            return False

    """Rate limit status"""
    rate_limit_status = bind_api(
        path = '/account/rate_limit_status.json',
        parser = parse_json
    )

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

    """Update profile image"""
    def update_profile_image(self, filename):
        headers, post_data = _pack_image(filename, 700)
        bind_api(
            path = '/account/update_profile_image.json',
            method = 'POST',
            parser = parse_none,
            require_auth = True
        )(self, post_data=post_data, headers=headers)

    """Update profile background image"""
    def update_profile_background_image(self, filename, *args, **kargs):
        headers, post_data = _pack_image(filename, 800)
        bind_api(
            path = '/account/update_profile_background_image.json',
            method = 'POST',
            parser = parse_none,
            allowed_param = ['tile'],
            require_auth = True
        )(self, post_data=post_data, headers=headers)

    """Update profile"""
    update_profile = bind_api(
        path = '/account/update_profile.json',
        method = 'POST',
        parser = parse_user,
        allowed_param = ['name', 'email', 'url', 'location', 'description'],
331
        require_auth = True
Josh Roesslein's avatar
Josh Roesslein committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
    )

    """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',
353
        method = 'DELETE',
Josh Roesslein's avatar
Josh Roesslein committed
354
        parser = parse_status,
355
356
        allowed_param = ['id'],
        require_auth = True
Josh Roesslein's avatar
Josh Roesslein committed
357
358
359
360
361
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    )

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

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

    """Get list of users that are blocked"""
    blocks = bind_api(
        path = '/blocks/blocking.json',
        parser = parse_users,
        allowed_param = ['page'],
        require_auth = True
    )

    """Get list of ids of users that are blocked"""
    blocks_ids = bind_api(
        path = '/blocks/blocking/ids.json',
        parser = parse_json,
        require_auth = True
    )

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

    def test(self):
        return bind_api(
            path = '/help/test.json',
            parser = parse_return_true
        )(self)

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

    def trends(self):
        return bind_api(
            host = 'search.' + self.host,
            path = '/trends.json',
478
            parser = parse_json
Josh Roesslein's avatar
Josh Roesslein committed
479
480
        )(self)

481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
    def trends_current(self, *args, **kargs):
        return bind_api(
            host = 'search.' + self.host,
            path = '/trends/current.json',
            parser = parse_json,
            allowed_param = ['exclude']
        )(self, *args, **kargs)

    def trends_daily(self, *args, **kargs):
        return bind_api(
            host = "search." + self.host,
            path = '/trends/daily.json',
            parser = parse_json,
            allowed_param = ['date', 'exclude']
        )(self, *args, **kargs)

    def trends_weekly(self, *args, **kargs):
        return bind_api(
            host = "search." + self.host,
            path = '/trends/weekly.json',
            parser = parse_json,
            allowed_param = ['date', 'exclude']
        )(self, *args, **kargs)

Josh Roesslein's avatar
Josh Roesslein committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
    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')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise TweepError('Invalid file type for image: %s' % file_type)

        # 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()
        body = '\r\n'.join(body)

        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
            'Content-Length': len(body)
        }

        return headers, body
543