]> jfr.im git - z_archive/twitter.git/blame - twitter/api.py
IRCBot should use default API v1.1
[z_archive/twitter.git] / twitter / api.py
CommitLineData
3930cc7b
MV
1try:
2 import urllib.request as urllib_request
3 import urllib.error as urllib_error
4except ImportError:
5 import urllib2 as urllib_request
6 import urllib2 as urllib_error
7364ea65 7
a403f1b3
JL
8try:
9 from cStringIO import StringIO
10except ImportError:
6204d0da 11 from io import BytesIO as StringIO
a403f1b3 12
14fc6b25
MG
13from .twitter_globals import POST_ACTIONS
14from .auth import NoAuth
4e9d6343 15
2ee65672 16import re
a403f1b3 17import gzip
dea9a3e7
MV
18
19try:
20 import http.client as http_client
21except ImportError:
22 import httplib as http_client
2ee65672 23
e149bb48
MV
24try:
25 import json
26except ImportError:
27 import simplejson as json
f1a8ed67 28
dea9a3e7 29
652c5402
MV
30class _DEFAULT(object):
31 pass
32
5251ea48 33class TwitterError(Exception):
21e3bd23 34 """
64a8d213
B
35 Base Exception thrown by the Twitter object when there is a
36 general error interacting with the API.
21e3bd23 37 """
5251ea48 38 pass
39
64a8d213
B
40class TwitterHTTPError(TwitterError):
41 """
42 Exception thrown by the Twitter object when there is an
43 HTTP error interacting with twitter.com.
44 """
1be4ce71 45 def __init__(self, e, uri, format, uriparts):
4b12a3a0
MV
46 self.e = e
47 self.uri = uri
48 self.format = format
49 self.uriparts = uriparts
7fe9aab6
HN
50 try:
51 data = self.e.fp.read()
dea9a3e7 52 except http_client.IncompleteRead as e:
7fe9aab6
HN
53 # can't read the error text
54 # let's try some of it
55 data = e.partial
e9fc8d86 56 if self.e.headers.get('Content-Encoding') == 'gzip':
7fe9aab6 57 buf = StringIO(data)
84d2da3d 58 f = gzip.GzipFile(fileobj=buf)
59 self.response_data = f.read()
60 else:
7fe9aab6 61 self.response_data = data
64a8d213
B
62
63 def __str__(self):
57b54437 64 fmt = ("." + self.format) if self.format else ""
68b3e2ee 65 return (
57b54437 66 "Twitter sent status %i for URL: %s%s using parameters: "
68b3e2ee 67 "(%s)\ndetails: %s" %(
57b54437 68 self.e.code, self.uri, fmt, self.uriparts,
c7dd86d1 69 self.response_data))
64a8d213 70
84d0a294
MV
71class TwitterResponse(object):
72 """
73 Response from a twitter request. Behaves like a list or a string
74 (depending on requested format) but it has a few other interesting
75 attributes.
76
77 `headers` gives you access to the response headers as an
78 httplib.HTTPHeaders instance. You can do
ba02331e 79 `response.headers.get('h')` to retrieve a header.
84d0a294 80 """
aef72b31 81 def __init__(self, headers):
84d0a294
MV
82 self.headers = headers
83
84d0a294
MV
84 @property
85 def rate_limit_remaining(self):
86 """
87 Remaining requests in the current rate-limit.
88 """
eeec9b00
IA
89 return int(self.headers.get('X-Rate-Limit-Remaining', "0"))
90
91 @property
92 def rate_limit_limit(self):
93 """
c53558ad 94 The rate limit ceiling for that given request.
eeec9b00
IA
95 """
96 return int(self.headers.get('X-Rate-Limit-Limit', "0"))
84d0a294
MV
97
98 @property
99 def rate_limit_reset(self):
100 """
101 Time in UTC epoch seconds when the rate limit will reset.
102 """
eeec9b00 103 return int(self.headers.get('X-Rate-Limit-Reset', "0"))
84d0a294
MV
104
105
abddd419
MV
106def wrap_response(response, headers):
107 response_typ = type(response)
ce92ec77
MV
108 if response_typ is bool:
109 # HURF DURF MY NAME IS PYTHON AND I CAN'T SUBCLASS bool.
110 response_typ = int
a73cff02
MV
111 elif response_typ is str:
112 return response
12bba6ac
MV
113
114 class WrappedTwitterResponse(response_typ, TwitterResponse):
abddd419
MV
115 __doc__ = TwitterResponse.__doc__
116
c77b5e4b
SK
117 def __init__(self, response, headers):
118 response_typ.__init__(self, response)
119 TwitterResponse.__init__(self, headers)
94803fc9 120 def __new__(cls, response, headers):
121 return response_typ.__new__(cls, response)
122
c77b5e4b 123 return WrappedTwitterResponse(response, headers)
abddd419 124
0d6c0646
MV
125
126
7364ea65 127class TwitterCall(object):
dd648a25 128
c8d451e8 129 def __init__(
dd648a25 130 self, auth, format, domain, callable_cls, uri="",
effd06bb 131 uriparts=None, secure=True, timeout=None):
568331a9 132 self.auth = auth
a55e6a11 133 self.format = format
153dee29 134 self.domain = domain
dd648a25 135 self.callable_cls = callable_cls
7364ea65 136 self.uri = uri
b0dedfc0 137 self.uriparts = uriparts
9a148ed1 138 self.secure = secure
effd06bb 139 self.timeout = timeout
fd2bc885 140
7364ea65 141 def __getattr__(self, k):
142 try:
143 return object.__getattr__(self, k)
144 except AttributeError:
e748eed8 145 def extend_call(arg):
146 return self.callable_cls(
147 auth=self.auth, format=self.format, domain=self.domain,
effd06bb 148 callable_cls=self.callable_cls, timeout=self.timeout, uriparts=self.uriparts \
e748eed8 149 + (arg,),
150 secure=self.secure)
151 if k == "_":
152 return extend_call
153 else:
154 return extend_call(k)
fd2bc885 155
7364ea65 156 def __call__(self, **kwargs):
aec68959 157 # Build the uri.
1be4ce71 158 uriparts = []
b0dedfc0 159 for uripart in self.uriparts:
aec68959
MV
160 # If this part matches a keyword argument, use the
161 # supplied value otherwise, just use the part.
f7e63802
MV
162 uriparts.append(str(kwargs.pop(uripart, uripart)))
163 uri = '/'.join(uriparts)
1be4ce71 164
57b54437 165 method = kwargs.pop('_method', None)
166 if not method:
167 method = "GET"
168 for action in POST_ACTIONS:
2ee65672 169 if re.search("%s(/\d+)?$" % action, uri):
57b54437 170 method = "POST"
171 break
612ececa 172
aec68959
MV
173 # If an id kwarg is present and there is no id to fill in in
174 # the list of uriparts, assume the id goes at the end.
da45d039
MV
175 id = kwargs.pop('id', None)
176 if id:
177 uri += "/%s" %(id)
4e9d6343 178
920528cd
MV
179 # If an _id kwarg is present, this is treated as id as a CGI
180 # param.
181 _id = kwargs.pop('_id', None)
182 if _id:
183 kwargs['id'] = _id
be5f32da 184
8fd7289d
IA
185 # If an _timeout is specified in kwargs, use it
186 _timeout = kwargs.pop('_timeout', None)
920528cd 187
568331a9
MH
188 secure_str = ''
189 if self.secure:
190 secure_str = 's'
6c527e72 191 dot = ""
1be4ce71 192 if self.format:
6c527e72
MV
193 dot = "."
194 uriBase = "http%s://%s/%s%s%s" %(
195 secure_str, self.domain, uri, dot, self.format)
568331a9 196
a403f1b3 197 headers = {'Accept-Encoding': 'gzip'}
1be4ce71 198 if self.auth:
568331a9 199 headers.update(self.auth.generate_headers())
1be4ce71
MV
200 arg_data = self.auth.encode_params(uriBase, method, kwargs)
201 if method == 'GET':
202 uriBase += '?' + arg_data
203 body = None
204 else:
8eb73aab 205 body = arg_data.encode('utf8')
c53558ad 206
3930cc7b 207 req = urllib_request.Request(uriBase, body, headers)
8fd7289d 208 return self._handle_response(req, uri, arg_data, _timeout)
102acdb1 209
8fd7289d 210 def _handle_response(self, req, uri, arg_data, _timeout=None):
a5aab114 211 kwargs = {}
8fd7289d
IA
212 if _timeout:
213 kwargs['timeout'] = _timeout
7364ea65 214 try:
a5aab114 215 handle = urllib_request.urlopen(req, **kwargs)
918b8b48
GC
216 if handle.headers['Content-Type'] in ['image/jpeg', 'image/png']:
217 return handle
0fdfdc3d
DM
218 try:
219 data = handle.read()
dea9a3e7 220 except http_client.IncompleteRead as e:
0fdfdc3d
DM
221 # Even if we don't get all the bytes we should have there
222 # may be a complete response in e.partial
223 data = e.partial
224 if handle.info().get('Content-Encoding') == 'gzip':
a403f1b3 225 # Handle gzip decompression
0fdfdc3d 226 buf = StringIO(data)
a403f1b3
JL
227 f = gzip.GzipFile(fileobj=buf)
228 data = f.read()
de072195 229 if "json" == self.format:
a403f1b3 230 res = json.loads(data.decode('utf8'))
abddd419 231 return wrap_response(res, handle.headers)
de072195 232 else:
456ec92b 233 return wrap_response(
a403f1b3 234 data.decode('utf8'), handle.headers)
3930cc7b 235 except urllib_error.HTTPError as e:
de072195 236 if (e.code == 304):
7364ea65 237 return []
de072195 238 else:
aec68959 239 raise TwitterHTTPError(e, uri, self.format, arg_data)
102acdb1 240
7364ea65 241class Twitter(TwitterCall):
242 """
243 The minimalist yet fully featured Twitter API class.
4e9d6343 244
7364ea65 245 Get RESTful data by accessing members of this class. The result
246 is decoded python objects (lists and dicts).
247
51e0b8f1 248 The Twitter API is documented at:
153dee29 249
aec68959
MV
250 http://dev.twitter.com/doc
251
4e9d6343 252
7364ea65 253 Examples::
4e9d6343 254
d09c0dd3 255 t = Twitter(
51e0b8f1 256 auth=OAuth(token, token_key, con_secret, con_secret_key)))
4e9d6343 257
58ccea4e
MV
258 # Get your "home" timeline
259 t.statuses.home_timeline()
4e9d6343 260
51e0b8f1 261 # Get a particular friend's timeline
d09c0dd3 262 t.statuses.friends_timeline(id="billybob")
4e9d6343 263
51e0b8f1 264 # Also supported (but totally weird)
d09c0dd3
MV
265 t.statuses.friends_timeline.billybob()
266
267 # Update your status
268 t.statuses.update(
269 status="Using @sixohsix's sweet Python Twitter Tools.")
4e9d6343 270
51e0b8f1 271 # Send a direct message
d09c0dd3 272 t.direct_messages.new(
51e0b8f1
MV
273 user="billybob",
274 text="I think yer swell!")
7364ea65 275
d09c0dd3
MV
276 # Get the members of tamtar's list "Things That Are Rad"
277 t._("tamtar")._("things-that-are-rad").members()
278
279 # Note how the magic `_` method can be used to insert data
280 # into the middle of a call. You can also use replacement:
281 t.user.list.members(user="tamtar", list="things-that-are-rad")
be5f32da 282
8fd7289d 283 # An *optional* `_timeout` parameter can also be used for API
a5aab114
IA
284 # calls which take much more time than normal or twitter stops
285 # responding for some reasone
286 t.users.lookup(
287 screen_name=','.join(A_LIST_OF_100_SCREEN_NAMES), \
8fd7289d 288 _timeout=1)
a5aab114 289
b0dedfc0 290
69e1f98e 291
153dee29 292 Searching Twitter::
4e9d6343 293
58ccea4e
MV
294 # Search for the latest tweets about #pycon
295 t.search.tweets(q="#pycon")
153dee29 296
7364ea65 297
68b3e2ee
MV
298 Using the data returned
299 -----------------------
300
301 Twitter API calls return decoded JSON. This is converted into
302 a bunch of Python lists, dicts, ints, and strings. For example::
7364ea65 303
58ccea4e 304 x = twitter.statuses.home_timeline()
7364ea65 305
51e0b8f1
MV
306 # The first 'tweet' in the timeline
307 x[0]
7364ea65 308
51e0b8f1
MV
309 # The screen name of the user who wrote the first 'tweet'
310 x[0]['user']['screen_name']
4e9d6343 311
4e9d6343 312
68b3e2ee
MV
313 Getting raw XML data
314 --------------------
315
316 If you prefer to get your Twitter data in XML format, pass
317 format="xml" to the Twitter object when you instantiate it::
4e9d6343 318
51e0b8f1 319 twitter = Twitter(format="xml")
4e9d6343 320
51e0b8f1
MV
321 The output will not be parsed in any way. It will be a raw string
322 of XML.
68b3e2ee 323
7364ea65 324 """
45688301 325 def __init__(
aec68959 326 self, format="json",
87ad04c3 327 domain="api.twitter.com", secure=True, auth=None,
652c5402 328 api_version=_DEFAULT):
7364ea65 329 """
68b3e2ee
MV
330 Create a new twitter API connector.
331
332 Pass an `auth` parameter to use the credentials of a specific
333 user. Generally you'll want to pass an `OAuth`
69e1f98e
MV
334 instance::
335
336 twitter = Twitter(auth=OAuth(
337 token, token_secret, consumer_key, consumer_secret))
338
339
68b3e2ee 340 `domain` lets you change the domain you are connecting. By
87ad04c3 341 default it's `api.twitter.com` but `search.twitter.com` may be
68b3e2ee
MV
342 useful too.
343
344 If `secure` is False you will connect with HTTP instead of
345 HTTPS.
346
1cc9ab0b 347 `api_version` is used to set the base uri. By default it's
652c5402 348 '1'. If you are using "search.twitter.com" set this to None.
7364ea65 349 """
d20da7f3
MV
350 if not auth:
351 auth = NoAuth()
352
6c527e72 353 if (format not in ("json", "xml", "")):
68b3e2ee
MV
354 raise ValueError("Unknown data format '%s'" %(format))
355
652c5402 356 if api_version is _DEFAULT:
82a93c03 357 api_version = '1.1'
652c5402 358
1be4ce71 359 uriparts = ()
68b3e2ee 360 if api_version:
1be4ce71 361 uriparts += (str(api_version),)
68b3e2ee 362
9a148ed1 363 TwitterCall.__init__(
aec68959 364 self, auth=auth, format=format, domain=domain,
dd648a25 365 callable_cls=TwitterCall,
1be4ce71 366 secure=secure, uriparts=uriparts)
7e43e2ed 367
7364ea65 368
abddd419 369__all__ = ["Twitter", "TwitterError", "TwitterHTTPError", "TwitterResponse"]