api.py 33.5 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 tweepy.binder import bind_api
from tweepy.error import TweepError
Josh Roesslein's avatar
Josh Roesslein committed
10
from tweepy.parsers import *
11

Josh Roesslein's avatar
Josh Roesslein committed
12

13
class API(object):
Josh Roesslein's avatar
Josh Roesslein committed
14
15
16
    """Twitter API"""

    def __init__(self, auth_handler=None, host='twitter.com', cache=None,
Josh Roesslein's avatar
Josh Roesslein committed
17
            secure=False, api_root='',
18
            retry_count=0, retry_delay=0, retry_errors=None):
Josh Roesslein's avatar
Josh Roesslein committed
19
20
21
22
23
24
        # you may access these freely
        self.auth_handler = auth_handler
        self.host = host
        self.api_root = api_root
        self.cache = cache
        self.secure = secure
25
26
        self.retry_count = retry_count
        self.retry_delay = retry_delay
27
        self.retry_errors = retry_errors
Josh Roesslein's avatar
Josh Roesslein committed
28

29
30
31
32
33
34
35
36
37
38
39
    """ statuses/public_timeline

        Returns the 20 most recent statuses from non-protected users who
        have set a custom user icon. The public timeline is cached for 60 
        seconds so requesting it more often than that is a waste of resources.

        Parameters: None
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-public_timeline
	"""
Josh Roesslein's avatar
Josh Roesslein committed
40
41
42
43
44
45
    public_timeline = bind_api(
        path = '/statuses/public_timeline.json',
        parser = parse_statuses,
        allowed_param = []
    )

46
47
48
49
50
51
52
53
54
55
56
    """ statuses/home_timeline [Coming soon]

        Returns the 20 most recent statuses, including retweets, posted
        by the authenticating user and that user's friends. This is the
        equivalent of /timeline/home on the Web.

        Parameters: since_id, max_id, count, page
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-home_timeline
    """
Josh Roesslein's avatar
Josh Roesslein committed
57
58
59
60
61
62
63
    home_timeline = bind_api(
        path = '/statuses/home_timeline.json',
        parser = parse_statuses,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

64
65
66
67
68
69
70
71
72
73
    """ statuses/friends_timeline

        Returns the 20 most recent statuses posted by the
        authenticating user and that user's friends.

        Parameters: since_id, max_id, count, page
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-friends_timeline
    """
Josh Roesslein's avatar
Josh Roesslein committed
74
75
76
77
78
79
80
    friends_timeline = bind_api(
        path = '/statuses/friends_timeline.json',
        parser = parse_statuses,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

81
82
83
84
85
86
87
88
89
90
91
    """ statuses/user_timeline

        Returns the 20 most recent statuses posted from the
        authenticating user. It's also possible to request another
        user's timeline via the id parameter.

        Parameters: (id or user_id or screen_name), since_id, max_id, count, page
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-user_timeline
    """
Josh Roesslein's avatar
Josh Roesslein committed
92
93
94
95
96
97
98
    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']
    )

99
100
101
102
103
104
105
106
107
108
    """ statuses/mentions

        Returns the 20 most recent mentions (status containing @username)
        for the authenticating user.

        Parameters: since_id, max_id, count, page
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-mentions
    """
Josh Roesslein's avatar
Josh Roesslein committed
109
110
111
112
113
114
115
    mentions = bind_api(
        path = '/statuses/mentions.json',
        parser = parse_statuses,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

116
117
118
119
120
121
122
123
124
    """ statuses/retweeted_by_me [Coming soon]

        Returns the 20 most recent retweets posted by the authenticating user.

        Parameters: since_id, max_id, count, page
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-retweeted_by_me
    """
Josh Roesslein's avatar
Josh Roesslein committed
125
126
127
128
129
130
131
    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
    )

132
133
134
135
136
137
138
139
140
141
    """ statuses/retweeted_to_me

        Returns the 20 most recent retweets posted by the
        authenticating user's friends.

        Parameters: since_id, max_id, count, page
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-retweeted_to_me
    """
Josh Roesslein's avatar
Josh Roesslein committed
142
143
144
145
146
147
148
    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
    )

149
150
151
152
153
154
155
156
157
158
    """ statuses/retweets_of_me

        Returns the 20 most recent tweets of the authenticated
        user that have been retweeted by others.

        Parameters: since_id, max_id, count, page
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-retweets_of_me
    """
Josh Roesslein's avatar
Josh Roesslein committed
159
160
161
162
163
164
165
    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
    )

166
167
168
169
170
171
172
173
174
175
    """ statuses/show

        Returns a single status, specified by the id parameter below.
        The status's author will be returned inline.

        Parameters: id (Required)
        Returns: Status

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0show
    """
Josh Roesslein's avatar
Josh Roesslein committed
176
177
178
179
180
181
    get_status = bind_api(
        path = '/statuses/show.json',
        parser = parse_status,
        allowed_param = ['id']
    )

182
183
184
185
186
187
188
189
190
191
192
    """ statuses/update [Geolocation parameters coming soon]

        Updates the authenticating user's status.
        A status update with text identical to the authenticating user's
        current status will be ignored to prevent duplicates.

        Parameters: status (Required), in_reply_to_status_id, lat, long
        Returns: Status

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0update
    """
Josh Roesslein's avatar
Josh Roesslein committed
193
194
195
196
    update_status = bind_api(
        path = '/statuses/update.json',
        method = 'POST',
        parser = parse_status,
197
        allowed_param = ['status', 'in_reply_to_status_id', 'lat', 'long'],
Josh Roesslein's avatar
Josh Roesslein committed
198
199
200
        require_auth = True
    )

201
202
203
204
205
206
207
208
    """ statuses/destroy

        Destroys the status specified by the required ID parameter.
        The authenticating user must be the author of the specified status.

        Parameters: id (Required)
        Returns: Status
    """
Josh Roesslein's avatar
Josh Roesslein committed
209
210
211
212
213
214
215
216
    destroy_status = bind_api(
        path = '/statuses/destroy.json',
        method = 'DELETE',
        parser = parse_status,
        allowed_param = ['id'],
        require_auth = True
    )

217
218
219
220
221
222
223
224
225
226
    """ statuses/retweet [Coming soon]

        Retweets a tweet. Requires the id parameter of the tweet you are
        retweeting. Returns the original tweet with retweet details.

        Parameters: id (Required)
        Returns: Status

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-retweet
    """
Josh Roesslein's avatar
Josh Roesslein committed
227
228
229
230
231
232
233
234
    retweet = bind_api(
        path = '/statuses/retweet/id.json',
        method = 'POST',
        parser = parse_status,
        allowed_param = ['id'],
        require_auth = True
    )

235
236
237
238
239
240
241
242
243
    """ statuses/retweets [Coming soon]

        Returns up to 100 of the first retweets of a given tweet.

        Parameters: id (Required), count
        Returns: Retweet

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-retweets
    """
244
245
246
247
248
249
250
251
    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)

252
253
254
255
256
257
258
259
260
261
    """ users/show

        Returns extended information of a given user, specified by ID or
        screen name as per the required id parameter.

        Parameters: id or user_id or screen_name (One of these is required)
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-users%C2%A0show
    """
Josh Roesslein's avatar
Josh Roesslein committed
262
263
264
265
266
267
    get_user = bind_api(
        path = '/users/show.json',
        parser = parse_user,
        allowed_param = ['id', 'user_id', 'screen_name']
    )

268
269
270
271
272
273
274
275
276
    """ Get the authenticated user

        Equivalent of calling API.get_user(authenticated_user_name)

        Parameters: None
        Returns: User

        See: API.get_user()
    """
Josh Roesslein's avatar
Josh Roesslein committed
277
    def me(self):
Josh Roesslein's avatar
Josh Roesslein committed
278
        return self.get_user(screen_name=self.auth_handler.get_username())
Josh Roesslein's avatar
Josh Roesslein committed
279

280
281
282
283
284
285
286
287
288
289
290
    """ statuses/friends

        Returns a user's friends. They are ordered by the order in
        which they were added as friends, 100 at a time.
        (Please note that the result set isn't guaranteed to be 100
        every time as suspended users will be filtered out.)
        Use the page option to access older friends. With no user specified,
        request defaults to the authenticated user's friends. It's also
        possible to request another user's friends list via the id,
        screen_name or user_id parameter.

291
        Parameters: (id or user_id or screen_name), page (deprecated), cursor
292
293
294
295
        Returns: list[Users]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0friends
    """
Josh Roesslein's avatar
Josh Roesslein committed
296
297
298
    friends = bind_api(
        path = '/statuses/friends.json',
        parser = parse_users,
299
        allowed_param = ['id', 'user_id', 'screen_name', 'page', 'cursor']
Josh Roesslein's avatar
Josh Roesslein committed
300
301
    )

302
303
304
305
306
307
308
309
    """ statuses/followers

        Returns the authenticating user's followers.They are ordered by
        the order in which they joined Twitter, 100 at a time.
        (Please note that the result set isn't guaranteed to be 100 every
        time as suspended users will be filtered out.)
        Use the page option to access earlier followers.

310
        Parameters: (id or user_id or screen_name), page (deprecated), cursor
311
312
313
314
        Returns: list[User]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0followers
    """
Josh Roesslein's avatar
Josh Roesslein committed
315
316
317
    followers = bind_api(
        path = '/statuses/followers.json',
        parser = parse_users,
318
        allowed_param = ['id', 'user_id', 'screen_name', 'page', 'cursor']
Josh Roesslein's avatar
Josh Roesslein committed
319
320
    )

321
322
323
324
325
326
327
328
329
330
    """ direct_messages

        Returns a list of the 20 most recent direct messages sent
        to the authenticating user.

        Parameters: since_id, max_id, count, page
        Returns: list[DirectMessage]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-direct_messages
    """
Josh Roesslein's avatar
Josh Roesslein committed
331
332
333
334
335
336
337
    direct_messages = bind_api(
        path = '/direct_messages.json',
        parser = parse_directmessages,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )

338
339
340
341
342
343
344
345
346
347
    """ direct_messages/sent

        Returns a list of the 20 most recent direct messages sent
        by the authenticating user.

        Parameters: since_id, max_id, count, page
        Returns: list[DirectMessage]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-direct_messages%C2%A0sent
    """
Josh Roesslein's avatar
Josh Roesslein committed
348
349
350
351
352
353
    sent_direct_messages = bind_api(
        path = '/direct_messages/sent.json',
        parser = parse_directmessages,
        allowed_param = ['since_id', 'max_id', 'count', 'page'],
        require_auth = True
    )
354

355
356
357
358
359
360
361
362
363
364
    """ direct_messages/new

        Sends a new direct message to the specified user from
        the authenticating user.

        Parameters: user (Required), text (Required)
        Returns: DirectMessage

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-direct_messages%C2%A0new
    """
Josh Roesslein's avatar
Josh Roesslein committed
365
366
    send_direct_message = bind_api(
        path = '/direct_messages/new.json',
367
        method = 'POST',
Josh Roesslein's avatar
Josh Roesslein committed
368
369
        parser = parse_dm,
        allowed_param = ['user', 'text'],
370
        require_auth = True
Josh Roesslein's avatar
Josh Roesslein committed
371
    )
372

373
374
375
376
377
378
379
380
381
382
383
    """ direct_messages/destroy

        Destroys the direct message specified in the required ID parameter.
        The authenticating user must be the recipient of the
        specified direct message.

        Parameters: id (Required)
        Returns: DirectMessage

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-direct_messages%C2%A0destroy
    """
Josh Roesslein's avatar
Josh Roesslein committed
384
385
386
387
388
389
390
391
    destroy_direct_message = bind_api(
        path = '/direct_messages/destroy.json',
        method = 'DELETE',
        parser = parse_dm,
        allowed_param = ['id'],
        require_auth = True
    )

392
393
394
395
396
397
398
399
400
401
402
403
    """ friendships/create

        Allows the authenticating users to follow the user specified in
        the ID parameter.  Returns the befriended user when successful.

        Parameters:
            id or user_id or screen_name (One of these is required)
            follow
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-friendships%C2%A0create
    """
Josh Roesslein's avatar
Josh Roesslein committed
404
405
    create_friendship = bind_api(
        path = '/friendships/create.json',
406
        method = 'POST',
Josh Roesslein's avatar
Josh Roesslein committed
407
408
        parser = parse_user,
        allowed_param = ['id', 'user_id', 'screen_name', 'follow'],
409
        require_auth = True
Josh Roesslein's avatar
Josh Roesslein committed
410
411
    )

412
413
414
415
416
417
418
419
420
421
    """ friendships/destroy

        Allows the authenticating users to unfollow the user specified
        in the ID parameter.  Returns the unfollowed user when successful.

        Parameters: id or user_id or screen_name (One of these is required)
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-friendships%C2%A0destroy
    """
Josh Roesslein's avatar
Josh Roesslein committed
422
423
424
425
426
427
428
429
    destroy_friendship = bind_api(
        path = '/friendships/destroy.json',
        method = 'DELETE',
        parser = parse_user,
        allowed_param = ['id', 'user_id', 'screen_name'],
        require_auth = True
    )

430
431
432
433
434
435
436
437
438
    """ friendships/exists

        Tests for the existence of friendship between two users.

        Parameters: user_a (Required), user_b (Required)
        Returns: Boolean (True if user_a follows user_b, otherwise False)

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-friendships-exists
    """
Josh Roesslein's avatar
Josh Roesslein committed
439
440
441
442
443
444
    exists_friendship = bind_api(
        path = '/friendships/exists.json',
        parser = parse_json,
        allowed_param = ['user_a', 'user_b']
    )

445
446
447
448
449
450
451
452
453
454
455
    """ friendships/show

        Returns detailed information about the relationship between two users.

        Parameters:
            source_id or source_screen_name (One of these is required)
            target_id or target_screen_name (One of these is required)
        Returns: tuple(Friendship - source, Friendship - target)

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-friendships-show
    """
Josh Roesslein's avatar
Josh Roesslein committed
456
457
458
459
460
461
462
    show_friendship = bind_api(
        path = '/friendships/show.json',
        parser = parse_friendship,
        allowed_param = ['source_id', 'source_screen_name',
                          'target_id', 'target_screen_name']
    )

463
464
465
466
467
468
469
470
    """ friends/ids

        Returns an array of numeric IDs for every user the
        specified user is following.

        Parameters:
            id or user_id or screen_name (One of these is required)
            cursor
471
        Returns: list<int>
472
473
474

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-friends%C2%A0ids
    """
Josh Roesslein's avatar
Josh Roesslein committed
475
476
    friends_ids = bind_api(
        path = '/friends/ids.json',
477
        parser = parse_ids,
478
        allowed_param = ['id', 'user_id', 'screen_name', 'cursor']
Josh Roesslein's avatar
Josh Roesslein committed
479
480
    )

481
482
483
484
485
486
487
488
    """ followers/ids

        Returns an array of numeric IDs for every user following
        the specified user.

        Parameters:
            id or user_id or screen_name (One of these is required)
            cursor
489
        Returns: list<int>
490
491
492

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-followers%C2%A0ids
    """
Josh Roesslein's avatar
Josh Roesslein committed
493
494
    followers_ids = bind_api(
        path = '/followers/ids.json',
495
        parser = parse_ids,
496
        allowed_param = ['id', 'user_id', 'screen_name', 'cursor']
Josh Roesslein's avatar
Josh Roesslein committed
497
498
    )

499
500
501
502
503
504
505
506
507
508
509
510
    """ account/verify_credentials

        Use this method to test if supplied user credentials are valid.
        Because this method can be a vector for a brute force dictionary
        attack to determine a user's password, it is limited to 15 requests
        per 60 minute period (starting from your first request).

        Parameters: None
        Returns: True if credentials are valid, otherwise False

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0verify_credentials
    """
Josh Roesslein's avatar
Josh Roesslein committed
511
512
513
514
    def verify_credentials(self):
        try:
            return bind_api(
                path = '/account/verify_credentials.json',
Josh Roesslein's avatar
Josh Roesslein committed
515
                parser = parse_user,
Josh Roesslein's avatar
Josh Roesslein committed
516
517
518
519
520
                require_auth = True
            )(self)
        except TweepError:
            return False

521
522
523
524
525
526
527
528
529
530
531
532
533
534
    """ account/rate_limit_status

        Returns the remaining number of API requests available to the
        requesting user before the API limit is reached for the current hour.
        Calls to rate_limit_status do not count against the rate limit.
        If authentication credentials are provided, the rate limit status for
        the authenticating user is returned.  Otherwise, the rate limit status
        for the requester's IP address is returned.

        Parameters: None
        Returns: json object

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0rate_limit_status
    """
Josh Roesslein's avatar
Josh Roesslein committed
535
536
537
538
539
    rate_limit_status = bind_api(
        path = '/account/rate_limit_status.json',
        parser = parse_json
    )

540
541
542
543
544
545
546
547
548
549
550
    """ account/update_delivery_device

        Sets which device Twitter delivers updates to for the authenticating
        user.  Sending "none" as the device parameter will disable IM or SMS
        updates.

        Parameters: device (Required)
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0update_delivery_device
    """
Josh Roesslein's avatar
Josh Roesslein committed
551
552
553
554
555
556
557
558
    set_delivery_device = bind_api(
        path = '/account/update_delivery_device.json',
        method = 'POST',
        allowed_param = ['device'],
        parser = parse_user,
        require_auth = True
    )

559
560
561
562
563
564
565
566
567
568
569
570
    """ account/update_profile_colors

        Sets one or more hex values that control the color scheme of the
        authenticating user's profile page on twitter.com.

        Parameters: profile_background_color, profile_text_color,
            profile_link_color, profile_sidebar_fill_color,
            profile_sidebar_border_color
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0update_profile_colors
    """
Josh Roesslein's avatar
Josh Roesslein committed
571
572
573
574
575
576
577
578
579
580
    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
    )

581
582
583
584
585
586
587
588
589
590
    """ account/update_profile_image

        Updates the authenticating user's profile image.

        Parameters:
            filename - local file path to image (Required)
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0update_profile_image
    """
Josh Roesslein's avatar
Josh Roesslein committed
591
    def update_profile_image(self, filename):
Josh Roesslein's avatar
Josh Roesslein committed
592
        headers, post_data = API._pack_image(filename, 700)
Josh Roesslein's avatar
Josh Roesslein committed
593
        return bind_api(
Josh Roesslein's avatar
Josh Roesslein committed
594
595
            path = '/account/update_profile_image.json',
            method = 'POST',
Josh Roesslein's avatar
Josh Roesslein committed
596
            parser = parse_user,
Josh Roesslein's avatar
Josh Roesslein committed
597
598
599
            require_auth = True
        )(self, post_data=post_data, headers=headers)

600
601
602
603
604
605
606
607
608
609
610
    """ account/update_profile_background_image

        Updates the authenticating user's profile background image.

        Parameters:
            filename - local file path to image (Required)
            tile
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0update_profile_background_image
    """
Josh Roesslein's avatar
Josh Roesslein committed
611
    def update_profile_background_image(self, filename, *args, **kargs):
Josh Roesslein's avatar
Josh Roesslein committed
612
        headers, post_data = API._pack_image(filename, 800)
Josh Roesslein's avatar
Josh Roesslein committed
613
614
615
        bind_api(
            path = '/account/update_profile_background_image.json',
            method = 'POST',
Josh Roesslein's avatar
Josh Roesslein committed
616
            parser = parse_user,
Josh Roesslein's avatar
Josh Roesslein committed
617
618
619
620
            allowed_param = ['tile'],
            require_auth = True
        )(self, post_data=post_data, headers=headers)

621
622
623
624
625
    """ account/update_profile

        Sets values that users are able to set under the "Account" tab of
        their settings page. Only the parameters specified will be updated.

Josh Roesslein's avatar
Josh Roesslein committed
626
        Parameters: name, url, location, description
627
628
629
630
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0update_profile
    """
Josh Roesslein's avatar
Josh Roesslein committed
631
632
633
634
    update_profile = bind_api(
        path = '/account/update_profile.json',
        method = 'POST',
        parser = parse_user,
Josh Roesslein's avatar
Josh Roesslein committed
635
        allowed_param = ['name', 'url', 'location', 'description'],
636
        require_auth = True
Josh Roesslein's avatar
Josh Roesslein committed
637
638
    )

639
640
641
642
643
644
645
646
647
648
    """ favorites

        Returns the 20 most recent favorite statuses for the authenticating
        user or user specified by the ID parameter.

        Parameters: id, page
        Returns: list[Status]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-favorites
    """
Josh Roesslein's avatar
Josh Roesslein committed
649
650
651
652
653
654
    favorites = bind_api(
        path = '/favorites.json',
        parser = parse_statuses,
        allowed_param = ['id', 'page']
    )

655
656
657
658
659
660
661
662
663
664
    """ favorites/create

        Favorites the status specified in the ID parameter as the
        authenticating user. Returns the favorite status when successful.

        Parameters: id (Required)
        Returns: Status

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-favorites%C2%A0create
    """
665
666
667
668
669
670
671
672
    def create_favorite(self, id):
        return bind_api(
            path = '/favorites/create/%s.json' % id,
            method = 'POST',
            parser = parse_status,
            allowed_param = ['id'],
            require_auth = True
        )(self, id)
Josh Roesslein's avatar
Josh Roesslein committed
673

674
675
676
677
678
679
680
681
682
683
    """ favorites/destroy

        Un-favorites the status specified in the ID parameter as the
        authenticating user. Returns the un-favorited status.

        Parameters: id (Required)
        Returns: Status

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-favorites%C2%A0destroy
    """
684
685
686
687
688
689
690
691
    def destroy_favorite(self, id):
        return bind_api(
            path = '/favorites/destroy/%s.json' % id,
            method = 'DELETE',
            parser = parse_status,
            allowed_param = ['id'],
            require_auth = True
        )(self, id)
Josh Roesslein's avatar
Josh Roesslein committed
692

693
694
695
696
697
698
699
700
701
702
    """ notifications/follow

        Enables device notifications for updates from the specified user.
        Returns the specified user when successful.

        Parameters: id or user_id or screen_name (One of these is required)
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-notifications%C2%A0follow
    """
Josh Roesslein's avatar
Josh Roesslein committed
703
704
705
706
707
708
709
710
    enable_notifications = bind_api(
        path = '/notifications/follow.json',
        method = 'POST',
        parser = parse_user,
        allowed_param = ['id', 'user_id', 'screen_name'],
        require_auth = True
    )

711
712
713
714
715
716
717
718
719
720
    """ notifications/leave

        Disables notifications for updates from the specified user to the
        authenticating user.  Returns the specified user when successful.

        Parameters: id or user_id or screen_name (One of these is required)
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-notifications%C2%A0leave
    """
Josh Roesslein's avatar
Josh Roesslein committed
721
722
723
724
725
726
727
728
    disable_notifications = bind_api(
        path = '/notifications/leave.json',
        method = 'POST',
        parser = parse_user,
        allowed_param = ['id', 'user_id', 'screen_name'],
        require_auth = True
    )

729
730
731
732
733
734
735
736
737
738
739
    """ blocks/create

        Blocks the user specified in the ID parameter as the authenticating
        user. Destroys a friendship to the blocked user if it exists.
        Returns the blocked user when successful.

        Parameters: id (Required)
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-blocks%C2%A0create
    """
Josh Roesslein's avatar
Josh Roesslein committed
740
741
742
743
    create_block = bind_api(
        path = '/blocks/create.json',
        method = 'POST',
        parser = parse_user,
Josh Roesslein's avatar
Josh Roesslein committed
744
        allowed_param = ['id', 'user_id', 'screen_name'],
Josh Roesslein's avatar
Josh Roesslein committed
745
746
747
        require_auth = True
    )

748
749
750
751
752
753
754
755
756
757
    """ blocks/destroy

        Un-blocks the user specified in the ID parameter for the
        authenticating user. Returns the un-blocked user when successful.

        Parameters: id (Required)
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-blocks%C2%A0destroy
    """
Josh Roesslein's avatar
Josh Roesslein committed
758
759
760
761
    destroy_block = bind_api(
        path = '/blocks/destroy.json',
        method = 'DELETE',
        parser = parse_user,
Josh Roesslein's avatar
Josh Roesslein committed
762
        allowed_param = ['id', 'user_id', 'screen_name'],
Josh Roesslein's avatar
Josh Roesslein committed
763
764
765
        require_auth = True
    )

766
767
768
769
770
771
772
773
774
    """ blocks/exists

        Checks if the authenticating user is blocking a target user.

        Parameters: id or user_id or screen_name (One of these is required)
        Returns: Boolean (True if blocked, otherwise False)

        http://apiwiki.twitter.com/Twitter+REST+API+Method%3A-blocks-exists
    """
Josh Roesslein's avatar
Josh Roesslein committed
775
    def exists_block(self, *args, **kargs):
Josh Roesslein's avatar
Josh Roesslein committed
776
777
778
779
780
781
        try:
            bind_api(
                path = '/blocks/exists.json',
                parser = parse_none,
                allowed_param = ['id', 'user_id', 'screen_name'],
                require_auth = True
Josh Roesslein's avatar
Josh Roesslein committed
782
            )(self, *args, **kargs)
Josh Roesslein's avatar
Josh Roesslein committed
783
784
785
786
787
        except TweepError:
            return False

        return True

788
789
790
791
792
793
794
795
796
797
    """ blocks/blocking

        Returns an array of user objects that the authenticating
        user is blocking.

        Parameters: page
        Returns: list[User]

        http://apiwiki.twitter.com/Twitter+REST+API+Method%3A-blocks-blocking
    """
Josh Roesslein's avatar
Josh Roesslein committed
798
799
800
801
802
803
804
    blocks = bind_api(
        path = '/blocks/blocking.json',
        parser = parse_users,
        allowed_param = ['page'],
        require_auth = True
    )

805
806
807
808
809
810
811
812
813
814
    """ blocks/blocking/ids

        Returns an array of numeric user ids the authenticating
        user is blocking.

        Parameters: None
        Returns: json object

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-blocks-blocking-ids
    """
Josh Roesslein's avatar
Josh Roesslein committed
815
816
817
818
819
820
    blocks_ids = bind_api(
        path = '/blocks/blocking/ids.json',
        parser = parse_json,
        require_auth = True
    )

Josh Roesslein's avatar
Josh Roesslein committed
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
    """ report_spam

        The user specified in the id is blocked by the authenticated user
        and reported as a spammer.

        Parameters: id or user_id or screen_name
        Returns: User

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-report_spam
    """
    report_spam = bind_api(
        path = '/report_spam.json',
        method = 'POST',
        parser = parse_user,
        allowed_param = ['id', 'user_id', 'screen_name'],
        require_auth = True
    )

839
840
841
842
843
844
845
846
847
    """ saved_searches

        Returns the authenticated user's saved search queries.

        Parameters: None
        Returns: list[SavedSearch]

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-saved_searches
    """
Josh Roesslein's avatar
Josh Roesslein committed
848
849
850
851
852
853
    saved_searches = bind_api(
        path = '/saved_searches.json',
        parser = parse_saved_searches,
        require_auth = True
    )

854
855
856
857
858
859
860
861
862
863
    """ saved_searches/show

        Retrieve the data for a saved search owned by the
        authenticating user specified by the given id.

        Parameters: id (Required)
        Returns: SavedSearch

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-saved_searches-show
    """
Josh Roesslein's avatar
Josh Roesslein committed
864
865
866
867
868
869
870
    def get_saved_search(self, id):
        return bind_api(
            path = '/saved_searches/show/%s.json' % id,
            parser = parse_saved_search,
            require_auth = True
        )(self)

871
872
873
874
875
876
877
878
879
    """ saved_searches/create

        Creates a saved search for the authenticated user.

        Parameters: query (Required)
        Returns: SavedSearch

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-saved_searches-create
    """
Josh Roesslein's avatar
Josh Roesslein committed
880
881
882
883
884
885
886
887
    create_saved_search = bind_api(
        path = '/saved_searches/create.json',
        method = 'POST',
        parser = parse_saved_search,
        allowed_param = ['query'],
        require_auth = True
    )

888
889
890
891
892
893
894
895
896
897
    """ saved_searches/destroy

        Destroys a saved search for the authenticated user.
        The search specified by id must be owned by the authenticating user.

        Parameters: id (Required)
        Returns: SavedSearch

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-saved_searches-destroy
    """
Josh Roesslein's avatar
Josh Roesslein committed
898
899
900
901
902
903
904
905
906
    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)

907
908
909
910
911
912
913
914
915
    """ help/test

        Invokes the test method in the Twitter API.

        Parameters: None
        Returns: Boolean (True if 200 status code returned, otherwise False)

        http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-help%C2%A0test
    """
Josh Roesslein's avatar
Josh Roesslein committed
916
    def test(self):
917
918
919
920
921
922
923
924
        try:
            return bind_api(
                path = '/help/test.json',
                parser = parse_return_true
            )(self)
        except TweepError:
            return False

Josh Roesslein's avatar
Josh Roesslein committed
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
    """ Create list

        Creates a new list for the authenticated user.

        Parameters: name (required), mode
        Returns: List
    """
    def create_list(self, *args, **kargs):
        return bind_api(
            path = '/%s/lists.json' % self.auth_handler.get_username(),
            method = 'POST',
            parser = parse_list,
            allowed_param = ['name', 'mode'],
            require_auth = True
        )(self, *args, **kargs)

    """ Update list

        Updates the specified list.

        Parameters: name (required), mode
        Returns: List
    """
    def update_list(self, slug, *args, **kargs):
        return bind_api(
            path = '/%s/lists/%s.json' % (self.auth_handler.get_username, slug),
            method = 'POST',
            parser = parse_list,
            allowed_param = ['name', 'mode'],
            require_auth = True
        )(self, *args, **kargs)

957
    """ search
Josh Roesslein's avatar
Josh Roesslein committed
958

959
960
961
962
963
964
965
966
        Returns tweets that match a specified query.

        Parameters: q (Required), lang, locale, rpp, page, since_id
            geocode, show_user
        Returns: list[SearchResult]

        http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-search
    """
Josh Roesslein's avatar
Josh Roesslein committed
967
968
969
970
971
972

    def search(self, *args, **kargs):
        return bind_api(
            host = 'search.' + self.host,
            path = '/search.json',
            parser = parse_search_results,
973
            allowed_param = ['q', 'lang', 'locale', 'rpp', 'page', 'since_id', 'geocode', 'show_user'],
Josh Roesslein's avatar
Josh Roesslein committed
974
        )(self, *args, **kargs)
975
    search.pagination_mode = 'page'
Josh Roesslein's avatar
Josh Roesslein committed
976

977
978
979
980
981
982
983
984
985
986
987
    """ trends

        Returns the top ten topics that are currently trending on Twitter.
        The response includes the time of the request, the name of each trend,
        and the url to the Twitter Search results page for that topic.

        Parameters: None
        Returns: json object

        http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-trends
    """
Josh Roesslein's avatar
Josh Roesslein committed
988
989
990
991
    def trends(self):
        return bind_api(
            host = 'search.' + self.host,
            path = '/trends.json',
992
            parser = parse_json
Josh Roesslein's avatar
Josh Roesslein committed
993
994
        )(self)

995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
    """ trends/current

        Returns the current top 10 trending topics on Twitter.
        The response includes the time of the request, the name of each
        trending topic, and query used on Twitter Search results
        page for that topic.

        Parameters: exclude
        Returns: json object

        http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-trends-current
    """
1007
1008
1009
1010
1011
1012
1013
1014
    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)

1015
1016
1017
1018
1019
1020
1021
1022
1023
    """ trends/daily

        Returns the top 20 trending topics for each hour in a given day.

        Parameters: date, exclude
        Returns: json object

        http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-trends-daily
    """
1024
1025
1026
1027
1028
1029
1030
1031
    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)

1032
1033
1034
1035
1036
1037
1038
1039
1040
    """ trends/weekly

        Returns the top 30 trending topics for each day in a given week.

        Parameters: date, exclude
        Returns: json object

        http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-trends-weekly
    """
1041
1042
1043
1044
1045
1046
1047
1048
    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)

1049
1050
    """ Internal use only """

Josh Roesslein's avatar
Josh Roesslein committed
1051
    @staticmethod
Josh Roesslein's avatar
Josh Roesslein committed
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
    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
1090