]>
jfr.im git - z_archive/twitter.git/blob - twitter/api.py
2 from base64
import b64encode
3 from urllib
import urlencode
7 from exceptions
import Exception
9 from twitter
.twitter_globals
import POST_ACTIONS
13 return sys
.hexversion
> 0x20600f0
18 import simplejson
as json
20 class TwitterError(Exception):
22 Exception thrown by the Twitter object when there is an
23 error interacting with twitter.com.
27 class TwitterCall(object):
29 self
, username
, password
, format
, domain
, uri
="", agent
=None, encoded_args
=None):
30 self
.username
= username
31 self
.password
= password
36 self
.encoded_args
= encoded_args
38 def __getattr__(self
, k
):
40 return object.__getattr
__(self
, k
)
41 except AttributeError:
43 self
.username
, self
.password
, self
.format
, self
.domain
,
44 self
.uri
+ "/" + k
, self
.agent
, self
.encoded_args
)
46 def __call__(self
, **kwargs
):
49 for action
in POST_ACTIONS
:
50 if self
.uri
.endswith(action
):
53 kwargs
["source"] = self
.agent
56 if (not self
.encoded_args
):
57 if kwargs
.has_key('id'):
58 uri
+= "/%s" %(kwargs
['id'])
60 self
.encoded_args
= urlencode(kwargs
.items())
66 argStr
= "?%s" %(self
.encoded_args
)
68 argData
= self
.encoded_args
72 headers
["X-Twitter-Client"] = self
.agent
74 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
75 self
.username
, self
.password
))
77 req
= urllib2
.Request(
78 "http://%s/%s.%s%s" %(self
.domain
, uri
, self
.format
, argStr
),
82 handle
= urllib2
.urlopen(req
)
83 if "json" == self
.format
:
84 return json
.loads(handle
.read())
87 except urllib2
.HTTPError
, e
:
92 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
93 e
.code
, uri
, self
.format
, encoded_kwargs
, e
.fp
.read()))
95 class Twitter(TwitterCall
):
97 The minimalist yet fully featured Twitter API class.
99 Get RESTful data by accessing members of this class. The result
100 is decoded python objects (lists and dicts).
102 The Twitter API is documented here:
104 http://apiwiki.twitter.com/
105 http://groups.google.com/group/twitter-development-talk/web/api-documentation
109 twitter = Twitter("hello@foo.com", "password123")
111 # Get the public timeline
112 twitter.statuses.public_timeline()
114 # Get a particular friend's timeline
115 twitter.statuses.friends_timeline(id="billybob")
117 # Also supported (but totally weird)
118 twitter.statuses.friends_timeline.billybob()
120 # Send a direct message
121 twitter.direct_messages.new(
123 text="I think yer swell!")
127 twitter_search = Twitter(domain="search.twitter.com")
129 # Find the latest search trends
130 twitter_search.trends()
132 # Search for the latest News on #gaza
133 twitter_search.search(q="#gaza")
135 Using the data returned::
137 Twitter API calls return decoded JSON. This is converted into
138 a bunch of Python lists, dicts, ints, and strings. For example,
140 x = twitter.statuses.public_timeline()
142 # The first 'tweet' in the timeline
145 # The screen name of the user who wrote the first 'tweet'
146 x[0]['user']['screen_name']
148 Getting raw XML data::
150 If you prefer to get your Twitter data in XML format, pass
151 format="xml" to the Twitter object when you instantiate it:
153 twitter = Twitter(format="xml")
155 The output will not be parsed in any way. It will be a raw string
159 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
162 Create a new twitter API connector using the specified
163 credentials (email and password). Format specifies the output
164 format ("json" (default) or "xml").
166 if (format
not in ("json", "xml")):
167 raise TwitterError("Unknown data format '%s'" %(format))
168 TwitterCall
.__init
__(self
, email
, password
, format
, domain
, "", agent
)
170 __all__
= ["Twitter", "TwitterError"]