]>
jfr.im git - z_archive/twitter.git/blob - twitter/api.py
2 from base64
import b64encode
7 class TwitterCall(object):
8 def __init__(self
, username
=None, password
=None, uri
=""):
9 self
.username
= username
10 self
.password
= password
12 def __getattr__(self
, k
):
14 return object.__getattr
__(self
, k
)
15 except AttributeError:
17 self
.username
, self
.password
, self
.uri
+ "/" + k
)
18 def __call__(self
, **kwargs
):
20 if self
.uri
.endswith('new') or self
.uri
.endswith('update'):
24 argStr
= "?" + "&".join([
25 "%s=%s" %(k
, v
) for k
, v
in kwargs
.iteritems()])
26 c
= httplib
.HTTPConnection("twitter.com")
28 c
.putrequest(method
, "/%s.json%s" %(self
.uri
, argStr
))
30 c
.putheader("Authorization", "Basic "
31 + b64encode("%s:%s" %(
32 self
.username
, self
.password
)))
37 elif (r
.status
!= 200):
38 raise Exception("Twitter sent status %i: %s" %(
40 return simplejson
.loads(r
.read())
44 class Twitter(TwitterCall
):
46 The minimalist yet fully featured Twitter API class.
48 Get RESTful data by accessing members of this class. The result
49 is decoded python objects (lists and dicts).
51 The Twitter API is documented here:
52 http://groups.google.com/group/twitter-development-talk/web/api-documentation
56 twitter = Twitter("hello@foo.com", "password123")
58 # Get the public timeline
59 twitter.statuses.public_timeline()
61 # Get a particular friend's timeline
62 twitter.statuses.friends_timeline(id="billybob")
64 # Also supported (but totally weird)
65 twitter.statuses.friends_timeline.billybob()
67 # Send a direct message
68 twitter.direct_messages.new(
70 text="I think yer swell!")
72 Using the data returned::
74 Twitter API calls return decoded JSON. This is converted into
75 a bunch of Python lists, dicts, ints, and strings. For example,
77 x = twitter.statuses.public_timeline()
79 # The first 'tweet' in the timeline
82 # The screen name of the user who wrote the first 'tweet'
83 x[0]['user']['screen_name']
86 def __init__(self
, email
=None, password
=None):
88 Create a new twitter API connector using the specified
89 credentials (email and password).
91 TwitterCall
.__init
__(self
, email
, password
)