/
core.py
1812 lines (1554 loc) · 95.4 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
127
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
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""
Twython is an up-to-date library for Python that wraps the Twitter API.
Other Python Twitter libraries seem to have fallen a bit behind, and
Twitter's API has evolved a bit. Here's hoping this helps.
TODO: OAuth, Streaming API?
Questions, comments? ryan@venodesigns.net
"""
import httplib, urllib, urllib2, mimetypes, mimetools
from urlparse import urlparse
from urllib2 import HTTPError
__author__ = "Ryan McGrath <ryan@venodesigns.net>"
__version__ = "1.0"
"""Twython - Easy Twitter utilities in Python"""
try:
import simplejson
except ImportError:
try:
import json as simplejson
except ImportError:
try:
from django.utils import simplejson
except:
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
class TwythonError(Exception):
def __init__(self, msg, error_code=None):
self.msg = msg
if error_code == 400:
raise APILimit(msg)
def __str__(self):
return repr(self.msg)
class APILimit(TwythonError):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
class AuthError(TwythonError):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
class setup:
def __init__(self, username = None, password = None, headers = None, proxy = None, version = 1):
"""setup(authtype = "OAuth", username = None, password = None, proxy = None, headers = None)
Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).
Parameters:
username - Your Twitter username, if you want Basic (HTTP) Authentication.
password - Password for your twitter account, if you want Basic (HTTP) Authentication.
headers - User agent header.
proxy - An object detailing information, in case proxy use/authentication is required. Object passed should be something like...
proxyobj = {
"username": "fjnfsjdnfjd",
"password": "fjnfjsjdfnjd",
"host": "http://fjanfjasnfjjfnajsdfasd.com",
"port": 87
}
version (number) - Twitter supports a "versioned" API as of Oct. 16th, 2009 - this defaults to 1, but can be overridden on a class and function-based basis.
** Note: versioning is not currently used by search.twitter functions; when Twitter moves their junk, it'll be supported.
"""
self.authenticated = False
self.username = username
self.apiVersion = version
self.proxy = proxy
self.headers = headers
if self.proxy is not None:
self.proxyobj = urllib2.ProxyHandler({'http': 'http://%s:%s@%s:%d' % (self.proxy["username"], self.proxy["password"], self.proxy["host"], self.proxy["port"])})
# Check and set up authentication
if self.username is not None and password is not None:
# Assume Basic authentication ritual
self.auth_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
self.auth_manager.add_password(None, "http://api.twitter.com", self.username, password)
self.handler = urllib2.HTTPBasicAuthHandler(self.auth_manager)
if self.proxy is not None:
self.opener = urllib2.build_opener(self.proxyobj, self.handler)
else:
self.opener = urllib2.build_opener(self.handler)
if self.headers is not None:
self.opener.addheaders = [('User-agent', self.headers)]
try:
simplejson.load(self.opener.open("http://api.twitter.com/%d/account/verify_credentials.json" % self.apiVersion))
self.authenticated = True
except HTTPError, e:
raise AuthError("Authentication failed with your provided credentials. Try again? (%s failure)" % `e.code`)
else:
# Build a non-auth opener so we can allow proxy-auth and/or header swapping
if self.proxy is not None:
self.opener = urllib2.build_opener(self.proxyobj)
else:
self.opener = urllib2.build_opener()
if self.headers is not None:
self.opener.addheaders = [('User-agent', self.headers)]
# URL Shortening function huzzah
def shortenURL(self, url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl"):
"""shortenURL(url_to_shorten, shortener = "http://is.gd/api.php", query = "longurl")
Shortens url specified by url_to_shorten.
Parameters:
url_to_shorten - URL to shorten.
shortener - In case you want to use url shorterning service other that is.gd.
"""
try:
return urllib2.urlopen(shortener + "?" + urllib.urlencode({query: self.unicode2utf8(url_to_shorten)})).read()
except HTTPError, e:
raise TwythonError("shortenURL() failed with a %s error code." % `e.code`)
def constructApiURL(self, base_url, params):
return base_url + "?" + "&".join(["%s=%s" %(key, value) for (key, value) in params.iteritems()])
def getRateLimitStatus(self, rate_for = "requestingIP", version = None):
"""getRateLimitStatus()
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 requesting
IP address is returned.
Params:
rate_for - Defaults to "requestingIP", but can be changed to check on whatever account is currently authenticated. (Pass a blank string or something)
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
try:
if rate_for == "requestingIP":
return simplejson.load(self.opener.open("http://api.twitter.com/%d/account/rate_limit_status.json" % version))
else:
if self.authenticated is True:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/account/rate_limit_status.json" % version))
else:
raise TwythonError("You need to be authenticated to check a rate limit status on an account.")
except HTTPError, e:
raise TwythonError("It seems that there's something wrong. Twitter gave you a %s error code; are you doing something you shouldn't be?" % `e.code`, e.code)
def getPublicTimeline(self, version = None):
"""getPublicTimeline()
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.
Params:
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
try:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/statuses/public_timeline.json" % version))
except HTTPError, e:
raise TwythonError("getPublicTimeline() failed with a %s error code." % `e.code`)
def getHomeTimeline(self, version = None, **kwargs):
"""getHomeTimeline(**kwargs)
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.
Usage note: This home_timeline is identical to statuses/friends_timeline, except it also
contains retweets, which statuses/friends_timeline does not (for backwards compatibility
reasons). In a future version of the API, statuses/friends_timeline will go away and
be replaced by home_timeline.
Parameters:
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Optional. Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
homeTimelineURL = self.constructApiURL("http://api.twitter.com/%d/statuses/home_timeline.json" % version, kwargs)
return simplejson.load(self.opener.open(homeTimelineURL))
except HTTPError, e:
raise TwythonError("getHomeTimeline() failed with a %s error code. (This is an upcoming feature in the Twitter API, and may not be implemented yet)" % `e.code`)
else:
raise AuthError("getHomeTimeline() requires you to be authenticated.")
def getFriendsTimeline(self, version = None, **kwargs):
"""getFriendsTimeline(**kwargs)
Returns the 20 most recent statuses posted by the authenticating user, as well as that users friends.
This is the equivalent of /timeline/home on the Web.
Parameters:
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Optional. Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
friendsTimelineURL = self.constructApiURL("http://api.twitter.com/%d/statuses/friends_timeline.json" % version, kwargs)
return simplejson.load(self.opener.open(friendsTimelineURL))
except HTTPError, e:
raise TwythonError("getFriendsTimeline() failed with a %s error code." % `e.code`)
else:
raise AuthError("getFriendsTimeline() requires you to be authenticated.")
def getUserTimeline(self, id = None, version = None, **kwargs):
"""getUserTimeline(id = None, **kwargs)
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. This is the
equivalent of the Web /<user> page for your own user, or the profile page for a third party.
Parameters:
id - Optional. Specifies the ID or screen name of the user for whom to return the user_timeline.
user_id - Optional. Specfies the ID of the user for whom to return the user_timeline. Helpful for disambiguating.
screen_name - Optional. Specfies the screen name of the user for whom to return the user_timeline. (Helpful for disambiguating when a valid screen name is also a user ID)
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if id is not None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False:
userTimelineURL = self.constructApiURL("http://api.twitter.com/%d/statuses/user_timeline/%s.json" % (version, `id`), kwargs)
elif id is None and kwargs.has_key("user_id") is False and kwargs.has_key("screen_name") is False and self.authenticated is True:
userTimelineURL = self.constructApiURL("http://api.twitter.com/%d/statuses/user_timeline/%s.json" % (version, self.username), kwargs)
else:
userTimelineURL = self.constructApiURL("http://api.twitter.com/%d/statuses/user_timeline.json" % version, kwargs)
try:
# We do our custom opener if we're authenticated, as it helps avoid cases where it's a protected user
if self.authenticated is True:
return simplejson.load(self.opener.open(userTimelineURL))
else:
return simplejson.load(self.opener.open(userTimelineURL))
except HTTPError, e:
raise TwythonError("Failed with a %s error code. Does this user hide/protect their updates? If so, you'll need to authenticate and be their friend to get their timeline."
% `e.code`, e.code)
def getUserMentions(self, version = None, **kwargs):
"""getUserMentions(**kwargs)
Returns the 20 most recent mentions (status containing @username) for the authenticating user.
Parameters:
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Optional. Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
mentionsFeedURL = self.constructApiURL("http://api.twitter.com/%d/statuses/mentions.json" % version, kwargs)
return simplejson.load(self.opener.open(mentionsFeedURL))
except HTTPError, e:
raise TwythonError("getUserMentions() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("getUserMentions() requires you to be authenticated.")
def reportSpam(self, id = None, user_id = None, screen_name = None, version = None):
"""reportSpam(self, id), user_id, screen_name):
Report a user account to Twitter as a spam account. *One* of the following parameters is required, and
this requires that you be authenticated with a user account.
Parameters:
id - Optional. The ID or screen_name of the user you want to report as a spammer.
user_id - Optional. The ID of the user you want to report as a spammer. Helpful for disambiguating when a valid user ID is also a valid screen name.
screen_name - Optional. The ID or screen_name of the user you want to report as a spammer. Helpful for disambiguating when a valid screen name is also a user ID.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
# This entire block of code is stupid, but I'm far too tired to think through it at the moment. Refactor it if you care.
if id is not None or user_id is not None or screen_name is not None:
try:
apiExtension = ""
if id is not None:
apiExtension = "id=%s" % id
if user_id is not None:
apiExtension = "user_id=%s" % `user_id`
if screen_name is not None:
apiExtension = "screen_name=%s" % screen_name
return simplejson.load(self.opener.open("http://api.twitter.com/%d/report_spam.json" % version, apiExtension))
except HTTPError, e:
raise TwythonError("reportSpam() failed with a %s error code." % `e.code`, e.code)
else:
raise TwythonError("reportSpam requires you to specify an id, user_id, or screen_name. Try again!")
else:
raise AuthError("reportSpam() requires you to be authenticated.")
def reTweet(self, id, version = None):
"""reTweet(id)
Retweets a tweet. Requires the id parameter of the tweet you are retweeting.
Parameters:
id - Required. The numerical ID of the tweet you are retweeting.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/statuses/retweet/%s.json" % (version, `id`), "POST"))
except HTTPError, e:
raise TwythonError("reTweet() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("reTweet() requires you to be authenticated.")
def getRetweets(self, id, count = None, version = None):
""" getRetweets(self, id, count):
Returns up to 100 of the first retweets of a given tweet.
Parameters:
id - Required. The numerical ID of the tweet you want the retweets of.
count - Optional. Specifies the number of retweets to retrieve. May not be greater than 100.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
apiURL = "http://api.twitter.com/%d/statuses/retweets/%s.json" % (version, `id`)
if count is not None:
apiURL += "?count=%s" % `count`
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TwythonError("getRetweets failed with a %s eroror code." % `e.code`, e.code)
else:
raise AuthError("getRetweets() requires you to be authenticated.")
def retweetedOfMe(self, version = None, **kwargs):
"""retweetedOfMe(**kwargs)
Returns the 20 most recent tweets of the authenticated user that have been retweeted by others.
Parameters:
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Optional. Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
retweetURL = self.constructApiURL("http://api.twitter.com/%d/statuses/retweets_of_me.json" % version, kwargs)
return simplejson.load(self.opener.open(retweetURL))
except HTTPError, e:
raise TwythonError("retweetedOfMe() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("retweetedOfMe() requires you to be authenticated.")
def retweetedByMe(self, version = None, **kwargs):
"""retweetedByMe(**kwargs)
Returns the 20 most recent retweets posted by the authenticating user.
Parameters:
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Optional. Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
retweetURL = self.constructApiURL("http://api.twitter.com/%d/statuses/retweeted_by_me.json" % version, kwargs)
return simplejson.load(self.opener.open(retweetURL))
except HTTPError, e:
raise TwythonError("retweetedByMe() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("retweetedByMe() requires you to be authenticated.")
def retweetedToMe(self, version = None, **kwargs):
"""retweetedToMe(**kwargs)
Returns the 20 most recent retweets posted by the authenticating user's friends.
Parameters:
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Optional. Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
retweetURL = self.constructApiURL("http://api.twitter.com/%d/statuses/retweeted_to_me.json" % version, kwargs)
return simplejson.load(self.opener.open(retweetURL))
except HTTPError, e:
raise TwythonError("retweetedToMe() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("retweetedToMe() requires you to be authenticated.")
def searchUsers(self, q, per_page = 20, page = 1, version = None):
""" searchUsers(q, per_page = None, page = None):
Query Twitter to find a set of users who match the criteria we have. (Note: This, oddly, requires authentication - go figure)
Parameters:
q (string) - Required. The query you wanna search against; self explanatory. ;)
per_page (number) - Optional, defaults to 20. Specify the number of users Twitter should return per page (no more than 20, just fyi)
page (number) - Optional, defaults to 1. The page of users you want to pull down.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/users/search.json?q=%s&per_page=%d&page=%d" % (version, q, per_page, page)))
except HTTPError, e:
raise TwythonError("searchUsers() failed with a %d error code." % e.code, e.code)
else:
raise AuthError("searchUsers(), oddly, requires you to be authenticated.")
def showUser(self, id = None, user_id = None, screen_name = None, version = None):
"""showUser(id = None, user_id = None, screen_name = None)
Returns extended information of a given user. The author's most recent status will be returned inline.
Parameters:
** Note: One of the following must always be specified.
id - The ID or screen name of a user.
user_id - Specfies the ID of the user to return. Helpful for disambiguating when a valid user ID is also a valid screen name.
screen_name - Specfies the screen name of the user to return. Helpful for disambiguating when a valid screen name is also a user ID.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
Usage Notes:
Requests for protected users without credentials from
1) the user requested or
2) a user that is following the protected user will omit the nested status element.
...will result in only publicly available data being returned.
"""
version = version or self.apiVersion
apiURL = ""
if id is not None:
apiURL = "http://api.twitter.com/%d/users/show/%s.json" % (version, id)
if user_id is not None:
apiURL = "http://api.twitter.com/%d/users/show.json?user_id=%s" % (version, `user_id`)
if screen_name is not None:
apiURL = "http://api.twitter.com/%d/users/show.json?screen_name=%s" % (version, screen_name)
if apiURL != "":
try:
if self.authenticated is True:
return simplejson.load(self.opener.open(apiURL))
else:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TwythonError("showUser() failed with a %s error code." % `e.code`, e.code)
def getFriendsStatus(self, id = None, user_id = None, screen_name = None, page = None, cursor="-1", version = None):
"""getFriendsStatus(id = None, user_id = None, screen_name = None, page = None, cursor="-1")
Returns a user's friends, each with current status inline. 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, the request defaults to the authenticated users friends.
It's also possible to request another user's friends list via the id, screen_name or user_id parameter.
Note: The previously documented page-based pagination mechanism is still in production, but please migrate to cursor-based pagination for increase reliability and performance.
Parameters:
** Note: One of the following is required. (id, user_id, or screen_name)
id - Optional. The ID or screen name of the user for whom to request a list of friends.
user_id - Optional. Specfies the ID of the user for whom to return the list of friends. Helpful for disambiguating when a valid user ID is also a valid screen name.
screen_name - Optional. Specfies the screen name of the user for whom to return the list of friends. Helpful for disambiguating when a valid screen name is also a user ID.
page - (BEING DEPRECATED) Optional. Specifies the page of friends to receive.
cursor - Optional. Breaks the results into pages. A single page contains 100 users. This is recommended for users who are following many users. Provide a value of -1 to begin paging. Provide values as returned to in the response body's next_cursor and previous_cursor attributes to page back and forth in the list.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://api.twitter.com/%d/statuses/friends/%s.json" % (version, id)
if user_id is not None:
apiURL = "http://api.twitter.com/%d/statuses/friends.json?user_id=%s" % (version, `user_id`)
if screen_name is not None:
apiURL = "http://api.twitter.com/%d/statuses/friends.json?screen_name=%s" % (version, screen_name)
try:
if page is not None:
return simplejson.load(self.opener.open(apiURL + "&page=%s" % `page`))
else:
return simplejson.load(self.opener.open(apiURL + "&cursor=%s" % cursor))
except HTTPError, e:
raise TwythonError("getFriendsStatus() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("getFriendsStatus() requires you to be authenticated.")
def getFollowersStatus(self, id = None, user_id = None, screen_name = None, page = None, cursor = "-1", version = None):
"""getFollowersStatus(id = None, user_id = None, screen_name = None, page = None, cursor = "-1")
Returns the authenticating user's followers, each with current status inline.
They are ordered by the order in which they joined Twitter, 100 at a time.
(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.
Note: The previously documented page-based pagination mechanism is still in production, but please migrate to cursor-based pagination for increase reliability and performance.
Parameters:
** Note: One of the following is required. (id, user_id, screen_name)
id - Optional. The ID or screen name of the user for whom to request a list of followers.
user_id - Optional. Specfies the ID of the user for whom to return the list of followers. Helpful for disambiguating when a valid user ID is also a valid screen name.
screen_name - Optional. Specfies the screen name of the user for whom to return the list of followers. Helpful for disambiguating when a valid screen name is also a user ID.
page - (BEING DEPRECATED) Optional. Specifies the page to retrieve.
cursor - Optional. Breaks the results into pages. A single page contains 100 users. This is recommended for users who are following many users. Provide a value of -1 to begin paging. Provide values as returned to in the response body's next_cursor and previous_cursor attributes to page back and forth in the list.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
apiURL = ""
if id is not None:
apiURL = "http://api.twitter.com/%d/statuses/followers/%s.json" % (version, id)
if user_id is not None:
apiURL = "http://api.twitter.com/%d/statuses/followers.json?user_id=%s" % (version, `user_id`)
if screen_name is not None:
apiURL = "http://api.twitter.com/%d/statuses/followers.json?screen_name=%s" % (version, screen_name)
try:
if page is not None:
return simplejson.load(self.opener.open(apiURL + "&page=%s" % page))
else:
return simplejson.load(self.opener.open(apiURL + "&cursor=%s" % cursor))
except HTTPError, e:
raise TwythonError("getFollowersStatus() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("getFollowersStatus() requires you to be authenticated.")
def showStatus(self, id, version = None):
"""showStatus(id)
Returns a single status, specified by the id parameter below.
The status's author will be returned inline.
Parameters:
id - Required. The numerical ID of the status to retrieve.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
try:
if self.authenticated is True:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/statuses/show/%s.json" % (version, id)))
else:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/statuses/show/%s.json" % (version, id)))
except HTTPError, e:
raise TwythonError("Failed with a %s error code. Does this user hide/protect their updates? You'll need to authenticate and be friends to get their timeline."
% `e.code`, e.code)
def updateStatus(self, status, in_reply_to_status_id = None, latitude = None, longitude = None, version = None):
"""updateStatus(status, in_reply_to_status_id = None)
Updates the authenticating user's status. Requires the status parameter specified below.
A status update with text identical to the authenticating users current status will be ignored to prevent duplicates.
Parameters:
status - Required. The text of your status update. URL encode as necessary. Statuses over 140 characters will be forceably truncated.
in_reply_to_status_id - Optional. The ID of an existing status that the update is in reply to.
latitude (string) - Optional. The location's latitude that this tweet refers to.
longitude (string) - Optional. The location's longitude that this tweet refers to.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
** Note: in_reply_to_status_id will be ignored unless the author of the tweet this parameter references
is mentioned within the status text. Therefore, you must include @username, where username is
the author of the referenced tweet, within the update.
** Note: valid ranges for latitude/longitude are, for example, -180.0 to +180.0 (East is positive) inclusive.
This parameter will be ignored if outside that range, not a number, if geo_enabled is disabled, or if there not a corresponding latitude parameter with this tweet.
"""
version = version or self.apiVersion
try:
postExt = urllib.urlencode({"status": self.unicode2utf8(status)})
if latitude is not None and longitude is not None:
postExt += "&lat=%s&long=%s" % (latitude, longitude)
if in_reply_to_status_id is not None:
postExt += "&in_reply_to_status_id=%s" % `in_reply_to_status_id`
return simplejson.load(self.opener.open("http://api.twitter.com/%d/statuses/update.json?" % version, postExt))
except HTTPError, e:
raise TwythonError("updateStatus() failed with a %s error code." % `e.code`, e.code)
def destroyStatus(self, id, version = None):
"""destroyStatus(id)
Destroys the status specified by the required ID parameter.
The authenticating user must be the author of the specified status.
Parameters:
id - Required. The ID of the status to destroy.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/statuses/destroy/%s.json?" % (version, id), "_method=DELETE"))
except HTTPError, e:
raise TwythonError("destroyStatus() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("destroyStatus() requires you to be authenticated.")
def endSession(self, version = None):
"""endSession()
Ends the session of the authenticating user, returning a null cookie.
Use this method to sign users out of client-facing applications (widgets, etc).
Parameters:
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
self.opener.open("http://api.twitter.com/%d/account/end_session.json" % version, "")
self.authenticated = False
except HTTPError, e:
raise TwythonError("endSession failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("You can't end a session when you're not authenticated to begin with.")
def getDirectMessages(self, since_id = None, max_id = None, count = None, page = "1", version = None):
"""getDirectMessages(since_id = None, max_id = None, count = None, page = "1")
Returns a list of the 20 most recent direct messages sent to the authenticating user.
Parameters:
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Optional. Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
apiURL = "http://api.twitter.com/%d/direct_messages.json?page=%s" % (version, `page`)
if since_id is not None:
apiURL += "&since_id=%s" % `since_id`
if max_id is not None:
apiURL += "&max_id=%s" % `max_id`
if count is not None:
apiURL += "&count=%s" % `count`
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TwythonError("getDirectMessages() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("getDirectMessages() requires you to be authenticated.")
def getSentMessages(self, since_id = None, max_id = None, count = None, page = "1", version = None):
"""getSentMessages(since_id = None, max_id = None, count = None, page = "1")
Returns a list of the 20 most recent direct messages sent by the authenticating user.
Parameters:
since_id - Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
max_id - Optional. Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
count - Optional. Specifies the number of statuses to retrieve. May not be greater than 200.
page - Optional. Specifies the page of results to retrieve. Note: there are pagination limits.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
apiURL = "http://api.twitter.com/%d/direct_messages/sent.json?page=%s" % (version, `page`)
if since_id is not None:
apiURL += "&since_id=%s" % `since_id`
if max_id is not None:
apiURL += "&max_id=%s" % `max_id`
if count is not None:
apiURL += "&count=%s" % `count`
try:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
raise TwythonError("getSentMessages() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("getSentMessages() requires you to be authenticated.")
def sendDirectMessage(self, user, text, version = None):
"""sendDirectMessage(user, text)
Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters.
Returns the sent message in the requested format when successful.
Parameters:
user - Required. The ID or screen name of the recipient user.
text - Required. The text of your direct message. Be sure to keep it under 140 characters.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
if len(list(text)) < 140:
try:
return self.opener.open("http://api.twitter.com/%d/direct_messages/new.json" % version, urllib.urlencode({"user": user, "text": text}))
except HTTPError, e:
raise TwythonError("sendDirectMessage() failed with a %s error code." % `e.code`, e.code)
else:
raise TwythonError("Your message must not be longer than 140 characters")
else:
raise AuthError("You must be authenticated to send a new direct message.")
def destroyDirectMessage(self, id, version = None):
"""destroyDirectMessage(id)
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. The ID of the direct message to destroy.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
return self.opener.open("http://api.twitter.com/%d/direct_messages/destroy/%s.json" % (version, id), "")
except HTTPError, e:
raise TwythonError("destroyDirectMessage() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("You must be authenticated to destroy a direct message.")
def createFriendship(self, id = None, user_id = None, screen_name = None, follow = "false", version = None):
"""createFriendship(id = None, user_id = None, screen_name = None, follow = "false")
Allows the authenticating users to follow the user specified in the ID parameter.
Returns the befriended user in the requested format when successful. Returns a
string describing the failure condition when unsuccessful. If you are already
friends with the user an HTTP 403 will be returned.
Parameters:
** Note: One of the following is required. (id, user_id, screen_name)
id - Required. The ID or screen name of the user to befriend.
user_id - Required. Specfies the ID of the user to befriend. Helpful for disambiguating when a valid user ID is also a valid screen name.
screen_name - Required. Specfies the screen name of the user to befriend. Helpful for disambiguating when a valid screen name is also a user ID.
follow - Optional. Enable notifications for the target user in addition to becoming friends.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
apiURL = ""
if user_id is not None:
apiURL = "?user_id=%s&follow=%s" %(`user_id`, follow)
if screen_name is not None:
apiURL = "?screen_name=%s&follow=%s" %(screen_name, follow)
try:
if id is not None:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/friendships/create/%s.json" % (version, id), "?follow=%s" % follow))
else:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/friendships/create.json" % version, apiURL))
except HTTPError, e:
# Rate limiting is done differently here for API reasons...
if e.code == 403:
raise APILimit("You've hit the update limit for this method. Try again in 24 hours.")
raise TwythonError("createFriendship() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("createFriendship() requires you to be authenticated.")
def destroyFriendship(self, id = None, user_id = None, screen_name = None, version = None):
"""destroyFriendship(id = None, user_id = None, screen_name = None)
Allows the authenticating users to unfollow the user specified in the ID parameter.
Returns the unfollowed user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
Parameters:
** Note: One of the following is required. (id, user_id, screen_name)
id - Required. The ID or screen name of the user to unfollow.
user_id - Required. Specfies the ID of the user to unfollow. Helpful for disambiguating when a valid user ID is also a valid screen name.
screen_name - Required. Specfies the screen name of the user to unfollow. Helpful for disambiguating when a valid screen name is also a user ID.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
apiURL = ""
if user_id is not None:
apiURL = "?user_id=%s" % `user_id`
if screen_name is not None:
apiURL = "?screen_name=%s" % screen_name
try:
if id is not None:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/friendships/destroy/%s.json" % (version, `id`), "lol=1")) # Random string hack for POST reasons ;P
else:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/friendships/destroy.json" % version, apiURL))
except HTTPError, e:
raise TwythonError("destroyFriendship() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("destroyFriendship() requires you to be authenticated.")
def checkIfFriendshipExists(self, user_a, user_b, version = None):
"""checkIfFriendshipExists(user_a, user_b)
Tests for the existence of friendship between two users.
Will return true if user_a follows user_b; otherwise, it'll return false.
Parameters:
user_a - Required. The ID or screen_name of the subject user.
user_b - Required. The ID or screen_name of the user to test for following.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
friendshipURL = "http://api.twitter.com/%d/friendships/exists.json?%s" % (version, urllib.urlencode({"user_a": user_a, "user_b": user_b}))
return simplejson.load(self.opener.open(friendshipURL))
except HTTPError, e:
raise TwythonError("checkIfFriendshipExists() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("checkIfFriendshipExists(), oddly, requires that you be authenticated.")
def showFriendship(self, source_id = None, source_screen_name = None, target_id = None, target_screen_name = None, version = None):
"""showFriendship(source_id, source_screen_name, target_id, target_screen_name)
Returns detailed information about the relationship between two users.
Parameters:
** Note: One of the following is required if the request is unauthenticated
source_id - The user_id of the subject user.
source_screen_name - The screen_name of the subject user.
** Note: One of the following is required at all times
target_id - The user_id of the target user.
target_screen_name - The screen_name of the target user.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
apiURL = "http://api.twitter.com/%d/friendships/show.json?lol=1" % version # Another quick hack, look away if you want. :D
if source_id is not None:
apiURL += "&source_id=%s" % `source_id`
if source_screen_name is not None:
apiURL += "&source_screen_name=%s" % source_screen_name
if target_id is not None:
apiURL += "&target_id=%s" % `target_id`
if target_screen_name is not None:
apiURL += "&target_screen_name=%s" % target_screen_name
try:
if self.authenticated is True:
return simplejson.load(self.opener.open(apiURL))
else:
return simplejson.load(self.opener.open(apiURL))
except HTTPError, e:
# Catch this for now
if e.code == 403:
raise AuthError("You're unauthenticated, and forgot to pass a source for this method. Try again!")
raise TwythonError("showFriendship() failed with a %s error code." % `e.code`, e.code)
def updateDeliveryDevice(self, device_name = "none", version = None):
"""updateDeliveryDevice(device_name = "none")
Sets which device Twitter delivers updates to for the authenticating user.
Sending "none" as the device parameter will disable IM or SMS updates. (Simply calling .updateDeliveryService() also accomplishes this)
Parameters:
device - Required. Must be one of: sms, im, none.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
return self.opener.open("http://api.twitter.com/%d/account/update_delivery_device.json?" % version, urllib.urlencode({"device": self.unicode2utf8(device_name)}))
except HTTPError, e:
raise TwythonError("updateDeliveryDevice() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("updateDeliveryDevice() requires you to be authenticated.")
def updateProfileColors(self, version = None, **kwargs):
"""updateProfileColors(**kwargs)
Sets one or more hex values that control the color scheme of the authenticating user's profile page on api.twitter.com.
Parameters:
** Note: One or more of the following parameters must be present. Each parameter's value must
be a valid hexidecimal value, and may be either three or six characters (ex: #fff or #ffffff).
profile_background_color - Optional.
profile_text_color - Optional.
profile_link_color - Optional.
profile_sidebar_fill_color - Optional.
profile_sidebar_border_color - Optional.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
return self.opener.open(self.constructApiURL("http://api.twitter.com/%d/account/update_profile_colors.json?" % version, kwargs))
except HTTPError, e:
raise TwythonError("updateProfileColors() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("updateProfileColors() requires you to be authenticated.")
def updateProfile(self, name = None, email = None, url = None, location = None, description = None, version = None):
"""updateProfile(name = None, email = None, url = None, location = None, description = None)
Sets values that users are able to set under the "Account" tab of their settings page.
Only the parameters specified will be updated.
Parameters:
One or more of the following parameters must be present. Each parameter's value
should be a string. See the individual parameter descriptions below for further constraints.
name - Optional. Maximum of 20 characters.
email - Optional. Maximum of 40 characters. Must be a valid email address.
url - Optional. Maximum of 100 characters. Will be prepended with "http://" if not present.
location - Optional. Maximum of 30 characters. The contents are not normalized or geocoded in any way.
description - Optional. Maximum of 160 characters.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
useAmpersands = False
updateProfileQueryString = ""
if name is not None:
if len(list(name)) < 20:
updateProfileQueryString += "name=" + name
useAmpersands = True
else:
raise TwythonError("Twitter has a character limit of 20 for all usernames. Try again.")
if email is not None and "@" in email:
if len(list(email)) < 40:
if useAmpersands is True:
updateProfileQueryString += "&email=" + email
else:
updateProfileQueryString += "email=" + email
useAmpersands = True
else:
raise TwythonError("Twitter has a character limit of 40 for all email addresses, and the email address must be valid. Try again.")
if url is not None:
if len(list(url)) < 100:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"url": self.unicode2utf8(url)})
else:
updateProfileQueryString += urllib.urlencode({"url": self.unicode2utf8(url)})
useAmpersands = True
else:
raise TwythonError("Twitter has a character limit of 100 for all urls. Try again.")
if location is not None:
if len(list(location)) < 30:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"location": self.unicode2utf8(location)})
else:
updateProfileQueryString += urllib.urlencode({"location": self.unicode2utf8(location)})
useAmpersands = True
else:
raise TwythonError("Twitter has a character limit of 30 for all locations. Try again.")
if description is not None:
if len(list(description)) < 160:
if useAmpersands is True:
updateProfileQueryString += "&" + urllib.urlencode({"description": self.unicode2utf8(description)})
else:
updateProfileQueryString += urllib.urlencode({"description": self.unicode2utf8(description)})
else:
raise TwythonError("Twitter has a character limit of 160 for all descriptions. Try again.")
if updateProfileQueryString != "":
try:
return self.opener.open("http://api.twitter.com/%d/account/update_profile.json?" % version, updateProfileQueryString)
except HTTPError, e:
raise TwythonError("updateProfile() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("updateProfile() requires you to be authenticated.")
def getFavorites(self, page = "1", version = None):
"""getFavorites(page = "1")
Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
Parameters:
page - Optional. Specifies the page of favorites to retrieve.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
"""
version = version or self.apiVersion
if self.authenticated is True:
try:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/favorites.json?page=%s" % (version, `page`)))
except HTTPError, e:
raise TwythonError("getFavorites() failed with a %s error code." % `e.code`, e.code)
else:
raise AuthError("getFavorites() requires you to be authenticated.")
def createFavorite(self, id, version = None):
"""createFavorite(id)
Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.
Parameters: