]>
jfr.im git - z_archive/twitter.git/blob - twitter/api.py
2 from base64
import b64encode
3 from urllib
import urlencode
8 from exceptions
import Exception
10 class TwitterError(Exception):
13 class TwitterCall(object):
14 def __init__(self
, username
=None, password
=None, uri
=""):
15 self
.username
= username
16 self
.password
= password
18 def __getattr__(self
, k
):
20 return object.__getattr
__(self
, k
)
21 except AttributeError:
23 self
.username
, self
.password
, self
.uri
+ "/" + k
)
24 def __call__(self
, **kwargs
):
26 if self
.uri
.endswith('new') or self
.uri
.endswith('update'):
30 argStr
= "?" + urlencode(kwargs
.items())
31 c
= httplib
.HTTPConnection("twitter.com")
33 c
.putrequest(method
, "/%s.json%s" %(self
.uri
, argStr
))
35 c
.putheader("Authorization", "Basic "
36 + b64encode("%s:%s" %(
37 self
.username
, self
.password
)))
42 elif (r
.status
!= 200):
43 raise TwitterError("Twitter sent status %i: %s" %(
45 return simplejson
.loads(r
.read())
49 class Twitter(TwitterCall
):
51 The minimalist yet fully featured Twitter API class.
53 Get RESTful data by accessing members of this class. The result
54 is decoded python objects (lists and dicts).
56 The Twitter API is documented here:
57 http://groups.google.com/group/twitter-development-talk/web/api-documentation
61 twitter = Twitter("hello@foo.com", "password123")
63 # Get the public timeline
64 twitter.statuses.public_timeline()
66 # Get a particular friend's timeline
67 twitter.statuses.friends_timeline(id="billybob")
69 # Also supported (but totally weird)
70 twitter.statuses.friends_timeline.billybob()
72 # Send a direct message
73 twitter.direct_messages.new(
75 text="I think yer swell!")
77 Using the data returned::
79 Twitter API calls return decoded JSON. This is converted into
80 a bunch of Python lists, dicts, ints, and strings. For example,
82 x = twitter.statuses.public_timeline()
84 # The first 'tweet' in the timeline
87 # The screen name of the user who wrote the first 'tweet'
88 x[0]['user']['screen_name']
91 def __init__(self
, email
=None, password
=None):
93 Create a new twitter API connector using the specified
94 credentials (email and password).
96 TwitterCall
.__init
__(self
, email
, password
)