]> jfr.im git - z_archive/twitter.git/blame - twitter/api.py
First import
[z_archive/twitter.git] / twitter / api.py
CommitLineData
7364ea65 1
2from base64 import b64encode
3
4import httplib
5import simplejson
6
7class TwitterCall(object):
8 def __init__(self, username=None, password=None, uri=""):
9 self.username = username
10 self.password = password
11 self.uri = uri
12 def __getattr__(self, k):
13 try:
14 return object.__getattr__(self, k)
15 except AttributeError:
16 return TwitterCall(
17 self.username, self.password, self.uri + "/" + k)
18 def __call__(self, **kwargs):
19 method = "GET"
20 if self.uri.endswith('new') or self.uri.endswith('update'):
21 method = "POST"
22 argStr = ""
23 if kwargs:
24 argStr = "?" + "&".join([
25 "%s=%s" %(k, v) for k, v in kwargs.iteritems()])
26 c = httplib.HTTPConnection("twitter.com")
27 try:
28 c.putrequest(method, "/%s.json%s" %(self.uri, argStr))
29 if (self.username):
30 c.putheader("Authorization", "Basic "
31 + b64encode("%s:%s" %(
32 self.username, self.password)))
33 c.endheaders()
34 r = c.getresponse()
35 if (r.status == 304):
36 return []
37 elif (r.status != 200):
38 raise Exception("Twitter sent status %i: %s" %(
39 r.status, r.read()))
40 return simplejson.loads(r.read())
41 finally:
42 c.close()
43
44class Twitter(TwitterCall):
45 """
46 The minimalist yet fully featured Twitter API class.
47
48 Get RESTful data by accessing members of this class. The result
49 is decoded python objects (lists and dicts).
50
51 The Twitter API is documented here:
52 http://groups.google.com/group/twitter-development-talk/web/api-documentation
53
54 Examples::
55
56 twitter = Twitter("hello@foo.com", "password123")
57
58 # Get the public timeline
59 twitter.statuses.public_timeline()
60
61 # Get a particular friend's timeline
62 twitter.statuses.friends_timeline(id="billybob")
63
64 # Also supported (but totally weird)
65 twitter.statuses.friends_timeline.billybob()
66
67 # Send a direct message
68 twitter.direct_messages.new(
69 user="billybob",
70 text="I think yer swell!")
71
72 Using the data returned::
73
74 Twitter API calls return decoded JSON. This is converted into
75 a bunch of Python lists, dicts, ints, and strings. For example,
76
77 x = twitter.statuses.public_timeline()
78
79 # The first 'tweet' in the timeline
80 x[0]
81
82 # The screen name of the user who wrote the first 'tweet'
83 x[0]['user']['screen_name']
84
85 """
86 def __init__(self, email=None, password=None):
87 """
88 Create a new twitter API connector using the specified
89 credentials (email and password).
90 """
91 TwitterCall.__init__(self, email, password)
92
93__all__ = ["Twitter"]