]> jfr.im git - z_archive/twitter.git/blob - twitter/api.py
Udpated api agent string
[z_archive/twitter.git] / twitter / api.py
1
2 from base64 import b64encode
3 from urllib import urlencode
4
5 import httplib
6
7 from exceptions import Exception
8
9 def _py26OrGreater():
10 import sys
11 return sys.hexversion > 0x20600f0
12
13 if _py26OrGreater():
14 import json
15 else:
16 import simplejson as json
17
18 class TwitterError(Exception):
19 """
20 Exception thrown by the Twitter object when there is an
21 error interacting with twitter.com.
22 """
23 pass
24
25 class TwitterCall(object):
26 def __init__(
27 self, username, password, format, domain, uri="",
28 agent="Python Twitter Tools"
29 ):
30 self.username = username
31 self.password = password
32 self.format = format
33 self.domain = domain
34 self.uri = uri
35 self.agent = agent
36 def __getattr__(self, k):
37 try:
38 return object.__getattr__(self, k)
39 except AttributeError:
40 return TwitterCall(
41 self.username, self.password, self.format, self.domain,
42 self.uri + "/" + k, self.agent
43 )
44 def __call__(self, **kwargs):
45 method = "GET"
46 if (self.uri.endswith('new')
47 or self.uri.endswith('update')
48 or self.uri.endswith('create')
49 or self.uri.endswith('destroy')):
50 method = "POST"
51 if (self.agent):
52 kwargs["source"] = self.agent
53
54 encoded_kwargs = urlencode(kwargs.items())
55 argStr = ""
56 if kwargs and (method == "GET"):
57 argStr = "?" + encoded_kwargs
58
59 headers = {}
60 if (self.agent):
61 headers["X-Twitter-Client"] = self.agent
62 if (self.username):
63 headers["Authorization"] = "Basic " + b64encode("%s:%s" %(
64 self.username, self.password))
65 if method == "POST":
66 headers["Content-type"] = "application/x-www-form-urlencoded"
67 headers["Content-length"] = len(encoded_kwargs)
68
69 c = httplib.HTTPConnection(self.domain)
70 try:
71 c.putrequest(method, "%s.%s%s" %(
72 self.uri, self.format, argStr))
73 for item in headers.iteritems():
74 c.putheader(*item)
75 c.endheaders()
76 if method == "POST":
77 c.send(encoded_kwargs)
78 r = c.getresponse()
79
80 if (r.status == 304):
81 return []
82 elif (r.status != 200):
83 raise TwitterError("Twitter sent status %i: %s" %(
84 r.status, r.read()))
85 if "json" == self.format:
86 return json.loads(r.read())
87 else:
88 return r.read()
89 finally:
90 c.close()
91
92 class Twitter(TwitterCall):
93 """
94 The minimalist yet fully featured Twitter API class.
95
96 Get RESTful data by accessing members of this class. The result
97 is decoded python objects (lists and dicts).
98
99 The Twitter API is documented here:
100
101 http://apiwiki.twitter.com/
102 http://groups.google.com/group/twitter-development-talk/web/api-documentation
103
104 Examples::
105
106 twitter = Twitter("hello@foo.com", "password123")
107
108 # Get the public timeline
109 twitter.statuses.public_timeline()
110
111 # Get a particular friend's timeline
112 twitter.statuses.friends_timeline(id="billybob")
113
114 # Also supported (but totally weird)
115 twitter.statuses.friends_timeline.billybob()
116
117 # Send a direct message
118 twitter.direct_messages.new(
119 user="billybob",
120 text="I think yer swell!")
121
122 Searching Twitter::
123
124 twitter_search = Twitter(domain="search.twitter.com")
125
126 # Find the latest search trends
127 twitter_search.trends()
128
129 # Search for the latest News on #gaza
130 twitter_search.search(q="#gaza")
131
132 Using the data returned::
133
134 Twitter API calls return decoded JSON. This is converted into
135 a bunch of Python lists, dicts, ints, and strings. For example,
136
137 x = twitter.statuses.public_timeline()
138
139 # The first 'tweet' in the timeline
140 x[0]
141
142 # The screen name of the user who wrote the first 'tweet'
143 x[0]['user']['screen_name']
144
145 Getting raw XML data::
146
147 If you prefer to get your Twitter data in XML format, pass
148 format="xml" to the Twitter object when you instantiate it:
149
150 twitter = Twitter(format="xml")
151
152 The output will not be parsed in any way. It will be a raw string
153 of XML.
154 """
155 def __init__(self, email=None, password=None, format="json", domain="twitter.com"):
156 """
157 Create a new twitter API connector using the specified
158 credentials (email and password). Format specifies the output
159 format ("json" (default) or "xml").
160 """
161 if (format not in ("json", "xml")):
162 raise TwitterError("Unknown data format '%s'" %(format))
163 TwitterCall.__init__(self, email, password, format, domain)
164
165 __all__ = ["Twitter", "TwitterError"]