]>
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):
30 self
.username
= username
31 self
.password
= password
36 def __getattr__(self
, k
):
38 return object.__getattr
__(self
, k
)
39 except AttributeError:
41 self
.username
, self
.password
, self
.format
, self
.domain
,
42 self
.uri
+ "/" + k
, self
.agent
)
43 def __call__(self
, **kwargs
):
46 for action
in POST_ACTIONS
:
47 if self
.uri
.endswith(action
):
50 kwargs
["source"] = self
.agent
53 if kwargs
.has_key('id'):
54 uri
+= "/%s" %(kwargs
['id'])
56 encoded_kwargs
= urlencode(kwargs
.items())
61 argStr
= "?%s" %(encoded_kwargs)
63 argData
= encoded_kwargs
67 headers
["X-Twitter-Client"] = self
.agent
69 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
70 self
.username
, self
.password
))
72 req
= urllib2
.Request(
73 "http://%s/%s.%s%s" %(self
.domain
, uri
, self
.format
, argStr
),
77 handle
= urllib2
.urlopen(req
)
78 if "json" == self
.format
:
79 return json
.loads(handle
.read())
82 except urllib2
.HTTPError
, e
:
87 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
88 e
.code
, uri
, self
.format
, encoded_kwargs
, e
.fp
.read()))
90 class Twitter(TwitterCall
):
92 The minimalist yet fully featured Twitter API class.
94 Get RESTful data by accessing members of this class. The result
95 is decoded python objects (lists and dicts).
97 The Twitter API is documented here:
99 http://apiwiki.twitter.com/
100 http://groups.google.com/group/twitter-development-talk/web/api-documentation
104 twitter = Twitter("hello@foo.com", "password123")
106 # Get the public timeline
107 twitter.statuses.public_timeline()
109 # Get a particular friend's timeline
110 twitter.statuses.friends_timeline(id="billybob")
112 # Also supported (but totally weird)
113 twitter.statuses.friends_timeline.billybob()
115 # Send a direct message
116 twitter.direct_messages.new(
118 text="I think yer swell!")
122 twitter_search = Twitter(domain="search.twitter.com")
124 # Find the latest search trends
125 twitter_search.trends()
127 # Search for the latest News on #gaza
128 twitter_search.search(q="#gaza")
130 Using the data returned::
132 Twitter API calls return decoded JSON. This is converted into
133 a bunch of Python lists, dicts, ints, and strings. For example,
135 x = twitter.statuses.public_timeline()
137 # The first 'tweet' in the timeline
140 # The screen name of the user who wrote the first 'tweet'
141 x[0]['user']['screen_name']
143 Getting raw XML data::
145 If you prefer to get your Twitter data in XML format, pass
146 format="xml" to the Twitter object when you instantiate it:
148 twitter = Twitter(format="xml")
150 The output will not be parsed in any way. It will be a raw string
154 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
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").
161 if (format
not in ("json", "xml")):
162 raise TwitterError("Unknown data format '%s'" %(format))
163 TwitterCall
.__init
__(self
, email
, password
, format
, domain
, "", agent
)
165 __all__
= ["Twitter", "TwitterError"]