twitter.py 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829
  1. #!/usr/bin/env python
  2. #
  3. # vim: sw=2 ts=2 sts=2
  4. #
  5. # Copyright 2007 The Python-Twitter Developers
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. '''A library that provides a Python interface to the Twitter API'''
  19. __author__ = 'python-twitter@googlegroups.com'
  20. __version__ = '1.0.1'
  21. import calendar
  22. import datetime
  23. import httplib
  24. import os
  25. import rfc822
  26. import sys
  27. import tempfile
  28. import textwrap
  29. import time
  30. import urllib
  31. import urllib2
  32. import urlparse
  33. import gzip
  34. import StringIO
  35. try:
  36. # Python >= 2.6
  37. import json as simplejson
  38. except ImportError:
  39. try:
  40. # Python < 2.6
  41. import simplejson
  42. except ImportError:
  43. try:
  44. # Google App Engine
  45. from django.utils import simplejson
  46. except ImportError:
  47. raise ImportError, "Unable to load a json library"
  48. # parse_qsl moved to urlparse module in v2.6
  49. try:
  50. from urlparse import parse_qsl, parse_qs
  51. except ImportError:
  52. from cgi import parse_qsl, parse_qs
  53. try:
  54. from hashlib import md5
  55. except ImportError:
  56. from md5 import md5
  57. import oauth2 as oauth
  58. CHARACTER_LIMIT = 140
  59. # A singleton representing a lazily instantiated FileCache.
  60. DEFAULT_CACHE = object()
  61. class TwitterError(Exception):
  62. '''Base class for Twitter errors'''
  63. @property
  64. def message(self):
  65. '''Returns the first argument used to construct this error.'''
  66. return self.args[0]
  67. class Status(object):
  68. '''A class representing the Status structure used by the twitter API.
  69. The Status structure exposes the following properties:
  70. status.created_at
  71. status.created_at_in_seconds # read only
  72. status.favorited
  73. status.favorite_count
  74. status.in_reply_to_screen_name
  75. status.in_reply_to_user_id
  76. status.in_reply_to_status_id
  77. status.truncated
  78. status.source
  79. status.id
  80. status.text
  81. status.location
  82. status.relative_created_at # read only
  83. status.user
  84. status.urls
  85. status.user_mentions
  86. status.hashtags
  87. status.geo
  88. status.place
  89. status.coordinates
  90. status.contributors
  91. '''
  92. def __init__(self,
  93. created_at=None,
  94. favorited=None,
  95. favorite_count=None,
  96. id=None,
  97. text=None,
  98. location=None,
  99. user=None,
  100. in_reply_to_screen_name=None,
  101. in_reply_to_user_id=None,
  102. in_reply_to_status_id=None,
  103. truncated=None,
  104. source=None,
  105. now=None,
  106. urls=None,
  107. user_mentions=None,
  108. hashtags=None,
  109. media=None,
  110. geo=None,
  111. place=None,
  112. coordinates=None,
  113. contributors=None,
  114. retweeted=None,
  115. retweeted_status=None,
  116. current_user_retweet=None,
  117. retweet_count=None,
  118. possibly_sensitive=None,
  119. scopes=None,
  120. withheld_copyright=None,
  121. withheld_in_countries=None,
  122. withheld_scope=None):
  123. '''An object to hold a Twitter status message.
  124. This class is normally instantiated by the twitter.Api class and
  125. returned in a sequence.
  126. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
  127. Args:
  128. created_at:
  129. The time this status message was posted. [Optional]
  130. favorited:
  131. Whether this is a favorite of the authenticated user. [Optional]
  132. favorite_count:
  133. Number of times this status message has been favorited. [Optional]
  134. id:
  135. The unique id of this status message. [Optional]
  136. text:
  137. The text of this status message. [Optional]
  138. location:
  139. the geolocation string associated with this message. [Optional]
  140. relative_created_at:
  141. A human readable string representing the posting time. [Optional]
  142. user:
  143. A twitter.User instance representing the person posting the
  144. message. [Optional]
  145. now:
  146. The current time, if the client chooses to set it.
  147. Defaults to the wall clock time. [Optional]
  148. urls:
  149. user_mentions:
  150. hashtags:
  151. geo:
  152. place:
  153. coordinates:
  154. contributors:
  155. retweeted:
  156. retweeted_status:
  157. current_user_retweet:
  158. retweet_count:
  159. possibly_sensitive:
  160. scopes:
  161. withheld_copyright:
  162. withheld_in_countries:
  163. withheld_scope:
  164. '''
  165. self.created_at = created_at
  166. self.favorited = favorited
  167. self.favorite_count = favorite_count
  168. self.id = id
  169. self.text = text
  170. self.location = location
  171. self.user = user
  172. self.now = now
  173. self.in_reply_to_screen_name = in_reply_to_screen_name
  174. self.in_reply_to_user_id = in_reply_to_user_id
  175. self.in_reply_to_status_id = in_reply_to_status_id
  176. self.truncated = truncated
  177. self.retweeted = retweeted
  178. self.source = source
  179. self.urls = urls
  180. self.user_mentions = user_mentions
  181. self.hashtags = hashtags
  182. self.media = media
  183. self.geo = geo
  184. self.place = place
  185. self.coordinates = coordinates
  186. self.contributors = contributors
  187. self.retweeted_status = retweeted_status
  188. self.current_user_retweet = current_user_retweet
  189. self.retweet_count = retweet_count
  190. self.possibly_sensitive = possibly_sensitive
  191. self.scopes = scopes
  192. self.withheld_copyright = withheld_copyright
  193. self.withheld_in_countries = withheld_in_countries
  194. self.withheld_scope = withheld_scope
  195. def GetCreatedAt(self):
  196. '''Get the time this status message was posted.
  197. Returns:
  198. The time this status message was posted
  199. '''
  200. return self._created_at
  201. def SetCreatedAt(self, created_at):
  202. '''Set the time this status message was posted.
  203. Args:
  204. created_at:
  205. The time this status message was created
  206. '''
  207. self._created_at = created_at
  208. created_at = property(GetCreatedAt, SetCreatedAt,
  209. doc='The time this status message was posted.')
  210. def GetCreatedAtInSeconds(self):
  211. '''Get the time this status message was posted, in seconds since the epoch.
  212. Returns:
  213. The time this status message was posted, in seconds since the epoch.
  214. '''
  215. return calendar.timegm(rfc822.parsedate(self.created_at))
  216. created_at_in_seconds = property(GetCreatedAtInSeconds,
  217. doc="The time this status message was "
  218. "posted, in seconds since the epoch")
  219. def GetFavorited(self):
  220. '''Get the favorited setting of this status message.
  221. Returns:
  222. True if this status message is favorited; False otherwise
  223. '''
  224. return self._favorited
  225. def SetFavorited(self, favorited):
  226. '''Set the favorited state of this status message.
  227. Args:
  228. favorited:
  229. boolean True/False favorited state of this status message
  230. '''
  231. self._favorited = favorited
  232. favorited = property(GetFavorited, SetFavorited,
  233. doc='The favorited state of this status message.')
  234. def GetFavoriteCount(self):
  235. '''Get the favorite count of this status message.
  236. Returns:
  237. number of times this status message has been favorited
  238. '''
  239. return self._favorite_count
  240. def SetFavoriteCount(self, favorite_count):
  241. '''Set the favorited state of this status message.
  242. Args:
  243. favorite_count:
  244. int number of favorites for this status message
  245. '''
  246. self._favorite_count = favorite_count
  247. favorite_count = property(GetFavoriteCount, SetFavoriteCount,
  248. doc='The number of favorites for this status message.')
  249. def GetId(self):
  250. '''Get the unique id of this status message.
  251. Returns:
  252. The unique id of this status message
  253. '''
  254. return self._id
  255. def SetId(self, id):
  256. '''Set the unique id of this status message.
  257. Args:
  258. id:
  259. The unique id of this status message
  260. '''
  261. self._id = id
  262. id = property(GetId, SetId,
  263. doc='The unique id of this status message.')
  264. def GetInReplyToScreenName(self):
  265. return self._in_reply_to_screen_name
  266. def SetInReplyToScreenName(self, in_reply_to_screen_name):
  267. self._in_reply_to_screen_name = in_reply_to_screen_name
  268. in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName,
  269. doc='')
  270. def GetInReplyToUserId(self):
  271. return self._in_reply_to_user_id
  272. def SetInReplyToUserId(self, in_reply_to_user_id):
  273. self._in_reply_to_user_id = in_reply_to_user_id
  274. in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId,
  275. doc='')
  276. def GetInReplyToStatusId(self):
  277. return self._in_reply_to_status_id
  278. def SetInReplyToStatusId(self, in_reply_to_status_id):
  279. self._in_reply_to_status_id = in_reply_to_status_id
  280. in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId,
  281. doc='')
  282. def GetTruncated(self):
  283. return self._truncated
  284. def SetTruncated(self, truncated):
  285. self._truncated = truncated
  286. truncated = property(GetTruncated, SetTruncated,
  287. doc='')
  288. def GetRetweeted(self):
  289. return self._retweeted
  290. def SetRetweeted(self, retweeted):
  291. self._retweeted = retweeted
  292. retweeted = property(GetRetweeted, SetRetweeted,
  293. doc='')
  294. def GetSource(self):
  295. return self._source
  296. def SetSource(self, source):
  297. self._source = source
  298. source = property(GetSource, SetSource,
  299. doc='')
  300. def GetText(self):
  301. '''Get the text of this status message.
  302. Returns:
  303. The text of this status message.
  304. '''
  305. return self._text
  306. def SetText(self, text):
  307. '''Set the text of this status message.
  308. Args:
  309. text:
  310. The text of this status message
  311. '''
  312. self._text = text
  313. text = property(GetText, SetText,
  314. doc='The text of this status message')
  315. def GetLocation(self):
  316. '''Get the geolocation associated with this status message
  317. Returns:
  318. The geolocation string of this status message.
  319. '''
  320. return self._location
  321. def SetLocation(self, location):
  322. '''Set the geolocation associated with this status message
  323. Args:
  324. location:
  325. The geolocation string of this status message
  326. '''
  327. self._location = location
  328. location = property(GetLocation, SetLocation,
  329. doc='The geolocation string of this status message')
  330. def GetRelativeCreatedAt(self):
  331. '''Get a human readable string representing the posting time
  332. Returns:
  333. A human readable string representing the posting time
  334. '''
  335. fudge = 1.25
  336. delta = long(self.now) - long(self.created_at_in_seconds)
  337. if delta < (1 * fudge):
  338. return 'about a second ago'
  339. elif delta < (60 * (1/fudge)):
  340. return 'about %d seconds ago' % (delta)
  341. elif delta < (60 * fudge):
  342. return 'about a minute ago'
  343. elif delta < (60 * 60 * (1/fudge)):
  344. return 'about %d minutes ago' % (delta / 60)
  345. elif delta < (60 * 60 * fudge) or delta / (60 * 60) == 1:
  346. return 'about an hour ago'
  347. elif delta < (60 * 60 * 24 * (1/fudge)):
  348. return 'about %d hours ago' % (delta / (60 * 60))
  349. elif delta < (60 * 60 * 24 * fudge) or delta / (60 * 60 * 24) == 1:
  350. return 'about a day ago'
  351. else:
  352. return 'about %d days ago' % (delta / (60 * 60 * 24))
  353. relative_created_at = property(GetRelativeCreatedAt,
  354. doc='Get a human readable string representing '
  355. 'the posting time')
  356. def GetUser(self):
  357. '''Get a twitter.User representing the entity posting this status message.
  358. Returns:
  359. A twitter.User representing the entity posting this status message
  360. '''
  361. return self._user
  362. def SetUser(self, user):
  363. '''Set a twitter.User representing the entity posting this status message.
  364. Args:
  365. user:
  366. A twitter.User representing the entity posting this status message
  367. '''
  368. self._user = user
  369. user = property(GetUser, SetUser,
  370. doc='A twitter.User representing the entity posting this '
  371. 'status message')
  372. def GetNow(self):
  373. '''Get the wallclock time for this status message.
  374. Used to calculate relative_created_at. Defaults to the time
  375. the object was instantiated.
  376. Returns:
  377. Whatever the status instance believes the current time to be,
  378. in seconds since the epoch.
  379. '''
  380. if self._now is None:
  381. self._now = time.time()
  382. return self._now
  383. def SetNow(self, now):
  384. '''Set the wallclock time for this status message.
  385. Used to calculate relative_created_at. Defaults to the time
  386. the object was instantiated.
  387. Args:
  388. now:
  389. The wallclock time for this instance.
  390. '''
  391. self._now = now
  392. now = property(GetNow, SetNow,
  393. doc='The wallclock time for this status instance.')
  394. def GetGeo(self):
  395. return self._geo
  396. def SetGeo(self, geo):
  397. self._geo = geo
  398. geo = property(GetGeo, SetGeo,
  399. doc='')
  400. def GetPlace(self):
  401. return self._place
  402. def SetPlace(self, place):
  403. self._place = place
  404. place = property(GetPlace, SetPlace,
  405. doc='')
  406. def GetCoordinates(self):
  407. return self._coordinates
  408. def SetCoordinates(self, coordinates):
  409. self._coordinates = coordinates
  410. coordinates = property(GetCoordinates, SetCoordinates,
  411. doc='')
  412. def GetContributors(self):
  413. return self._contributors
  414. def SetContributors(self, contributors):
  415. self._contributors = contributors
  416. contributors = property(GetContributors, SetContributors,
  417. doc='')
  418. def GetRetweeted_status(self):
  419. return self._retweeted_status
  420. def SetRetweeted_status(self, retweeted_status):
  421. self._retweeted_status = retweeted_status
  422. retweeted_status = property(GetRetweeted_status, SetRetweeted_status,
  423. doc='')
  424. def GetRetweetCount(self):
  425. return self._retweet_count
  426. def SetRetweetCount(self, retweet_count):
  427. self._retweet_count = retweet_count
  428. retweet_count = property(GetRetweetCount, SetRetweetCount,
  429. doc='')
  430. def GetCurrent_user_retweet(self):
  431. return self._current_user_retweet
  432. def SetCurrent_user_retweet(self, current_user_retweet):
  433. self._current_user_retweet = current_user_retweet
  434. current_user_retweet = property(GetCurrent_user_retweet, SetCurrent_user_retweet,
  435. doc='')
  436. def GetPossibly_sensitive(self):
  437. return self._possibly_sensitive
  438. def SetPossibly_sensitive(self, possibly_sensitive):
  439. self._possibly_sensitive = possibly_sensitive
  440. possibly_sensitive = property(GetPossibly_sensitive, SetPossibly_sensitive,
  441. doc='')
  442. def GetScopes(self):
  443. return self._scopes
  444. def SetScopes(self, scopes):
  445. self._scopes = scopes
  446. scopes = property(GetScopes, SetScopes, doc='')
  447. def GetWithheld_copyright(self):
  448. return self._withheld_copyright
  449. def SetWithheld_copyright(self, withheld_copyright):
  450. self._withheld_copyright = withheld_copyright
  451. withheld_copyright = property(GetWithheld_copyright, SetWithheld_copyright,
  452. doc='')
  453. def GetWithheld_in_countries(self):
  454. return self._withheld_in_countries
  455. def SetWithheld_in_countries(self, withheld_in_countries):
  456. self._withheld_in_countries = withheld_in_countries
  457. withheld_in_countries = property(GetWithheld_in_countries, SetWithheld_in_countries,
  458. doc='')
  459. def GetWithheld_scope(self):
  460. return self._withheld_scope
  461. def SetWithheld_scope(self, withheld_scope):
  462. self._withheld_scope = withheld_scope
  463. withheld_scope = property(GetWithheld_scope, SetWithheld_scope,
  464. doc='')
  465. def __ne__(self, other):
  466. return not self.__eq__(other)
  467. def __eq__(self, other):
  468. try:
  469. return other and \
  470. self.created_at == other.created_at and \
  471. self.id == other.id and \
  472. self.text == other.text and \
  473. self.location == other.location and \
  474. self.user == other.user and \
  475. self.in_reply_to_screen_name == other.in_reply_to_screen_name and \
  476. self.in_reply_to_user_id == other.in_reply_to_user_id and \
  477. self.in_reply_to_status_id == other.in_reply_to_status_id and \
  478. self.truncated == other.truncated and \
  479. self.retweeted == other.retweeted and \
  480. self.favorited == other.favorited and \
  481. self.favorite_count == other.favorite_count and \
  482. self.source == other.source and \
  483. self.geo == other.geo and \
  484. self.place == other.place and \
  485. self.coordinates == other.coordinates and \
  486. self.contributors == other.contributors and \
  487. self.retweeted_status == other.retweeted_status and \
  488. self.retweet_count == other.retweet_count and \
  489. self.current_user_retweet == other.current_user_retweet and \
  490. self.possibly_sensitive == other.possibly_sensitive and \
  491. self.scopes == other.scopes and \
  492. self.withheld_copyright == other.withheld_copyright and \
  493. self.withheld_in_countries == other.withheld_in_countries and \
  494. self.withheld_scope == other.withheld_scope
  495. except AttributeError:
  496. return False
  497. def __str__(self):
  498. '''A string representation of this twitter.Status instance.
  499. The return value is the same as the JSON string representation.
  500. Returns:
  501. A string representation of this twitter.Status instance.
  502. '''
  503. return self.AsJsonString()
  504. def AsJsonString(self):
  505. '''A JSON string representation of this twitter.Status instance.
  506. Returns:
  507. A JSON string representation of this twitter.Status instance
  508. '''
  509. return simplejson.dumps(self.AsDict(), sort_keys=True)
  510. def AsDict(self):
  511. '''A dict representation of this twitter.Status instance.
  512. The return value uses the same key names as the JSON representation.
  513. Return:
  514. A dict representing this twitter.Status instance
  515. '''
  516. data = {}
  517. if self.created_at:
  518. data['created_at'] = self.created_at
  519. if self.favorited:
  520. data['favorited'] = self.favorited
  521. if self.favorite_count:
  522. data['favorite_count'] = self.favorite_count
  523. if self.id:
  524. data['id'] = self.id
  525. if self.text:
  526. data['text'] = self.text
  527. if self.location:
  528. data['location'] = self.location
  529. if self.user:
  530. data['user'] = self.user.AsDict()
  531. if self.in_reply_to_screen_name:
  532. data['in_reply_to_screen_name'] = self.in_reply_to_screen_name
  533. if self.in_reply_to_user_id:
  534. data['in_reply_to_user_id'] = self.in_reply_to_user_id
  535. if self.in_reply_to_status_id:
  536. data['in_reply_to_status_id'] = self.in_reply_to_status_id
  537. if self.truncated is not None:
  538. data['truncated'] = self.truncated
  539. if self.retweeted is not None:
  540. data['retweeted'] = self.retweeted
  541. if self.favorited is not None:
  542. data['favorited'] = self.favorited
  543. if self.source:
  544. data['source'] = self.source
  545. if self.geo:
  546. data['geo'] = self.geo
  547. if self.place:
  548. data['place'] = self.place
  549. if self.coordinates:
  550. data['coordinates'] = self.coordinates
  551. if self.contributors:
  552. data['contributors'] = self.contributors
  553. if self.hashtags:
  554. data['hashtags'] = [h.text for h in self.hashtags]
  555. if self.retweeted_status:
  556. data['retweeted_status'] = self.retweeted_status.AsDict()
  557. if self.retweet_count:
  558. data['retweet_count'] = self.retweet_count
  559. if self.urls:
  560. data['urls'] = dict([(url.url, url.expanded_url) for url in self.urls])
  561. if self.user_mentions:
  562. data['user_mentions'] = [um.AsDict() for um in self.user_mentions]
  563. if self.current_user_retweet:
  564. data['current_user_retweet'] = self.current_user_retweet
  565. if self.possibly_sensitive:
  566. data['possibly_sensitive'] = self.possibly_sensitive
  567. if self.scopes:
  568. data['scopes'] = self.scopes
  569. if self.withheld_copyright:
  570. data['withheld_copyright'] = self.withheld_copyright
  571. if self.withheld_in_countries:
  572. data['withheld_in_countries'] = self.withheld_in_countries
  573. if self.withheld_scope:
  574. data['withheld_scope'] = self.withheld_scope
  575. return data
  576. @staticmethod
  577. def NewFromJsonDict(data):
  578. '''Create a new instance based on a JSON dict.
  579. Args:
  580. data: A JSON dict, as converted from the JSON in the twitter API
  581. Returns:
  582. A twitter.Status instance
  583. '''
  584. if 'user' in data:
  585. user = User.NewFromJsonDict(data['user'])
  586. else:
  587. user = None
  588. if 'retweeted_status' in data:
  589. retweeted_status = Status.NewFromJsonDict(data['retweeted_status'])
  590. else:
  591. retweeted_status = None
  592. if 'current_user_retweet' in data:
  593. current_user_retweet = data['current_user_retweet']['id']
  594. else:
  595. current_user_retweet = None
  596. urls = None
  597. user_mentions = None
  598. hashtags = None
  599. media = None
  600. if 'entities' in data:
  601. if 'urls' in data['entities']:
  602. urls = [Url.NewFromJsonDict(u) for u in data['entities']['urls']]
  603. if 'user_mentions' in data['entities']:
  604. user_mentions = [User.NewFromJsonDict(u) for u in data['entities']['user_mentions']]
  605. if 'hashtags' in data['entities']:
  606. hashtags = [Hashtag.NewFromJsonDict(h) for h in data['entities']['hashtags']]
  607. if 'media' in data['entities']:
  608. media = data['entities']['media']
  609. else:
  610. media = []
  611. return Status(created_at=data.get('created_at', None),
  612. favorited=data.get('favorited', None),
  613. favorite_count=data.get('favorite_count', None),
  614. id=data.get('id', None),
  615. text=data.get('text', None),
  616. location=data.get('location', None),
  617. in_reply_to_screen_name=data.get('in_reply_to_screen_name', None),
  618. in_reply_to_user_id=data.get('in_reply_to_user_id', None),
  619. in_reply_to_status_id=data.get('in_reply_to_status_id', None),
  620. truncated=data.get('truncated', None),
  621. retweeted=data.get('retweeted', None),
  622. source=data.get('source', None),
  623. user=user,
  624. urls=urls,
  625. user_mentions=user_mentions,
  626. hashtags=hashtags,
  627. media=media,
  628. geo=data.get('geo', None),
  629. place=data.get('place', None),
  630. coordinates=data.get('coordinates', None),
  631. contributors=data.get('contributors', None),
  632. retweeted_status=retweeted_status,
  633. current_user_retweet=current_user_retweet,
  634. retweet_count=data.get('retweet_count', None),
  635. possibly_sensitive=data.get('possibly_sensitive', None),
  636. scopes=data.get('scopes', None),
  637. withheld_copyright=data.get('withheld_copyright', None),
  638. withheld_in_countries=data.get('withheld_in_countries', None),
  639. withheld_scope=data.get('withheld_scope', None))
  640. class User(object):
  641. '''A class representing the User structure used by the twitter API.
  642. The User structure exposes the following properties:
  643. user.id
  644. user.name
  645. user.screen_name
  646. user.location
  647. user.description
  648. user.profile_image_url
  649. user.profile_background_tile
  650. user.profile_background_image_url
  651. user.profile_sidebar_fill_color
  652. user.profile_background_color
  653. user.profile_link_color
  654. user.profile_text_color
  655. user.protected
  656. user.utc_offset
  657. user.time_zone
  658. user.url
  659. user.status
  660. user.statuses_count
  661. user.followers_count
  662. user.friends_count
  663. user.favourites_count
  664. user.geo_enabled
  665. user.verified
  666. user.lang
  667. user.notifications
  668. user.contributors_enabled
  669. user.created_at
  670. user.listed_count
  671. '''
  672. def __init__(self,
  673. id=None,
  674. name=None,
  675. screen_name=None,
  676. location=None,
  677. description=None,
  678. profile_image_url=None,
  679. profile_background_tile=None,
  680. profile_background_image_url=None,
  681. profile_sidebar_fill_color=None,
  682. profile_background_color=None,
  683. profile_link_color=None,
  684. profile_text_color=None,
  685. protected=None,
  686. utc_offset=None,
  687. time_zone=None,
  688. followers_count=None,
  689. friends_count=None,
  690. statuses_count=None,
  691. favourites_count=None,
  692. url=None,
  693. status=None,
  694. geo_enabled=None,
  695. verified=None,
  696. lang=None,
  697. notifications=None,
  698. contributors_enabled=None,
  699. created_at=None,
  700. listed_count=None):
  701. self.id = id
  702. self.name = name
  703. self.screen_name = screen_name
  704. self.location = location
  705. self.description = description
  706. self.profile_image_url = profile_image_url
  707. self.profile_background_tile = profile_background_tile
  708. self.profile_background_image_url = profile_background_image_url
  709. self.profile_sidebar_fill_color = profile_sidebar_fill_color
  710. self.profile_background_color = profile_background_color
  711. self.profile_link_color = profile_link_color
  712. self.profile_text_color = profile_text_color
  713. self.protected = protected
  714. self.utc_offset = utc_offset
  715. self.time_zone = time_zone
  716. self.followers_count = followers_count
  717. self.friends_count = friends_count
  718. self.statuses_count = statuses_count
  719. self.favourites_count = favourites_count
  720. self.url = url
  721. self.status = status
  722. self.geo_enabled = geo_enabled
  723. self.verified = verified
  724. self.lang = lang
  725. self.notifications = notifications
  726. self.contributors_enabled = contributors_enabled
  727. self.created_at = created_at
  728. self.listed_count = listed_count
  729. def GetId(self):
  730. '''Get the unique id of this user.
  731. Returns:
  732. The unique id of this user
  733. '''
  734. return self._id
  735. def SetId(self, id):
  736. '''Set the unique id of this user.
  737. Args:
  738. id: The unique id of this user.
  739. '''
  740. self._id = id
  741. id = property(GetId, SetId,
  742. doc='The unique id of this user.')
  743. def GetName(self):
  744. '''Get the real name of this user.
  745. Returns:
  746. The real name of this user
  747. '''
  748. return self._name
  749. def SetName(self, name):
  750. '''Set the real name of this user.
  751. Args:
  752. name: The real name of this user
  753. '''
  754. self._name = name
  755. name = property(GetName, SetName,
  756. doc='The real name of this user.')
  757. def GetScreenName(self):
  758. '''Get the short twitter name of this user.
  759. Returns:
  760. The short twitter name of this user
  761. '''
  762. return self._screen_name
  763. def SetScreenName(self, screen_name):
  764. '''Set the short twitter name of this user.
  765. Args:
  766. screen_name: the short twitter name of this user
  767. '''
  768. self._screen_name = screen_name
  769. screen_name = property(GetScreenName, SetScreenName,
  770. doc='The short twitter name of this user.')
  771. def GetLocation(self):
  772. '''Get the geographic location of this user.
  773. Returns:
  774. The geographic location of this user
  775. '''
  776. return self._location
  777. def SetLocation(self, location):
  778. '''Set the geographic location of this user.
  779. Args:
  780. location: The geographic location of this user
  781. '''
  782. self._location = location
  783. location = property(GetLocation, SetLocation,
  784. doc='The geographic location of this user.')
  785. def GetDescription(self):
  786. '''Get the short text description of this user.
  787. Returns:
  788. The short text description of this user
  789. '''
  790. return self._description
  791. def SetDescription(self, description):
  792. '''Set the short text description of this user.
  793. Args:
  794. description: The short text description of this user
  795. '''
  796. self._description = description
  797. description = property(GetDescription, SetDescription,
  798. doc='The short text description of this user.')
  799. def GetUrl(self):
  800. '''Get the homepage url of this user.
  801. Returns:
  802. The homepage url of this user
  803. '''
  804. return self._url
  805. def SetUrl(self, url):
  806. '''Set the homepage url of this user.
  807. Args:
  808. url: The homepage url of this user
  809. '''
  810. self._url = url
  811. url = property(GetUrl, SetUrl,
  812. doc='The homepage url of this user.')
  813. def GetProfileImageUrl(self):
  814. '''Get the url of the thumbnail of this user.
  815. Returns:
  816. The url of the thumbnail of this user
  817. '''
  818. return self._profile_image_url
  819. def SetProfileImageUrl(self, profile_image_url):
  820. '''Set the url of the thumbnail of this user.
  821. Args:
  822. profile_image_url: The url of the thumbnail of this user
  823. '''
  824. self._profile_image_url = profile_image_url
  825. profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl,
  826. doc='The url of the thumbnail of this user.')
  827. def GetProfileBackgroundTile(self):
  828. '''Boolean for whether to tile the profile background image.
  829. Returns:
  830. True if the background is to be tiled, False if not, None if unset.
  831. '''
  832. return self._profile_background_tile
  833. def SetProfileBackgroundTile(self, profile_background_tile):
  834. '''Set the boolean flag for whether to tile the profile background image.
  835. Args:
  836. profile_background_tile: Boolean flag for whether to tile or not.
  837. '''
  838. self._profile_background_tile = profile_background_tile
  839. profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile,
  840. doc='Boolean for whether to tile the background image.')
  841. def GetProfileBackgroundImageUrl(self):
  842. return self._profile_background_image_url
  843. def SetProfileBackgroundImageUrl(self, profile_background_image_url):
  844. self._profile_background_image_url = profile_background_image_url
  845. profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl,
  846. doc='The url of the profile background of this user.')
  847. def GetProfileSidebarFillColor(self):
  848. return self._profile_sidebar_fill_color
  849. def SetProfileSidebarFillColor(self, profile_sidebar_fill_color):
  850. self._profile_sidebar_fill_color = profile_sidebar_fill_color
  851. profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor)
  852. def GetProfileBackgroundColor(self):
  853. return self._profile_background_color
  854. def SetProfileBackgroundColor(self, profile_background_color):
  855. self._profile_background_color = profile_background_color
  856. profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor)
  857. def GetProfileLinkColor(self):
  858. return self._profile_link_color
  859. def SetProfileLinkColor(self, profile_link_color):
  860. self._profile_link_color = profile_link_color
  861. profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor)
  862. def GetProfileTextColor(self):
  863. return self._profile_text_color
  864. def SetProfileTextColor(self, profile_text_color):
  865. self._profile_text_color = profile_text_color
  866. profile_text_color = property(GetProfileTextColor, SetProfileTextColor)
  867. def GetProtected(self):
  868. return self._protected
  869. def SetProtected(self, protected):
  870. self._protected = protected
  871. protected = property(GetProtected, SetProtected)
  872. def GetUtcOffset(self):
  873. return self._utc_offset
  874. def SetUtcOffset(self, utc_offset):
  875. self._utc_offset = utc_offset
  876. utc_offset = property(GetUtcOffset, SetUtcOffset)
  877. def GetTimeZone(self):
  878. '''Returns the current time zone string for the user.
  879. Returns:
  880. The descriptive time zone string for the user.
  881. '''
  882. return self._time_zone
  883. def SetTimeZone(self, time_zone):
  884. '''Sets the user's time zone string.
  885. Args:
  886. time_zone:
  887. The descriptive time zone to assign for the user.
  888. '''
  889. self._time_zone = time_zone
  890. time_zone = property(GetTimeZone, SetTimeZone)
  891. def GetStatus(self):
  892. '''Get the latest twitter.Status of this user.
  893. Returns:
  894. The latest twitter.Status of this user
  895. '''
  896. return self._status
  897. def SetStatus(self, status):
  898. '''Set the latest twitter.Status of this user.
  899. Args:
  900. status:
  901. The latest twitter.Status of this user
  902. '''
  903. self._status = status
  904. status = property(GetStatus, SetStatus,
  905. doc='The latest twitter.Status of this user.')
  906. def GetFriendsCount(self):
  907. '''Get the friend count for this user.
  908. Returns:
  909. The number of users this user has befriended.
  910. '''
  911. return self._friends_count
  912. def SetFriendsCount(self, count):
  913. '''Set the friend count for this user.
  914. Args:
  915. count:
  916. The number of users this user has befriended.
  917. '''
  918. self._friends_count = count
  919. friends_count = property(GetFriendsCount, SetFriendsCount,
  920. doc='The number of friends for this user.')
  921. def GetListedCount(self):
  922. '''Get the listed count for this user.
  923. Returns:
  924. The number of lists this user belongs to.
  925. '''
  926. return self._listed_count
  927. def SetListedCount(self, count):
  928. '''Set the listed count for this user.
  929. Args:
  930. count:
  931. The number of lists this user belongs to.
  932. '''
  933. self._listed_count = count
  934. listed_count = property(GetListedCount, SetListedCount,
  935. doc='The number of lists this user belongs to.')
  936. def GetFollowersCount(self):
  937. '''Get the follower count for this user.
  938. Returns:
  939. The number of users following this user.
  940. '''
  941. return self._followers_count
  942. def SetFollowersCount(self, count):
  943. '''Set the follower count for this user.
  944. Args:
  945. count:
  946. The number of users following this user.
  947. '''
  948. self._followers_count = count
  949. followers_count = property(GetFollowersCount, SetFollowersCount,
  950. doc='The number of users following this user.')
  951. def GetStatusesCount(self):
  952. '''Get the number of status updates for this user.
  953. Returns:
  954. The number of status updates for this user.
  955. '''
  956. return self._statuses_count
  957. def SetStatusesCount(self, count):
  958. '''Set the status update count for this user.
  959. Args:
  960. count:
  961. The number of updates for this user.
  962. '''
  963. self._statuses_count = count
  964. statuses_count = property(GetStatusesCount, SetStatusesCount,
  965. doc='The number of updates for this user.')
  966. def GetFavouritesCount(self):
  967. '''Get the number of favourites for this user.
  968. Returns:
  969. The number of favourites for this user.
  970. '''
  971. return self._favourites_count
  972. def SetFavouritesCount(self, count):
  973. '''Set the favourite count for this user.
  974. Args:
  975. count:
  976. The number of favourites for this user.
  977. '''
  978. self._favourites_count = count
  979. favourites_count = property(GetFavouritesCount, SetFavouritesCount,
  980. doc='The number of favourites for this user.')
  981. def GetGeoEnabled(self):
  982. '''Get the setting of geo_enabled for this user.
  983. Returns:
  984. True/False if Geo tagging is enabled
  985. '''
  986. return self._geo_enabled
  987. def SetGeoEnabled(self, geo_enabled):
  988. '''Set the latest twitter.geo_enabled of this user.
  989. Args:
  990. geo_enabled:
  991. True/False if Geo tagging is to be enabled
  992. '''
  993. self._geo_enabled = geo_enabled
  994. geo_enabled = property(GetGeoEnabled, SetGeoEnabled,
  995. doc='The value of twitter.geo_enabled for this user.')
  996. def GetVerified(self):
  997. '''Get the setting of verified for this user.
  998. Returns:
  999. True/False if user is a verified account
  1000. '''
  1001. return self._verified
  1002. def SetVerified(self, verified):
  1003. '''Set twitter.verified for this user.
  1004. Args:
  1005. verified:
  1006. True/False if user is a verified account
  1007. '''
  1008. self._verified = verified
  1009. verified = property(GetVerified, SetVerified,
  1010. doc='The value of twitter.verified for this user.')
  1011. def GetLang(self):
  1012. '''Get the setting of lang for this user.
  1013. Returns:
  1014. language code of the user
  1015. '''
  1016. return self._lang
  1017. def SetLang(self, lang):
  1018. '''Set twitter.lang for this user.
  1019. Args:
  1020. lang:
  1021. language code for the user
  1022. '''
  1023. self._lang = lang
  1024. lang = property(GetLang, SetLang,
  1025. doc='The value of twitter.lang for this user.')
  1026. def GetNotifications(self):
  1027. '''Get the setting of notifications for this user.
  1028. Returns:
  1029. True/False for the notifications setting of the user
  1030. '''
  1031. return self._notifications
  1032. def SetNotifications(self, notifications):
  1033. '''Set twitter.notifications for this user.
  1034. Args:
  1035. notifications:
  1036. True/False notifications setting for the user
  1037. '''
  1038. self._notifications = notifications
  1039. notifications = property(GetNotifications, SetNotifications,
  1040. doc='The value of twitter.notifications for this user.')
  1041. def GetContributorsEnabled(self):
  1042. '''Get the setting of contributors_enabled for this user.
  1043. Returns:
  1044. True/False contributors_enabled of the user
  1045. '''
  1046. return self._contributors_enabled
  1047. def SetContributorsEnabled(self, contributors_enabled):
  1048. '''Set twitter.contributors_enabled for this user.
  1049. Args:
  1050. contributors_enabled:
  1051. True/False contributors_enabled setting for the user
  1052. '''
  1053. self._contributors_enabled = contributors_enabled
  1054. contributors_enabled = property(GetContributorsEnabled, SetContributorsEnabled,
  1055. doc='The value of twitter.contributors_enabled for this user.')
  1056. def GetCreatedAt(self):
  1057. '''Get the setting of created_at for this user.
  1058. Returns:
  1059. created_at value of the user
  1060. '''
  1061. return self._created_at
  1062. def SetCreatedAt(self, created_at):
  1063. '''Set twitter.created_at for this user.
  1064. Args:
  1065. created_at:
  1066. created_at value for the user
  1067. '''
  1068. self._created_at = created_at
  1069. created_at = property(GetCreatedAt, SetCreatedAt,
  1070. doc='The value of twitter.created_at for this user.')
  1071. def __ne__(self, other):
  1072. return not self.__eq__(other)
  1073. def __eq__(self, other):
  1074. try:
  1075. return other and \
  1076. self.id == other.id and \
  1077. self.name == other.name and \
  1078. self.screen_name == other.screen_name and \
  1079. self.location == other.location and \
  1080. self.description == other.description and \
  1081. self.profile_image_url == other.profile_image_url and \
  1082. self.profile_background_tile == other.profile_background_tile and \
  1083. self.profile_background_image_url == other.profile_background_image_url and \
  1084. self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \
  1085. self.profile_background_color == other.profile_background_color and \
  1086. self.profile_link_color == other.profile_link_color and \
  1087. self.profile_text_color == other.profile_text_color and \
  1088. self.protected == other.protected and \
  1089. self.utc_offset == other.utc_offset and \
  1090. self.time_zone == other.time_zone and \
  1091. self.url == other.url and \
  1092. self.statuses_count == other.statuses_count and \
  1093. self.followers_count == other.followers_count and \
  1094. self.favourites_count == other.favourites_count and \
  1095. self.friends_count == other.friends_count and \
  1096. self.status == other.status and \
  1097. self.geo_enabled == other.geo_enabled and \
  1098. self.verified == other.verified and \
  1099. self.lang == other.lang and \
  1100. self.notifications == other.notifications and \
  1101. self.contributors_enabled == other.contributors_enabled and \
  1102. self.created_at == other.created_at and \
  1103. self.listed_count == other.listed_count
  1104. except AttributeError:
  1105. return False
  1106. def __str__(self):
  1107. '''A string representation of this twitter.User instance.
  1108. The return value is the same as the JSON string representation.
  1109. Returns:
  1110. A string representation of this twitter.User instance.
  1111. '''
  1112. return self.AsJsonString()
  1113. def AsJsonString(self):
  1114. '''A JSON string representation of this twitter.User instance.
  1115. Returns:
  1116. A JSON string representation of this twitter.User instance
  1117. '''
  1118. return simplejson.dumps(self.AsDict(), sort_keys=True)
  1119. def AsDict(self):
  1120. '''A dict representation of this twitter.User instance.
  1121. The return value uses the same key names as the JSON representation.
  1122. Return:
  1123. A dict representing this twitter.User instance
  1124. '''
  1125. data = {}
  1126. if self.id:
  1127. data['id'] = self.id
  1128. if self.name:
  1129. data['name'] = self.name
  1130. if self.screen_name:
  1131. data['screen_name'] = self.screen_name
  1132. if self.location:
  1133. data['location'] = self.location
  1134. if self.description:
  1135. data['description'] = self.description
  1136. if self.profile_image_url:
  1137. data['profile_image_url'] = self.profile_image_url
  1138. if self.profile_background_tile is not None:
  1139. data['profile_background_tile'] = self.profile_background_tile
  1140. if self.profile_background_image_url:
  1141. data['profile_sidebar_fill_color'] = self.profile_background_image_url
  1142. if self.profile_background_color:
  1143. data['profile_background_color'] = self.profile_background_color
  1144. if self.profile_link_color:
  1145. data['profile_link_color'] = self.profile_link_color
  1146. if self.profile_text_color:
  1147. data['profile_text_color'] = self.profile_text_color
  1148. if self.protected is not None:
  1149. data['protected'] = self.protected
  1150. if self.utc_offset:
  1151. data['utc_offset'] = self.utc_offset
  1152. if self.time_zone:
  1153. data['time_zone'] = self.time_zone
  1154. if self.url:
  1155. data['url'] = self.url
  1156. if self.status:
  1157. data['status'] = self.status.AsDict()
  1158. if self.friends_count:
  1159. data['friends_count'] = self.friends_count
  1160. if self.followers_count:
  1161. data['followers_count'] = self.followers_count
  1162. if self.statuses_count:
  1163. data['statuses_count'] = self.statuses_count
  1164. if self.favourites_count:
  1165. data['favourites_count'] = self.favourites_count
  1166. if self.geo_enabled:
  1167. data['geo_enabled'] = self.geo_enabled
  1168. if self.verified:
  1169. data['verified'] = self.verified
  1170. if self.lang:
  1171. data['lang'] = self.lang
  1172. if self.notifications:
  1173. data['notifications'] = self.notifications
  1174. if self.contributors_enabled:
  1175. data['contributors_enabled'] = self.contributors_enabled
  1176. if self.created_at:
  1177. data['created_at'] = self.created_at
  1178. if self.listed_count:
  1179. data['listed_count'] = self.listed_count
  1180. return data
  1181. @staticmethod
  1182. def NewFromJsonDict(data):
  1183. '''Create a new instance based on a JSON dict.
  1184. Args:
  1185. data:
  1186. A JSON dict, as converted from the JSON in the twitter API
  1187. Returns:
  1188. A twitter.User instance
  1189. '''
  1190. if 'status' in data:
  1191. status = Status.NewFromJsonDict(data['status'])
  1192. else:
  1193. status = None
  1194. return User(id=data.get('id', None),
  1195. name=data.get('name', None),
  1196. screen_name=data.get('screen_name', None),
  1197. location=data.get('location', None),
  1198. description=data.get('description', None),
  1199. statuses_count=data.get('statuses_count', None),
  1200. followers_count=data.get('followers_count', None),
  1201. favourites_count=data.get('favourites_count', None),
  1202. friends_count=data.get('friends_count', None),
  1203. profile_image_url=data.get('profile_image_url_https', data.get('profile_image_url', None)),
  1204. profile_background_tile = data.get('profile_background_tile', None),
  1205. profile_background_image_url = data.get('profile_background_image_url', None),
  1206. profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None),
  1207. profile_background_color = data.get('profile_background_color', None),
  1208. profile_link_color = data.get('profile_link_color', None),
  1209. profile_text_color = data.get('profile_text_color', None),
  1210. protected = data.get('protected', None),
  1211. utc_offset = data.get('utc_offset', None),
  1212. time_zone = data.get('time_zone', None),
  1213. url=data.get('url', None),
  1214. status=status,
  1215. geo_enabled=data.get('geo_enabled', None),
  1216. verified=data.get('verified', None),
  1217. lang=data.get('lang', None),
  1218. notifications=data.get('notifications', None),
  1219. contributors_enabled=data.get('contributors_enabled', None),
  1220. created_at=data.get('created_at', None),
  1221. listed_count=data.get('listed_count', None))
  1222. class List(object):
  1223. '''A class representing the List structure used by the twitter API.
  1224. The List structure exposes the following properties:
  1225. list.id
  1226. list.name
  1227. list.slug
  1228. list.description
  1229. list.full_name
  1230. list.mode
  1231. list.uri
  1232. list.member_count
  1233. list.subscriber_count
  1234. list.following
  1235. '''
  1236. def __init__(self,
  1237. id=None,
  1238. name=None,
  1239. slug=None,
  1240. description=None,
  1241. full_name=None,
  1242. mode=None,
  1243. uri=None,
  1244. member_count=None,
  1245. subscriber_count=None,
  1246. following=None,
  1247. user=None):
  1248. self.id = id
  1249. self.name = name
  1250. self.slug = slug
  1251. self.description = description
  1252. self.full_name = full_name
  1253. self.mode = mode
  1254. self.uri = uri
  1255. self.member_count = member_count
  1256. self.subscriber_count = subscriber_count
  1257. self.following = following
  1258. self.user = user
  1259. def GetId(self):
  1260. '''Get the unique id of this list.
  1261. Returns:
  1262. The unique id of this list
  1263. '''
  1264. return self._id
  1265. def SetId(self, id):
  1266. '''Set the unique id of this list.
  1267. Args:
  1268. id:
  1269. The unique id of this list.
  1270. '''
  1271. self._id = id
  1272. id = property(GetId, SetId,
  1273. doc='The unique id of this list.')
  1274. def GetName(self):
  1275. '''Get the real name of this list.
  1276. Returns:
  1277. The real name of this list
  1278. '''
  1279. return self._name
  1280. def SetName(self, name):
  1281. '''Set the real name of this list.
  1282. Args:
  1283. name:
  1284. The real name of this list
  1285. '''
  1286. self._name = name
  1287. name = property(GetName, SetName,
  1288. doc='The real name of this list.')
  1289. def GetSlug(self):
  1290. '''Get the slug of this list.
  1291. Returns:
  1292. The slug of this list
  1293. '''
  1294. return self._slug
  1295. def SetSlug(self, slug):
  1296. '''Set the slug of this list.
  1297. Args:
  1298. slug:
  1299. The slug of this list.
  1300. '''
  1301. self._slug = slug
  1302. slug = property(GetSlug, SetSlug,
  1303. doc='The slug of this list.')
  1304. def GetDescription(self):
  1305. '''Get the description of this list.
  1306. Returns:
  1307. The description of this list
  1308. '''
  1309. return self._description
  1310. def SetDescription(self, description):
  1311. '''Set the description of this list.
  1312. Args:
  1313. description:
  1314. The description of this list.
  1315. '''
  1316. self._description = description
  1317. description = property(GetDescription, SetDescription,
  1318. doc='The description of this list.')
  1319. def GetFull_name(self):
  1320. '''Get the full_name of this list.
  1321. Returns:
  1322. The full_name of this list
  1323. '''
  1324. return self._full_name
  1325. def SetFull_name(self, full_name):
  1326. '''Set the full_name of this list.
  1327. Args:
  1328. full_name:
  1329. The full_name of this list.
  1330. '''
  1331. self._full_name = full_name
  1332. full_name = property(GetFull_name, SetFull_name,
  1333. doc='The full_name of this list.')
  1334. def GetMode(self):
  1335. '''Get the mode of this list.
  1336. Returns:
  1337. The mode of this list
  1338. '''
  1339. return self._mode
  1340. def SetMode(self, mode):
  1341. '''Set the mode of this list.
  1342. Args:
  1343. mode:
  1344. The mode of this list.
  1345. '''
  1346. self._mode = mode
  1347. mode = property(GetMode, SetMode,
  1348. doc='The mode of this list.')
  1349. def GetUri(self):
  1350. '''Get the uri of this list.
  1351. Returns:
  1352. The uri of this list
  1353. '''
  1354. return self._uri
  1355. def SetUri(self, uri):
  1356. '''Set the uri of this list.
  1357. Args:
  1358. uri:
  1359. The uri of this list.
  1360. '''
  1361. self._uri = uri
  1362. uri = property(GetUri, SetUri,
  1363. doc='The uri of this list.')
  1364. def GetMember_count(self):
  1365. '''Get the member_count of this list.
  1366. Returns:
  1367. The member_count of this list
  1368. '''
  1369. return self._member_count
  1370. def SetMember_count(self, member_count):
  1371. '''Set the member_count of this list.
  1372. Args:
  1373. member_count:
  1374. The member_count of this list.
  1375. '''
  1376. self._member_count = member_count
  1377. member_count = property(GetMember_count, SetMember_count,
  1378. doc='The member_count of this list.')
  1379. def GetSubscriber_count(self):
  1380. '''Get the subscriber_count of this list.
  1381. Returns:
  1382. The subscriber_count of this list
  1383. '''
  1384. return self._subscriber_count
  1385. def SetSubscriber_count(self, subscriber_count):
  1386. '''Set the subscriber_count of this list.
  1387. Args:
  1388. subscriber_count:
  1389. The subscriber_count of this list.
  1390. '''
  1391. self._subscriber_count = subscriber_count
  1392. subscriber_count = property(GetSubscriber_count, SetSubscriber_count,
  1393. doc='The subscriber_count of this list.')
  1394. def GetFollowing(self):
  1395. '''Get the following status of this list.
  1396. Returns:
  1397. The following status of this list
  1398. '''
  1399. return self._following
  1400. def SetFollowing(self, following):
  1401. '''Set the following status of this list.
  1402. Args:
  1403. following:
  1404. The following of this list.
  1405. '''
  1406. self._following = following
  1407. following = property(GetFollowing, SetFollowing,
  1408. doc='The following status of this list.')
  1409. def GetUser(self):
  1410. '''Get the user of this list.
  1411. Returns:
  1412. The owner of this list
  1413. '''
  1414. return self._user
  1415. def SetUser(self, user):
  1416. '''Set the user of this list.
  1417. Args:
  1418. user:
  1419. The owner of this list.
  1420. '''
  1421. self._user = user
  1422. user = property(GetUser, SetUser,
  1423. doc='The owner of this list.')
  1424. def __ne__(self, other):
  1425. return not self.__eq__(other)
  1426. def __eq__(self, other):
  1427. try:
  1428. return other and \
  1429. self.id == other.id and \
  1430. self.name == other.name and \
  1431. self.slug == other.slug and \
  1432. self.description == other.description and \
  1433. self.full_name == other.full_name and \
  1434. self.mode == other.mode and \
  1435. self.uri == other.uri and \
  1436. self.member_count == other.member_count and \
  1437. self.subscriber_count == other.subscriber_count and \
  1438. self.following == other.following and \
  1439. self.user == other.user
  1440. except AttributeError:
  1441. return False
  1442. def __str__(self):
  1443. '''A string representation of this twitter.List instance.
  1444. The return value is the same as the JSON string representation.
  1445. Returns:
  1446. A string representation of this twitter.List instance.
  1447. '''
  1448. return self.AsJsonString()
  1449. def AsJsonString(self):
  1450. '''A JSON string representation of this twitter.List instance.
  1451. Returns:
  1452. A JSON string representation of this twitter.List instance
  1453. '''
  1454. return simplejson.dumps(self.AsDict(), sort_keys=True)
  1455. def AsDict(self):
  1456. '''A dict representation of this twitter.List instance.
  1457. The return value uses the same key names as the JSON representation.
  1458. Return:
  1459. A dict representing this twitter.List instance
  1460. '''
  1461. data = {}
  1462. if self.id:
  1463. data['id'] = self.id
  1464. if self.name:
  1465. data['name'] = self.name
  1466. if self.slug:
  1467. data['slug'] = self.slug
  1468. if self.description:
  1469. data['description'] = self.description
  1470. if self.full_name:
  1471. data['full_name'] = self.full_name
  1472. if self.mode:
  1473. data['mode'] = self.mode
  1474. if self.uri:
  1475. data['uri'] = self.uri
  1476. if self.member_count is not None:
  1477. data['member_count'] = self.member_count
  1478. if self.subscriber_count is not None:
  1479. data['subscriber_count'] = self.subscriber_count
  1480. if self.following is not None:
  1481. data['following'] = self.following
  1482. if self.user is not None:
  1483. data['user'] = self.user.AsDict()
  1484. return data
  1485. @staticmethod
  1486. def NewFromJsonDict(data):
  1487. '''Create a new instance based on a JSON dict.
  1488. Args:
  1489. data:
  1490. A JSON dict, as converted from the JSON in the twitter API
  1491. Returns:
  1492. A twitter.List instance
  1493. '''
  1494. if 'user' in data:
  1495. user = User.NewFromJsonDict(data['user'])
  1496. else:
  1497. user = None
  1498. return List(id=data.get('id', None),
  1499. name=data.get('name', None),
  1500. slug=data.get('slug', None),
  1501. description=data.get('description', None),
  1502. full_name=data.get('full_name', None),
  1503. mode=data.get('mode', None),
  1504. uri=data.get('uri', None),
  1505. member_count=data.get('member_count', None),
  1506. subscriber_count=data.get('subscriber_count', None),
  1507. following=data.get('following', None),
  1508. user=user)
  1509. class DirectMessage(object):
  1510. '''A class representing the DirectMessage structure used by the twitter API.
  1511. The DirectMessage structure exposes the following properties:
  1512. direct_message.id
  1513. direct_message.created_at
  1514. direct_message.created_at_in_seconds # read only
  1515. direct_message.sender_id
  1516. direct_message.sender_screen_name
  1517. direct_message.recipient_id
  1518. direct_message.recipient_screen_name
  1519. direct_message.text
  1520. '''
  1521. def __init__(self,
  1522. id=None,
  1523. created_at=None,
  1524. sender_id=None,
  1525. sender_screen_name=None,
  1526. recipient_id=None,
  1527. recipient_screen_name=None,
  1528. text=None):
  1529. '''An object to hold a Twitter direct message.
  1530. This class is normally instantiated by the twitter.Api class and
  1531. returned in a sequence.
  1532. Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
  1533. Args:
  1534. id:
  1535. The unique id of this direct message. [Optional]
  1536. created_at:
  1537. The time this direct message was posted. [Optional]
  1538. sender_id:
  1539. The id of the twitter user that sent this message. [Optional]
  1540. sender_screen_name:
  1541. The name of the twitter user that sent this message. [Optional]
  1542. recipient_id:
  1543. The id of the twitter that received this message. [Optional]
  1544. recipient_screen_name:
  1545. The name of the twitter that received this message. [Optional]
  1546. text:
  1547. The text of this direct message. [Optional]
  1548. '''
  1549. self.id = id
  1550. self.created_at = created_at
  1551. self.sender_id = sender_id
  1552. self.sender_screen_name = sender_screen_name
  1553. self.recipient_id = recipient_id
  1554. self.recipient_screen_name = recipient_screen_name
  1555. self.text = text
  1556. def GetId(self):
  1557. '''Get the unique id of this direct message.
  1558. Returns:
  1559. The unique id of this direct message
  1560. '''
  1561. return self._id
  1562. def SetId(self, id):
  1563. '''Set the unique id of this direct message.
  1564. Args:
  1565. id:
  1566. The unique id of this direct message
  1567. '''
  1568. self._id = id
  1569. id = property(GetId, SetId,
  1570. doc='The unique id of this direct message.')
  1571. def GetCreatedAt(self):
  1572. '''Get the time this direct message was posted.
  1573. Returns:
  1574. The time this direct message was posted
  1575. '''
  1576. return self._created_at
  1577. def SetCreatedAt(self, created_at):
  1578. '''Set the time this direct message was posted.
  1579. Args:
  1580. created_at:
  1581. The time this direct message was created
  1582. '''
  1583. self._created_at = created_at
  1584. created_at = property(GetCreatedAt, SetCreatedAt,
  1585. doc='The time this direct message was posted.')
  1586. def GetCreatedAtInSeconds(self):
  1587. '''Get the time this direct message was posted, in seconds since the epoch.
  1588. Returns:
  1589. The time this direct message was posted, in seconds since the epoch.
  1590. '''
  1591. return calendar.timegm(rfc822.parsedate(self.created_at))
  1592. created_at_in_seconds = property(GetCreatedAtInSeconds,
  1593. doc="The time this direct message was "
  1594. "posted, in seconds since the epoch")
  1595. def GetSenderId(self):
  1596. '''Get the unique sender id of this direct message.
  1597. Returns:
  1598. The unique sender id of this direct message
  1599. '''
  1600. return self._sender_id
  1601. def SetSenderId(self, sender_id):
  1602. '''Set the unique sender id of this direct message.
  1603. Args:
  1604. sender_id:
  1605. The unique sender id of this direct message
  1606. '''
  1607. self._sender_id = sender_id
  1608. sender_id = property(GetSenderId, SetSenderId,
  1609. doc='The unique sender id of this direct message.')
  1610. def GetSenderScreenName(self):
  1611. '''Get the unique sender screen name of this direct message.
  1612. Returns:
  1613. The unique sender screen name of this direct message
  1614. '''
  1615. return self._sender_screen_name
  1616. def SetSenderScreenName(self, sender_screen_name):
  1617. '''Set the unique sender screen name of this direct message.
  1618. Args:
  1619. sender_screen_name:
  1620. The unique sender screen name of this direct message
  1621. '''
  1622. self._sender_screen_name = sender_screen_name
  1623. sender_screen_name = property(GetSenderScreenName, SetSenderScreenName,
  1624. doc='The unique sender screen name of this direct message.')
  1625. def GetRecipientId(self):
  1626. '''Get the unique recipient id of this direct message.
  1627. Returns:
  1628. The unique recipient id of this direct message
  1629. '''
  1630. return self._recipient_id
  1631. def SetRecipientId(self, recipient_id):
  1632. '''Set the unique recipient id of this direct message.
  1633. Args:
  1634. recipient_id:
  1635. The unique recipient id of this direct message
  1636. '''
  1637. self._recipient_id = recipient_id
  1638. recipient_id = property(GetRecipientId, SetRecipientId,
  1639. doc='The unique recipient id of this direct message.')
  1640. def GetRecipientScreenName(self):
  1641. '''Get the unique recipient screen name of this direct message.
  1642. Returns:
  1643. The unique recipient screen name of this direct message
  1644. '''
  1645. return self._recipient_screen_name
  1646. def SetRecipientScreenName(self, recipient_screen_name):
  1647. '''Set the unique recipient screen name of this direct message.
  1648. Args:
  1649. recipient_screen_name:
  1650. The unique recipient screen name of this direct message
  1651. '''
  1652. self._recipient_screen_name = recipient_screen_name
  1653. recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName,
  1654. doc='The unique recipient screen name of this direct message.')
  1655. def GetText(self):
  1656. '''Get the text of this direct message.
  1657. Returns:
  1658. The text of this direct message.
  1659. '''
  1660. return self._text
  1661. def SetText(self, text):
  1662. '''Set the text of this direct message.
  1663. Args:
  1664. text:
  1665. The text of this direct message
  1666. '''
  1667. self._text = text
  1668. text = property(GetText, SetText,
  1669. doc='The text of this direct message')
  1670. def __ne__(self, other):
  1671. return not self.__eq__(other)
  1672. def __eq__(self, other):
  1673. try:
  1674. return other and \
  1675. self.id == other.id and \
  1676. self.created_at == other.created_at and \
  1677. self.sender_id == other.sender_id and \
  1678. self.sender_screen_name == other.sender_screen_name and \
  1679. self.recipient_id == other.recipient_id and \
  1680. self.recipient_screen_name == other.recipient_screen_name and \
  1681. self.text == other.text
  1682. except AttributeError:
  1683. return False
  1684. def __str__(self):
  1685. '''A string representation of this twitter.DirectMessage instance.
  1686. The return value is the same as the JSON string representation.
  1687. Returns:
  1688. A string representation of this twitter.DirectMessage instance.
  1689. '''
  1690. return self.AsJsonString()
  1691. def AsJsonString(self):
  1692. '''A JSON string representation of this twitter.DirectMessage instance.
  1693. Returns:
  1694. A JSON string representation of this twitter.DirectMessage instance
  1695. '''
  1696. return simplejson.dumps(self.AsDict(), sort_keys=True)
  1697. def AsDict(self):
  1698. '''A dict representation of this twitter.DirectMessage instance.
  1699. The return value uses the same key names as the JSON representation.
  1700. Return:
  1701. A dict representing this twitter.DirectMessage instance
  1702. '''
  1703. data = {}
  1704. if self.id:
  1705. data['id'] = self.id
  1706. if self.created_at:
  1707. data['created_at'] = self.created_at
  1708. if self.sender_id:
  1709. data['sender_id'] = self.sender_id
  1710. if self.sender_screen_name:
  1711. data['sender_screen_name'] = self.sender_screen_name
  1712. if self.recipient_id:
  1713. data['recipient_id'] = self.recipient_id
  1714. if self.recipient_screen_name:
  1715. data['recipient_screen_name'] = self.recipient_screen_name
  1716. if self.text:
  1717. data['text'] = self.text
  1718. return data
  1719. @staticmethod
  1720. def NewFromJsonDict(data):
  1721. '''Create a new instance based on a JSON dict.
  1722. Args:
  1723. data:
  1724. A JSON dict, as converted from the JSON in the twitter API
  1725. Returns:
  1726. A twitter.DirectMessage instance
  1727. '''
  1728. return DirectMessage(created_at=data.get('created_at', None),
  1729. recipient_id=data.get('recipient_id', None),
  1730. sender_id=data.get('sender_id', None),
  1731. text=data.get('text', None),
  1732. sender_screen_name=data.get('sender_screen_name', None),
  1733. id=data.get('id', None),
  1734. recipient_screen_name=data.get('recipient_screen_name', None))
  1735. class Hashtag(object):
  1736. ''' A class representing a twitter hashtag
  1737. '''
  1738. def __init__(self,
  1739. text=None):
  1740. self.text = text
  1741. @staticmethod
  1742. def NewFromJsonDict(data):
  1743. '''Create a new instance based on a JSON dict.
  1744. Args:
  1745. data:
  1746. A JSON dict, as converted from the JSON in the twitter API
  1747. Returns:
  1748. A twitter.Hashtag instance
  1749. '''
  1750. return Hashtag(text = data.get('text', None))
  1751. class Trend(object):
  1752. ''' A class representing a trending topic
  1753. '''
  1754. def __init__(self, name=None, query=None, timestamp=None, url=None):
  1755. self.name = name
  1756. self.query = query
  1757. self.timestamp = timestamp
  1758. self.url = url
  1759. def __repr__(self):
  1760. return self.name
  1761. def __str__(self):
  1762. return 'Name: %s\nQuery: %s\nTimestamp: %s\nSearch URL: %s\n' % (self.name, self.query, self.timestamp, self.url)
  1763. def __ne__(self, other):
  1764. return not self.__eq__(other)
  1765. def __eq__(self, other):
  1766. try:
  1767. return other and \
  1768. self.name == other.name and \
  1769. self.query == other.query and \
  1770. self.timestamp == other.timestamp and \
  1771. self.url == self.url
  1772. except AttributeError:
  1773. return False
  1774. @staticmethod
  1775. def NewFromJsonDict(data, timestamp = None):
  1776. '''Create a new instance based on a JSON dict
  1777. Args:
  1778. data:
  1779. A JSON dict
  1780. timestamp:
  1781. Gets set as the timestamp property of the new object
  1782. Returns:
  1783. A twitter.Trend object
  1784. '''
  1785. return Trend(name=data.get('name', None),
  1786. query=data.get('query', None),
  1787. url=data.get('url', None),
  1788. timestamp=timestamp)
  1789. class Url(object):
  1790. '''A class representing an URL contained in a tweet'''
  1791. def __init__(self,
  1792. url=None,
  1793. expanded_url=None):
  1794. self.url = url
  1795. self.expanded_url = expanded_url
  1796. @staticmethod
  1797. def NewFromJsonDict(data):
  1798. '''Create a new instance based on a JSON dict.
  1799. Args:
  1800. data:
  1801. A JSON dict, as converted from the JSON in the twitter API
  1802. Returns:
  1803. A twitter.Url instance
  1804. '''
  1805. return Url(url=data.get('url', None),
  1806. expanded_url=data.get('expanded_url', None))
  1807. class Api(object):
  1808. '''A python interface into the Twitter API
  1809. By default, the Api caches results for 1 minute.
  1810. Example usage:
  1811. To create an instance of the twitter.Api class, with no authentication:
  1812. >>> import twitter
  1813. >>> api = twitter.Api()
  1814. To fetch a single user's public status messages, where "user" is either
  1815. a Twitter "short name" or their user id.
  1816. >>> statuses = api.GetUserTimeline(user)
  1817. >>> print [s.text for s in statuses]
  1818. To use authentication, instantiate the twitter.Api class with a
  1819. consumer key and secret; and the oAuth key and secret:
  1820. >>> api = twitter.Api(consumer_key='twitter consumer key',
  1821. consumer_secret='twitter consumer secret',
  1822. access_token_key='the_key_given',
  1823. access_token_secret='the_key_secret')
  1824. To fetch your friends (after being authenticated):
  1825. >>> users = api.GetFriends()
  1826. >>> print [u.name for u in users]
  1827. To post a twitter status message (after being authenticated):
  1828. >>> status = api.PostUpdate('I love python-twitter!')
  1829. >>> print status.text
  1830. I love python-twitter!
  1831. There are many other methods, including:
  1832. >>> api.PostUpdates(status)
  1833. >>> api.PostDirectMessage(user, text)
  1834. >>> api.GetUser(user)
  1835. >>> api.GetReplies()
  1836. >>> api.GetUserTimeline(user)
  1837. >>> api.GetHomeTimeLine()
  1838. >>> api.GetStatus(id)
  1839. >>> api.DestroyStatus(id)
  1840. >>> api.GetFriends(user)
  1841. >>> api.GetFollowers()
  1842. >>> api.GetFeatured()
  1843. >>> api.GetDirectMessages()
  1844. >>> api.GetSentDirectMessages()
  1845. >>> api.PostDirectMessage(user, text)
  1846. >>> api.DestroyDirectMessage(id)
  1847. >>> api.DestroyFriendship(user)
  1848. >>> api.CreateFriendship(user)
  1849. >>> api.GetUserByEmail(email)
  1850. >>> api.VerifyCredentials()
  1851. '''
  1852. DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute
  1853. _API_REALM = 'Twitter API'
  1854. def __init__(self,
  1855. consumer_key=None,
  1856. consumer_secret=None,
  1857. access_token_key=None,
  1858. access_token_secret=None,
  1859. input_encoding=None,
  1860. request_headers=None,
  1861. cache=DEFAULT_CACHE,
  1862. shortner=None,
  1863. base_url=None,
  1864. use_gzip_compression=False,
  1865. debugHTTP=False,
  1866. proxy=None):
  1867. '''Instantiate a new twitter.Api object.
  1868. Args:
  1869. consumer_key:
  1870. Your Twitter user's consumer_key.
  1871. consumer_secret:
  1872. Your Twitter user's consumer_secret.
  1873. access_token_key:
  1874. The oAuth access token key value you retrieved
  1875. from running get_access_token.py.
  1876. access_token_secret:
  1877. The oAuth access token's secret, also retrieved
  1878. from the get_access_token.py run.
  1879. input_encoding:
  1880. The encoding used to encode input strings. [Optional]
  1881. request_header:
  1882. A dictionary of additional HTTP request headers. [Optional]
  1883. cache:
  1884. The cache instance to use. Defaults to DEFAULT_CACHE.
  1885. Use None to disable caching. [Optional]
  1886. shortner:
  1887. The shortner instance to use. Defaults to None.
  1888. See shorten_url.py for an example shortner. [Optional]
  1889. base_url:
  1890. The base URL to use to contact the Twitter API.
  1891. Defaults to https://api.twitter.com. [Optional]
  1892. use_gzip_compression:
  1893. Set to True to tell enable gzip compression for any call
  1894. made to Twitter. Defaults to False. [Optional]
  1895. debugHTTP:
  1896. Set to True to enable debug output from urllib2 when performing
  1897. any HTTP requests. Defaults to False. [Optional]
  1898. '''
  1899. self.SetCache(cache)
  1900. self.http_proxy = None
  1901. if proxy is not None:
  1902. self.http_proxy = proxy
  1903. self._urllib = urllib2
  1904. self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
  1905. self._input_encoding = input_encoding
  1906. self._use_gzip = use_gzip_compression
  1907. self._debugHTTP = debugHTTP
  1908. self._oauth_consumer = None
  1909. self._shortlink_size = 19
  1910. self._InitializeRequestHeaders(request_headers)
  1911. self._InitializeUserAgent()
  1912. self._InitializeDefaultParameters()
  1913. from config import APIsources
  1914. for source in APIsources:
  1915. self.source_api = source['source_api']
  1916. if base_url is None:
  1917. if self.source_api == "api.twitter.com":
  1918. self.base_url = 'https://'+self.source_api+'/1.1'
  1919. else:
  1920. self.base_url = 'https://'+self.source_api
  1921. else:
  1922. self.base_url = base_url
  1923. if consumer_key is not None and (access_token_key is None or
  1924. access_token_secret is None):
  1925. print >> sys.stderr, 'Twitter now requires an oAuth Access Token for API calls.'
  1926. print >> sys.stderr, 'If your using this library from a command line utility, please'
  1927. print >> sys.stderr, 'run the included get_access_token.py tool to generate one.'
  1928. raise TwitterError('Twitter requires oAuth Access Token for all API access')
  1929. self.SetCredentials(consumer_key, consumer_secret, access_token_key, access_token_secret)
  1930. def SetCredentials(self,
  1931. consumer_key,
  1932. consumer_secret,
  1933. access_token_key=None,
  1934. access_token_secret=None):
  1935. '''Set the consumer_key and consumer_secret for this instance
  1936. Args:
  1937. consumer_key:
  1938. The consumer_key of the twitter account.
  1939. consumer_secret:
  1940. The consumer_secret for the twitter account.
  1941. access_token_key:
  1942. The oAuth access token key value you retrieved
  1943. from running get_access_token.py.
  1944. access_token_secret:
  1945. The oAuth access token's secret, also retrieved
  1946. from the get_access_token.py run.
  1947. '''
  1948. self._consumer_key = consumer_key
  1949. self._consumer_secret = consumer_secret
  1950. self._access_token_key = access_token_key
  1951. self._access_token_secret = access_token_secret
  1952. self._oauth_consumer = None
  1953. if consumer_key is not None and consumer_secret is not None and \
  1954. access_token_key is not None and access_token_secret is not None:
  1955. self._signature_method_plaintext = oauth.SignatureMethod_PLAINTEXT()
  1956. self._signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
  1957. self._oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
  1958. self._oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
  1959. self._config = self.GetHelpConfiguration()
  1960. def GetHelpConfiguration(self):
  1961. if self.source_api == "api.twitter.com":
  1962. url = '%s/help/configuration.json' % self.base_url
  1963. else:
  1964. url = '%s/statusnet/config.json' % self.base_url
  1965. json = self._FetchUrl(url)
  1966. data = self._ParseAndCheckTwitter(json)
  1967. return data
  1968. def GetShortUrlLength(self, https=False):
  1969. if https:
  1970. return self._config['short_url_length_https']
  1971. else:
  1972. return self._config['short_url_length']
  1973. def ClearCredentials(self):
  1974. '''Clear the any credentials for this instance
  1975. '''
  1976. self._consumer_key = None
  1977. self._consumer_secret = None
  1978. self._access_token_key = None
  1979. self._access_token_secret = None
  1980. self._oauth_consumer = None
  1981. def GetSearch(self,
  1982. term=None,
  1983. geocode=None,
  1984. since_id=None,
  1985. max_id=None,
  1986. until=None,
  1987. count=15,
  1988. lang=None,
  1989. locale=None,
  1990. result_type="mixed",
  1991. include_entities=None):
  1992. '''Return twitter search results for a given term.
  1993. Args:
  1994. term:
  1995. Term to search by. Optional if you include geocode.
  1996. since_id:
  1997. Returns results with an ID greater than (that is, more recent
  1998. than) the specified ID. There are limits to the number of
  1999. Tweets which can be accessed through the API. If the limit of
  2000. Tweets has occurred since the since_id, the since_id will be
  2001. forced to the oldest ID available. [Optional]
  2002. max_id:
  2003. Returns only statuses with an ID less than (that is, older
  2004. than) or equal to the specified ID. [Optional]
  2005. until:
  2006. Returns tweets generated before the given date. Date should be
  2007. formatted as YYYY-MM-DD. [Optional]
  2008. geocode:
  2009. Geolocation information in the form (latitude, longitude, radius)
  2010. [Optional]
  2011. count:
  2012. Number of results to return. Default is 15 [Optional]
  2013. lang:
  2014. Language for results as ISO 639-1 code. Default is None (all languages)
  2015. [Optional]
  2016. locale:
  2017. Language of the search query. Currently only 'ja' is effective. This is
  2018. intended for language-specific consumers and the default should work in
  2019. the majority of cases.
  2020. result_type:
  2021. Type of result which should be returned. Default is "mixed". Other
  2022. valid options are "recent" and "popular". [Optional]
  2023. include_entities:
  2024. If True, each tweet will include a node called "entities,".
  2025. This node offers a variety of metadata about the tweet in a
  2026. discrete structure, including: user_mentions, urls, and
  2027. hashtags. [Optional]
  2028. Returns:
  2029. A sequence of twitter.Status instances, one for each message containing
  2030. the term
  2031. '''
  2032. # Build request parameters
  2033. parameters = {}
  2034. if since_id:
  2035. try:
  2036. parameters['since_id'] = long(since_id)
  2037. except ValueError:
  2038. raise TwitterError("since_id must be an integer")
  2039. if max_id:
  2040. try:
  2041. parameters['max_id'] = long(max_id)
  2042. except ValueError:
  2043. raise TwitterError("max_id must be an integer")
  2044. if until:
  2045. parameters['until'] = until
  2046. if lang:
  2047. parameters['lang'] = lang
  2048. if locale:
  2049. parameters['locale'] = locale
  2050. if term is None and geocode is None:
  2051. return []
  2052. if term is not None:
  2053. parameters['q'] = term
  2054. if geocode is not None:
  2055. parameters['geocode'] = ','.join(map(str, geocode))
  2056. if include_entities:
  2057. parameters['include_entities'] = 1
  2058. try:
  2059. parameters['count'] = int(count)
  2060. except ValueError:
  2061. raise TwitterError("count must be an integer")
  2062. if result_type in ["mixed", "popular", "recent"]:
  2063. parameters['result_type'] = result_type
  2064. # Make and send requests
  2065. if self.source_api == "api.twitter.com":
  2066. url = "%s/search/tweets.json" % self.base_url
  2067. else:
  2068. url = '%s/search.json' % self.base_url
  2069. json = self._FetchUrl(url, parameters=parameters)
  2070. data = self._ParseAndCheckTwitter(json)
  2071. if self.source_api == "api.twitter.com":
  2072. return [Status.NewFromJsonDict(x) for x in data["statuses"]]
  2073. else:
  2074. return [Status.NewFromJsonDict(x) for x in data]
  2075. def GetUsersSearch(self,
  2076. term=None,
  2077. page=1,
  2078. count=20,
  2079. include_entities=None):
  2080. '''Return twitter user search results for a given term.
  2081. Args:
  2082. term:
  2083. Term to search by.
  2084. page:
  2085. Page of results to return. Default is 1
  2086. [Optional]
  2087. count:
  2088. Number of results to return. Default is 20
  2089. [Optional]
  2090. include_entities:
  2091. If True, each tweet will include a node called "entities,".
  2092. This node offers a variety of metadata about the tweet in a
  2093. discrete structure, including: user_mentions, urls, and hashtags.
  2094. [Optional]
  2095. Returns:
  2096. A sequence of twitter.User instances, one for each message containing
  2097. the term
  2098. '''
  2099. # Build request parameters
  2100. parameters = {}
  2101. if term is not None:
  2102. parameters['q'] = term
  2103. if include_entities:
  2104. parameters['include_entities'] = 1
  2105. try:
  2106. parameters['count'] = int(count)
  2107. except ValueError:
  2108. raise TwitterError("count must be an integer")
  2109. # Make and send requests
  2110. url = '%s/users/search.json' % self.base_url
  2111. json = self._FetchUrl(url, parameters=parameters)
  2112. data = self._ParseAndCheckTwitter(json)
  2113. return [User.NewFromJsonDict(x) for x in data]
  2114. def GetTrendsCurrent(self, exclude=None):
  2115. '''Get the current top trending topics (global)
  2116. Args:
  2117. exclude:
  2118. Appends the exclude parameter as a request parameter.
  2119. Currently only exclude=hashtags is supported. [Optional]
  2120. Returns:
  2121. A list with 10 entries. Each entry contains a trend.
  2122. '''
  2123. return self.GetTrendsWoeid(id=1, exclude=exclude)
  2124. def GetTrendsWoeid(self, id, exclude=None):
  2125. '''Return the top 10 trending topics for a specific WOEID, if trending
  2126. information is available for it.
  2127. Args:
  2128. woeid:
  2129. the Yahoo! Where On Earth ID for a location.
  2130. exclude:
  2131. Appends the exclude parameter as a request parameter.
  2132. Currently only exclude=hashtags is supported. [Optional]
  2133. Returns:
  2134. A list with 10 entries. Each entry contains a trend.
  2135. '''
  2136. url = '%s/trends/place.json' % (self.base_url)
  2137. parameters = {'id': id}
  2138. if exclude:
  2139. parameters['exclude'] = exclude
  2140. json = self._FetchUrl(url, parameters=parameters)
  2141. data = self._ParseAndCheckTwitter(json)
  2142. trends = []
  2143. timestamp = data[0]['as_of']
  2144. for trend in data[0]['trends']:
  2145. trends.append(Trend.NewFromJsonDict(trend, timestamp = timestamp))
  2146. return trends
  2147. def GetHomeTimeline(self,
  2148. count=None,
  2149. since_id=None,
  2150. max_id=None,
  2151. trim_user=False,
  2152. exclude_replies=False,
  2153. contributor_details=False,
  2154. include_entities=True):
  2155. '''
  2156. Fetch a collection of the most recent Tweets and retweets posted by the
  2157. authenticating user and the users they follow.
  2158. The home timeline is central to how most users interact with the Twitter
  2159. service.
  2160. The twitter.Api instance must be authenticated.
  2161. Args:
  2162. count:
  2163. Specifies the number of statuses to retrieve. May not be
  2164. greater than 200. Defaults to 20. [Optional]
  2165. since_id:
  2166. Returns results with an ID greater than (that is, more recent
  2167. than) the specified ID. There are limits to the number of
  2168. Tweets which can be accessed through the API. If the limit of
  2169. Tweets has occurred since the since_id, the since_id will be
  2170. forced to the oldest ID available. [Optional]
  2171. max_id:
  2172. Returns results with an ID less than (that is, older than) or
  2173. equal to the specified ID. [Optional]
  2174. trim_user:
  2175. When True, each tweet returned in a timeline will include a user
  2176. object including only the status authors numerical ID. Omit this
  2177. parameter to receive the complete user object. [Optional]
  2178. exclude_replies:
  2179. This parameter will prevent replies from appearing in the
  2180. returned timeline. Using exclude_replies with the count
  2181. parameter will mean you will receive up-to count tweets -
  2182. this is because the count parameter retrieves that many
  2183. tweets before filtering out retweets and replies.
  2184. [Optional]
  2185. contributor_details:
  2186. This parameter enhances the contributors element of the
  2187. status response to include the screen_name of the contributor.
  2188. By default only the user_id of the contributor is included.
  2189. [Optional]
  2190. include_entities:
  2191. The entities node will be disincluded when set to false.
  2192. This node offers a variety of metadata about the tweet in a
  2193. discreet structure, including: user_mentions, urls, and
  2194. hashtags. [Optional]
  2195. Returns:
  2196. A sequence of twitter.Status instances, one for each message
  2197. '''
  2198. if self.source_api == "api.twitter.com":
  2199. url = '%s/statuses/home_timeline.json' % self.base_url
  2200. else:
  2201. url = '%s/statuses/public_timeline.json' % self.base_url
  2202. if not self._oauth_consumer:
  2203. raise TwitterError("API must be authenticated.")
  2204. parameters = {}
  2205. if count is not None:
  2206. try:
  2207. if int(count) > 200:
  2208. raise TwitterError("'count' may not be greater than 200")
  2209. except ValueError:
  2210. raise TwitterError("'count' must be an integer")
  2211. parameters['count'] = count
  2212. if since_id:
  2213. try:
  2214. parameters['since_id'] = long(since_id)
  2215. except ValueError:
  2216. raise TwitterError("'since_id' must be an integer")
  2217. if max_id:
  2218. try:
  2219. parameters['max_id'] = long(max_id)
  2220. except ValueError:
  2221. raise TwitterError("'max_id' must be an integer")
  2222. if trim_user:
  2223. parameters['trim_user'] = 1
  2224. if exclude_replies:
  2225. parameters['exclude_replies'] = 1
  2226. if contributor_details:
  2227. parameters['contributor_details'] = 1
  2228. if not include_entities:
  2229. parameters['include_entities'] = 'false'
  2230. json = self._FetchUrl(url, parameters=parameters)
  2231. data = self._ParseAndCheckTwitter(json)
  2232. return [Status.NewFromJsonDict(x) for x in data]
  2233. def GetUserTimeline(self,
  2234. user_id=None,
  2235. screen_name=None,
  2236. since_id=None,
  2237. max_id=None,
  2238. count=None,
  2239. include_rts=True,
  2240. trim_user=None,
  2241. exclude_replies=None):
  2242. '''Fetch the sequence of public Status messages for a single user.
  2243. The twitter.Api instance must be authenticated if the user is prprintivate.
  2244. Args:
  2245. user_id:
  2246. Specifies the ID of the user for whom to return the
  2247. user_timeline. Helpful for disambiguating when a valid user ID
  2248. is also a valid screen name. [Optional]
  2249. screen_name:
  2250. Specifies the screen name of the user for whom to return the
  2251. user_timeline. Helpful for disambiguating when a valid screen
  2252. name is also a user ID. [Optional]
  2253. since_id:
  2254. Returns results with an ID greater than (that is, more recent
  2255. than) the specified ID. There are limits to the number of
  2256. Tweets which can be accessed through the API. If the limit of
  2257. Tweets has occurred since the since_id, the since_id will be
  2258. forced to the oldest ID available. [Optional]
  2259. max_id:
  2260. Returns only statuses with an ID less than (that is, older
  2261. than) or equal to the specified ID. [Optional]
  2262. count:
  2263. Specifies the number of statuses to retrieve. May not be
  2264. greater than 200. [Optional]
  2265. include_rts:
  2266. If True, the timeline will contain native retweets (if they
  2267. exist) in addition to the standard stream of tweets. [Optional]
  2268. trim_user:
  2269. If True, statuses will only contain the numerical user ID only.
  2270. Otherwise a full user object will be returned for each status.
  2271. [Optional]
  2272. exclude_replies:
  2273. If True, this will prevent replies from appearing in the returned
  2274. timeline. Using exclude_replies with the count parameter will mean you
  2275. will receive up-to count tweets - this is because the count parameter
  2276. retrieves that many tweets before filtering out retweets and replies.
  2277. This parameter is only supported for JSON and XML responses. [Optional]
  2278. Returns:
  2279. A sequence of Status instances, one for each message up to count
  2280. '''
  2281. parameters = {}
  2282. url ='%s/statuses/user_timeline.json' % (self.base_url)
  2283. if user_id:
  2284. parameters['user_id'] = user_id
  2285. elif screen_name:
  2286. parameters['screen_name'] = screen_name
  2287. if since_id:
  2288. try:
  2289. parameters['since_id'] = long(since_id)
  2290. except ValueError:
  2291. raise TwitterError("since_id must be an integer")
  2292. if max_id:
  2293. try:
  2294. parameters['max_id'] = long(max_id)
  2295. except ValueError:
  2296. raise TwitterError("max_id must be an integer")
  2297. if count:
  2298. try:
  2299. parameters['count'] = int(count)
  2300. except ValueError:
  2301. raise TwitterError("count must be an integer")
  2302. if not include_rts:
  2303. parameters['include_rts'] = 0
  2304. if trim_user:
  2305. parameters['trim_user'] = 1
  2306. if exclude_replies:
  2307. parameters['exclude_replies'] = 1
  2308. json = self._FetchUrl(url, parameters=parameters)
  2309. data = self._ParseAndCheckTwitter(json)
  2310. return [Status.NewFromJsonDict(x) for x in data]
  2311. def GetStatus(self,
  2312. id,
  2313. trim_user=False,
  2314. include_my_retweet=True,
  2315. include_entities=True):
  2316. '''Returns a single status message, specified by the id parameter.
  2317. The twitter.Api instance must be authenticated.
  2318. Args:
  2319. id:
  2320. The numeric ID of the status you are trying to retrieve.
  2321. trim_user:
  2322. When set to True, each tweet returned in a timeline will include
  2323. a user object including only the status authors numerical ID.
  2324. Omit this parameter to receive the complete user object.
  2325. [Optional]
  2326. include_my_retweet:
  2327. When set to True, any Tweets returned that have been retweeted by
  2328. the authenticating user will include an additional
  2329. current_user_retweet node, containing the ID of the source status
  2330. for the retweet. [Optional]
  2331. include_entities:
  2332. If False, the entities node will be disincluded.
  2333. This node offers a variety of metadata about the tweet in a
  2334. discreet structure, including: user_mentions, urls, and
  2335. hashtags. [Optional]
  2336. Returns:
  2337. A twitter.Status instance representing that status message
  2338. '''
  2339. url = '%s/statuses/show.json' % (self.base_url)
  2340. if not self._oauth_consumer:
  2341. raise TwitterError("API must be authenticated.")
  2342. parameters = {}
  2343. try:
  2344. parameters['id'] = long(id)
  2345. except ValueError:
  2346. raise TwitterError("'id' must be an integer.")
  2347. if trim_user:
  2348. parameters['trim_user'] = 1
  2349. if include_my_retweet:
  2350. parameters['include_my_retweet'] = 1
  2351. if not include_entities:
  2352. parameters['include_entities'] = 'none'
  2353. json = self._FetchUrl(url, parameters=parameters)
  2354. data = self._ParseAndCheckTwitter(json)
  2355. return Status.NewFromJsonDict(data)
  2356. def GetStatusOembed(self,
  2357. id=None,
  2358. url=None,
  2359. maxwidth=None,
  2360. hide_media=False,
  2361. hide_thread=False,
  2362. omit_script=False,
  2363. align=None,
  2364. related=None,
  2365. lang=None):
  2366. '''Returns information allowing the creation of an embedded representation of a
  2367. Tweet on third party sites.
  2368. Specify tweet by the id or url parameter.
  2369. The twitter.Api instance must be authenticated.
  2370. Args:
  2371. id:
  2372. The numeric ID of the status you are trying to embed.
  2373. url:
  2374. The url of the status you are trying to embed.
  2375. maxwidth:
  2376. The maximum width in pixels that the embed should be rendered at.
  2377. This value is constrained to be between 250 and 550 pixels. [Optional]
  2378. hide_media:
  2379. Specifies whether the embedded Tweet should automatically expand images. [Optional]
  2380. hide_thread:
  2381. Specifies whether the embedded Tweet should automatically show the original
  2382. message in the case that the embedded Tweet is a reply. [Optional]
  2383. omit_script:
  2384. Specifies whether the embedded Tweet HTML should include a <script>
  2385. element pointing to widgets.js. [Optional]
  2386. align:
  2387. Specifies whether the embedded Tweet should be left aligned, right aligned,
  2388. or centered in the page. [Optional]
  2389. related:
  2390. A comma sperated string of related screen names. [Optional]
  2391. lang:
  2392. Language code for the rendered embed. [Optional]
  2393. Returns:
  2394. A dictionary with the response.
  2395. '''
  2396. request_url = '%s/statuses/oembed.json' % (self.base_url)
  2397. if not self._oauth_consumer:
  2398. raise TwitterError("API must be authenticated.")
  2399. parameters = {}
  2400. if id is not None:
  2401. try:
  2402. parameters['id'] = long(id)
  2403. except ValueError:
  2404. raise TwitterError("'id' must be an integer.")
  2405. elif url is not None:
  2406. parameters['url'] = url
  2407. else:
  2408. raise TwitterError("Must specify either 'id' or 'url'")
  2409. if maxwidth is not None:
  2410. parameters['maxwidth'] = maxwidth
  2411. if hide_media == True:
  2412. parameters['hide_media'] = 'true'
  2413. if hide_thread == True:
  2414. parameters['hide_thread'] = 'true'
  2415. if omit_script == True:
  2416. parameters['omit_script'] = 'true'
  2417. if align is not None:
  2418. if align not in ('left', 'center', 'right', 'none'):
  2419. raise TwitterError("'align' must be 'left', 'center', 'right', or 'none'")
  2420. parameters['align'] = align
  2421. if related:
  2422. if not isinstance(related, str):
  2423. raise TwitterError("'related' should be a string of comma separated screen names")
  2424. parameters['related'] = related
  2425. if lang is not None:
  2426. if not isinstance(lang, str):
  2427. raise TwitterError("'lang' should be string instance")
  2428. parameters['lang'] = lang
  2429. json = self._FetchUrl(request_url, parameters=parameters)
  2430. data = self._ParseAndCheckTwitter(json)
  2431. return data
  2432. def DestroyStatus(self, id, trim_user=False):
  2433. '''Destroys the status specified by the required ID parameter.
  2434. The twitter.Api instance must be authenticated and the
  2435. authenticating user must be the author of the specified status.
  2436. Args:
  2437. id:
  2438. The numerical ID of the status you're trying to destroy.
  2439. Returns:
  2440. A twitter.Status instance representing the destroyed status message
  2441. '''
  2442. if not self._oauth_consumer:
  2443. raise TwitterError("API must be authenticated.")
  2444. try:
  2445. post_data = {'id': long(id)}
  2446. except ValueError:
  2447. raise TwitterError("id must be an integer")
  2448. url = '%s/statuses/destroy/%s.json' % (self.base_url, id)
  2449. if trim_user:
  2450. post_data['trim_user'] = 1
  2451. json = self._FetchUrl(url, post_data=post_data)
  2452. data = self._ParseAndCheckTwitter(json)
  2453. return Status.NewFromJsonDict(data)
  2454. @classmethod
  2455. def _calculate_status_length(cls, status, linksize=19):
  2456. dummy_link_replacement = 'https://-%d-chars%s/' % (linksize, '-'*(linksize - 18))
  2457. shortened = ' '.join([x if not (x.startswith('http://') or
  2458. x.startswith('https://'))
  2459. else
  2460. dummy_link_replacement
  2461. for x in status.split(' ')])
  2462. return len(shortened)
  2463. def PostUpdate(self, status, in_reply_to_status_id=None, latitude=None, longitude=None, place_id=None, display_coordinates=False, trim_user=False):
  2464. '''Post a twitter status message from the authenticated user.
  2465. The twitter.Api instance must be authenticated.
  2466. https://dev.twitter.com/docs/api/1.1/post/statuses/update
  2467. Args:
  2468. status:
  2469. The message text to be posted.
  2470. Must be less than or equal to 140 characters.
  2471. in_reply_to_status_id:
  2472. The ID of an existing status that the status to be posted is
  2473. in reply to. This implicitly sets the in_reply_to_user_id
  2474. attribute of the resulting status to the user ID of the
  2475. message being replied to. Invalid/missing status IDs will be
  2476. ignored. [Optional]
  2477. latitude:
  2478. Latitude coordinate of the tweet in degrees. Will only work
  2479. in conjunction with longitude argument. Both longitude and
  2480. latitude will be ignored by twitter if the user has a false
  2481. geo_enabled setting. [Optional]
  2482. longitude:
  2483. Longitude coordinate of the tweet in degrees. Will only work
  2484. in conjunction with latitude argument. Both longitude and
  2485. latitude will be ignored by twitter if the user has a false
  2486. geo_enabled setting. [Optional]
  2487. place_id:
  2488. A place in the world. These IDs can be retrieved from
  2489. GET geo/reverse_geocode. [Optional]
  2490. display_coordinates:
  2491. Whether or not to put a pin on the exact coordinates a tweet
  2492. has been sent from. [Optional]
  2493. trim_user:
  2494. If True the returned payload will only contain the user IDs,
  2495. otherwise the payload will contain the full user data item.
  2496. [Optional]
  2497. Returns:
  2498. A twitter.Status instance representing the message posted.
  2499. '''
  2500. if not self._oauth_consumer:
  2501. raise TwitterError("The twitter.Api instance must be authenticated.")
  2502. url = '%s/statuses/update.json' % self.base_url
  2503. if isinstance(status, unicode) or self._input_encoding is None:
  2504. u_status = status
  2505. else:
  2506. u_status = unicode(status, self._input_encoding)
  2507. #if self._calculate_status_length(u_status, self._shortlink_size) > CHARACTER_LIMIT:
  2508. # raise TwitterError("Text must be less than or equal to %d characters. "
  2509. # "Consider using PostUpdates." % CHARACTER_LIMIT)
  2510. data = {'status': status}
  2511. if in_reply_to_status_id:
  2512. data['in_reply_to_status_id'] = in_reply_to_status_id
  2513. if latitude is not None and longitude is not None:
  2514. data['lat'] = str(latitude)
  2515. data['long'] = str(longitude)
  2516. if place_id is not None:
  2517. data['place_id'] = str(place_id)
  2518. if display_coordinates:
  2519. data['display_coordinates'] = 'true'
  2520. if trim_user:
  2521. data['trim_user'] = 'true'
  2522. json = self._FetchUrl(url, post_data=data)
  2523. data = self._ParseAndCheckTwitter(json)
  2524. return Status.NewFromJsonDict(data)
  2525. def PostUpdates(self, status, continuation=None, **kwargs):
  2526. '''Post one or more twitter status messages from the authenticated user.
  2527. Unlike api.PostUpdate, this method will post multiple status updates
  2528. if the message is longer than 140 characters.
  2529. The twitter.Api instance must be authenticated.
  2530. Args:
  2531. status:
  2532. The message text to be posted.
  2533. May be longer than 140 characters.
  2534. continuation:
  2535. The character string, if any, to be appended to all but the
  2536. last message. Note that Twitter strips trailing '...' strings
  2537. from messages. Consider using the unicode \u2026 character
  2538. (horizontal ellipsis) instead. [Defaults to None]
  2539. **kwargs:
  2540. See api.PostUpdate for a list of accepted parameters.
  2541. Returns:
  2542. A of list twitter.Status instance representing the messages posted.
  2543. '''
  2544. results = list()
  2545. if continuation is None:
  2546. continuation = ''
  2547. line_length = CHARACTER_LIMIT - len(continuation)
  2548. lines = textwrap.wrap(status, line_length)
  2549. for line in lines[0:-1]:
  2550. results.append(self.PostUpdate(line + continuation, **kwargs))
  2551. results.append(self.PostUpdate(lines[-1], **kwargs))
  2552. return results
  2553. def PostRetweet(self, original_id, trim_user=False):
  2554. '''Retweet a tweet with the Retweet API.
  2555. The twitter.Api instance must be authenticated.
  2556. Args:
  2557. original_id:
  2558. The numerical id of the tweet that will be retweeted
  2559. trim_user:
  2560. If True the returned payload will only contain the user IDs,
  2561. otherwise the payload will contain the full user data item.
  2562. [Optional]
  2563. Returns:
  2564. A twitter.Status instance representing the original tweet with retweet details embedded.
  2565. '''
  2566. if not self._oauth_consumer:
  2567. raise TwitterError("The twitter.Api instance must be authenticated.")
  2568. try:
  2569. if int(original_id) <= 0:
  2570. raise TwitterError("'original_id' must be a positive number")
  2571. except ValueError:
  2572. raise TwitterError("'original_id' must be an integer")
  2573. url = '%s/statuses/retweet/%s.json' % (self.base_url, original_id)
  2574. data = {'id': original_id}
  2575. if trim_user:
  2576. data['trim_user'] = 'true'
  2577. json = self._FetchUrl(url, post_data=data)
  2578. data = self._ParseAndCheckTwitter(json)
  2579. return Status.NewFromJsonDict(data)
  2580. def GetUserRetweets(self, count=None, since_id=None, max_id=None, trim_user=False):
  2581. '''Fetch the sequence of retweets made by the authenticated user.
  2582. The twitter.Api instance must be authenticated.
  2583. Args:
  2584. count:
  2585. The number of status messages to retrieve. [Optional]
  2586. since_id:
  2587. Returns results with an ID greater than (that is, more recent
  2588. than) the specified ID. There are limits to the number of
  2589. Tweets which can be accessed through the API. If the limit of
  2590. Tweets has occurred since the since_id, the since_id will be
  2591. forced to the oldest ID available. [Optional]
  2592. max_id:
  2593. Returns results with an ID less than (that is, older than) or
  2594. equal to the specified ID. [Optional]
  2595. trim_user:
  2596. If True the returned payload will only contain the user IDs,
  2597. otherwise the payload will contain the full user data item.
  2598. [Optional]
  2599. Returns:
  2600. A sequence of twitter.Status instances, one for each message up to count
  2601. '''
  2602. return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user, exclude_replies=True, include_rts=True)
  2603. def GetReplies(self, since_id=None, count=None, max_id=None, trim_user=False):
  2604. '''Get a sequence of status messages representing the 20 most
  2605. recent replies (status updates prefixed with @twitterID) to the
  2606. authenticating user.
  2607. Args:
  2608. since_id:
  2609. Returns results with an ID greater than (that is, more recent
  2610. than) the specified ID. There are limits to the number of
  2611. Tweets which can be accessed through the API. If the limit of
  2612. Tweets has occurred since the since_id, the since_id will be
  2613. forced to the oldest ID available. [Optional]
  2614. max_id:
  2615. Returns results with an ID less than (that is, older than) or
  2616. equal to the specified ID. [Optional]
  2617. trim_user:
  2618. If True the returned payload will only contain the user IDs,
  2619. otherwise the payload will contain the full user data item.
  2620. [Optional]
  2621. Returns:
  2622. A sequence of twitter.Status instances, one for each reply to the user.
  2623. '''
  2624. return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user, exclude_replies=False, include_rts=False)
  2625. def GetRetweets(self, statusid, count=None, trim_user=False):
  2626. '''Returns up to 100 of the first retweets of the tweet identified
  2627. by statusid
  2628. Args:
  2629. statusid:
  2630. The ID of the tweet for which retweets should be searched for
  2631. count:
  2632. The number of status messages to retrieve. [Optional]
  2633. trim_user:
  2634. If True the returned payload will only contain the user IDs,
  2635. otherwise the payload will contain the full user data item.
  2636. [Optional]
  2637. Returns:
  2638. A list of twitter.Status instances, which are retweets of statusid
  2639. '''
  2640. if not self._oauth_consumer:
  2641. raise TwitterError("The twitter.Api instsance must be authenticated.")
  2642. url = '%s/statuses/retweets/%s.json' % (self.base_url, statusid)
  2643. parameters = {}
  2644. if trim_user:
  2645. parameters['trim_user'] = 'true'
  2646. if count:
  2647. try:
  2648. parameters['count'] = int(count)
  2649. except ValueError:
  2650. raise TwitterError("count must be an integer")
  2651. json = self._FetchUrl(url, parameters=parameters)
  2652. data = self._ParseAndCheckTwitter(json)
  2653. return [Status.NewFromJsonDict(s) for s in data]
  2654. def GetRetweetsOfMe(self,
  2655. count=None,
  2656. since_id=None,
  2657. max_id=None,
  2658. trim_user=False,
  2659. include_entities=True,
  2660. include_user_entities=True):
  2661. '''Returns up to 100 of the most recent tweets of the user that have been
  2662. retweeted by others.
  2663. Args:
  2664. count:
  2665. The number of retweets to retrieve, up to 100. If omitted, 20 is
  2666. assumed.
  2667. since_id:
  2668. Returns results with an ID greater than (newer than) this ID.
  2669. max_id:
  2670. Returns results with an ID less than or equal to this ID.
  2671. trim_user:
  2672. When True, the user object for each tweet will only be an ID.
  2673. include_entities:
  2674. When True, the tweet entities will be included.
  2675. include_user_entities:
  2676. When True, the user entities will be included.
  2677. '''
  2678. if not self._oauth_consumer:
  2679. raise TwitterError("The twitter.Api instance must be authenticated.")
  2680. url = '%s/statuses/retweets_of_me.json' % self.base_url
  2681. parameters = {}
  2682. if count is not None:
  2683. try:
  2684. if int(count) > 100:
  2685. raise TwitterError("'count' may not be greater than 100")
  2686. except ValueError:
  2687. raise TwitterError("'count' must be an integer")
  2688. if count:
  2689. parameters['count'] = count
  2690. if since_id:
  2691. parameters['since_id'] = since_id
  2692. if max_id:
  2693. parameters['max_id'] = max_id
  2694. if trim_user:
  2695. parameters['trim_user'] = trim_user
  2696. if not include_entities:
  2697. parameters['include_entities'] = include_entities
  2698. if not include_user_entities:
  2699. parameters['include_user_entities'] = include_user_entities
  2700. json = self._FetchUrl(url, parameters=parameters)
  2701. data = self._ParseAndCheckTwitter(json)
  2702. return [Status.NewFromJsonDict(s) for s in data]
  2703. def GetBlocks(self, user_id=None, screen_name=None, cursor=-1, skip_status=False, include_user_entities=False):
  2704. '''Fetch the sequence of twitter.User instances, one for each blocked user.
  2705. The twitter.Api instance must be authenticated.
  2706. Args:
  2707. user_id:
  2708. The twitter id of the user whose friends you are fetching.
  2709. If not specified, defaults to the authenticated user. [Optional]
  2710. screen_name:
  2711. The twitter name of the user whose friends you are fetching.
  2712. If not specified, defaults to the authenticated user. [Optional]
  2713. cursor:
  2714. Should be set to -1 for the initial call and then is used to
  2715. control what result page Twitter returns [Optional(ish)]
  2716. skip_status:
  2717. If True the statuses will not be returned in the user items.
  2718. [Optional]
  2719. include_user_entities:
  2720. When True, the user entities will be included.
  2721. Returns:
  2722. A sequence of twitter.User instances, one for each friend
  2723. '''
  2724. if not self._oauth_consumer:
  2725. raise TwitterError("twitter.Api instance must be authenticated")
  2726. url = '%s/blocks/list.json' % self.base_url
  2727. result = []
  2728. parameters = {}
  2729. if user_id is not None:
  2730. parameters['user_id'] = user_id
  2731. if screen_name is not None:
  2732. parameters['screen_name'] = screen_name
  2733. if skip_status:
  2734. parameters['skip_status'] = True
  2735. if include_user_entities:
  2736. parameters['include_user_entities'] = True
  2737. while True:
  2738. parameters['cursor'] = cursor
  2739. json = self._FetchUrl(url, parameters=parameters)
  2740. data = self._ParseAndCheckTwitter(json)
  2741. result += [User.NewFromJsonDict(x) for x in data['users']]
  2742. if 'next_cursor' in data:
  2743. if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
  2744. break
  2745. else:
  2746. cursor = data['next_cursor']
  2747. else:
  2748. break
  2749. return result
  2750. def GetFriends(self, user_id=None, screen_name=None, cursor=-1, skip_status=False, include_user_entities=False):
  2751. '''Fetch the sequence of twitter.User instances, one for each friend.
  2752. The twitter.Api instance must be authenticated.
  2753. Args:
  2754. user_id:
  2755. The twitter id of the user whose friends you are fetching.
  2756. If not specified, defaults to the authenticated user. [Optional]
  2757. screen_name:
  2758. The twitter name of the user whose friends you are fetching.
  2759. If not specified, defaults to the authenticated user. [Optional]
  2760. cursor:
  2761. Should be set to -1 for the initial call and then is used to
  2762. control what result page Twitter returns [Optional(ish)]
  2763. skip_status:
  2764. If True the statuses will not be returned in the user items.
  2765. [Optional]
  2766. include_user_entities:
  2767. When True, the user entities will be included.
  2768. Returns:
  2769. A sequence of twitter.User instances, one for each friend
  2770. '''
  2771. if not self._oauth_consumer:
  2772. raise TwitterError("twitter.Api instance must be authenticated")
  2773. url = '%s/friends/list.json' % self.base_url
  2774. result = []
  2775. parameters = {}
  2776. if user_id is not None:
  2777. parameters['user_id'] = user_id
  2778. if screen_name is not None:
  2779. parameters['screen_name'] = screen_name
  2780. if skip_status:
  2781. parameters['skip_status'] = True
  2782. if include_user_entities:
  2783. parameters['include_user_entities'] = True
  2784. while True:
  2785. parameters['cursor'] = cursor
  2786. json = self._FetchUrl(url, parameters=parameters)
  2787. data = self._ParseAndCheckTwitter(json)
  2788. result += [User.NewFromJsonDict(x) for x in data['users']]
  2789. if 'next_cursor' in data:
  2790. if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
  2791. break
  2792. else:
  2793. cursor = data['next_cursor']
  2794. else:
  2795. break
  2796. return result
  2797. def GetFriendIDs(self, user_id=None, screen_name=None, cursor=-1, stringify_ids=False, count=None):
  2798. '''Returns a list of twitter user id's for every person
  2799. the specified user is following.
  2800. Args:
  2801. user_id:
  2802. The id of the user to retrieve the id list for
  2803. [Optional]
  2804. screen_name:
  2805. The screen_name of the user to retrieve the id list for
  2806. [Optional]
  2807. cursor:
  2808. Specifies the Twitter API Cursor location to start at.
  2809. Note: there are pagination limits.
  2810. [Optional]
  2811. stringify_ids:
  2812. if True then twitter will return the ids as strings instead of integers.
  2813. [Optional]
  2814. count:
  2815. The number of status messages to retrieve. [Optional]
  2816. Returns:
  2817. A list of integers, one for each user id.
  2818. '''
  2819. url = '%s/friends/ids.json' % self.base_url
  2820. if not self._oauth_consumer:
  2821. raise TwitterError("twitter.Api instance must be authenticated")
  2822. parameters = {}
  2823. if user_id is not None:
  2824. parameters['user_id'] = user_id
  2825. if screen_name is not None:
  2826. parameters['screen_name'] = screen_name
  2827. if stringify_ids:
  2828. parameters['stringify_ids'] = True
  2829. if count is not None:
  2830. parameters['count'] = count
  2831. result = []
  2832. while True:
  2833. parameters['cursor'] = cursor
  2834. json = self._FetchUrl(url, parameters=parameters)
  2835. data = self._ParseAndCheckTwitter(json)
  2836. result += [x for x in data['ids']]
  2837. if 'next_cursor' in data:
  2838. if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
  2839. break
  2840. else:
  2841. cursor = data['next_cursor']
  2842. else:
  2843. break
  2844. return result
  2845. def GetFollowerIDs(self, user_id=None, screen_name=None, cursor=-1, stringify_ids=False, count=None, total_count=None):
  2846. '''Returns a list of twitter user id's for every person
  2847. that is following the specified user.
  2848. Args:
  2849. user_id:
  2850. The id of the user to retrieve the id list for
  2851. [Optional]
  2852. screen_name:
  2853. The screen_name of the user to retrieve the id list for
  2854. [Optional]
  2855. cursor:
  2856. Specifies the Twitter API Cursor location to start at.
  2857. Note: there are pagination limits.
  2858. [Optional]
  2859. stringify_ids:
  2860. if True then twitter will return the ids as strings instead of integers.
  2861. [Optional]
  2862. count:
  2863. The number of user id's to retrieve per API request. Please be aware that
  2864. this might get you rate-limited if set to a small number. By default Twitter
  2865. will retrieve 5000 UIDs per call.
  2866. [Optional]
  2867. total_count:
  2868. The total amount of UIDs to retrieve. Good if the account has many followers
  2869. and you don't want to get rate limited. The data returned might contain more
  2870. UIDs if total_count is not a multiple of count (5000 by default).
  2871. [Optional]
  2872. Returns:
  2873. A list of integers, one for each user id.
  2874. '''
  2875. url = '%s/followers/ids.json' % self.base_url
  2876. if not self._oauth_consumer:
  2877. raise TwitterError("twitter.Api instance must be authenticated")
  2878. parameters = {}
  2879. if user_id is not None:
  2880. parameters['user_id'] = user_id
  2881. if screen_name is not None:
  2882. parameters['screen_name'] = screen_name
  2883. if stringify_ids:
  2884. parameters['stringify_ids'] = True
  2885. if count is not None:
  2886. parameters['count'] = count
  2887. result = []
  2888. while True:
  2889. if total_count and total_count < count:
  2890. parameters['count'] = total_count
  2891. parameters['cursor'] = cursor
  2892. json = self._FetchUrl(url, parameters=parameters)
  2893. data = self._ParseAndCheckTwitter(json)
  2894. result += [x for x in data['ids']]
  2895. if 'next_cursor' in data:
  2896. if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
  2897. break
  2898. else:
  2899. cursor = data['next_cursor']
  2900. total_count -= len(data['ids'])
  2901. if total_count < 1:
  2902. break
  2903. else:
  2904. break
  2905. return result
  2906. def GetFollowers(self, user_id=None, screen_name=None, cursor=-1, skip_status=False, include_user_entities=False):
  2907. '''Fetch the sequence of twitter.User instances, one for each follower
  2908. The twitter.Api instance must be authenticated.
  2909. Args:
  2910. user_id:
  2911. The twitter id of the user whose followers you are fetching.
  2912. If not specified, defaults to the authenticated user. [Optional]
  2913. screen_name:
  2914. The twitter name of the user whose followers you are fetching.
  2915. If not specified, defaults to the authenticated user. [Optional]
  2916. cursor:
  2917. Should be set to -1 for the initial call and then is used to
  2918. control what result page Twitter returns [Optional(ish)]
  2919. skip_status:
  2920. If True the statuses will not be returned in the user items.
  2921. [Optional]
  2922. include_user_entities:
  2923. When True, the user entities will be included.
  2924. Returns:
  2925. A sequence of twitter.User instances, one for each follower
  2926. '''
  2927. if not self._oauth_consumer:
  2928. raise TwitterError("twitter.Api instance must be authenticated")
  2929. url = '%s/followers/list.json' % self.base_url
  2930. result = []
  2931. parameters = {}
  2932. if user_id is not None:
  2933. parameters['user_id'] = user_id
  2934. if screen_name is not None:
  2935. parameters['screen_name'] = screen_name
  2936. if skip_status:
  2937. parameters['skip_status'] = True
  2938. if include_user_entities:
  2939. parameters['include_user_entities'] = True
  2940. while True:
  2941. parameters['cursor'] = cursor
  2942. json = self._FetchUrl(url, parameters=parameters)
  2943. data = self._ParseAndCheckTwitter(json)
  2944. result += [User.NewFromJsonDict(x) for x in data['users']]
  2945. if 'next_cursor' in data:
  2946. if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
  2947. break
  2948. else:
  2949. cursor = data['next_cursor']
  2950. else:
  2951. break
  2952. return result
  2953. def UsersLookup(self, user_id=None, screen_name=None, users=None, include_entities=True):
  2954. '''Fetch extended information for the specified users.
  2955. Users may be specified either as lists of either user_ids,
  2956. screen_names, or twitter.User objects. The list of users that
  2957. are queried is the union of all specified parameters.
  2958. The twitter.Api instance must be authenticated.
  2959. Args:
  2960. user_id:
  2961. A list of user_ids to retrieve extended information.
  2962. [Optional]
  2963. screen_name:
  2964. A list of screen_names to retrieve extended information.
  2965. [Optional]
  2966. users:
  2967. A list of twitter.User objects to retrieve extended information.
  2968. [Optional]
  2969. include_entities:
  2970. The entities node that may appear within embedded statuses will be
  2971. disincluded when set to False.
  2972. [Optional]
  2973. Returns:
  2974. A list of twitter.User objects for the requested users
  2975. '''
  2976. if not self._oauth_consumer:
  2977. raise TwitterError("The twitter.Api instance must be authenticated.")
  2978. if not user_id and not screen_name and not users:
  2979. raise TwitterError("Specify at least one of user_id, screen_name, or users.")
  2980. url = '%s/users/lookup.json' % self.base_url
  2981. parameters = {}
  2982. uids = list()
  2983. if user_id:
  2984. uids.extend(user_id)
  2985. if users:
  2986. uids.extend([u.id for u in users])
  2987. if len(uids):
  2988. parameters['user_id'] = ','.join(["%s" % u for u in uids])
  2989. if screen_name:
  2990. parameters['screen_name'] = ','.join(screen_name)
  2991. if not include_entities:
  2992. parameters['include_entities'] = 'false'
  2993. json = self._FetchUrl(url, parameters=parameters)
  2994. try:
  2995. data = self._ParseAndCheckTwitter(json)
  2996. except TwitterError, e:
  2997. _, e, _ = sys.exc_info()
  2998. t = e.args[0]
  2999. if len(t) == 1 and ('code' in t[0]) and (t[0]['code'] == 34):
  3000. data = []
  3001. else:
  3002. raise
  3003. return [User.NewFromJsonDict(u) for u in data]
  3004. def GetUser(self, user_id=None, screen_name=None, include_entities=True):
  3005. '''Returns a single user.
  3006. The twitter.Api instance must be authenticated.
  3007. Args:
  3008. user_id:
  3009. The id of the user to retrieve.
  3010. [Optional]
  3011. screen_name:
  3012. The screen name of the user for whom to return results for. Either a
  3013. user_id or screen_name is required for this method.
  3014. [Optional]
  3015. include_entities:
  3016. if set to False, the 'entities' node will not be included.
  3017. [Optional]
  3018. Returns:
  3019. A twitter.User instance representing that user
  3020. '''
  3021. url = '%s/users/show.json' % (self.base_url)
  3022. parameters = {}
  3023. if not self._oauth_consumer:
  3024. raise TwitterError("The twitter.Api instance must be authenticated.")
  3025. if user_id:
  3026. parameters['user_id'] = user_id
  3027. elif screen_name:
  3028. parameters['screen_name'] = screen_name
  3029. else:
  3030. raise TwitterError("Specify at least one of user_id or screen_name.")
  3031. if not include_entities:
  3032. parameters['include_entities'] = 'false'
  3033. json = self._FetchUrl(url, parameters=parameters)
  3034. data = self._ParseAndCheckTwitter(json)
  3035. return User.NewFromJsonDict(data)
  3036. def GetDirectMessages(self, since_id=None, max_id=None, count=None, include_entities=True, skip_status=False):
  3037. '''Returns a list of the direct messages sent to the authenticating user.
  3038. The twitter.Api instance must be authenticated.
  3039. Args:
  3040. since_id:
  3041. Returns results with an ID greater than (that is, more recent
  3042. than) the specified ID. There are limits to the number of
  3043. Tweets which can be accessed through the API. If the limit of
  3044. Tweets has occurred since the since_id, the since_id will be
  3045. forced to the oldest ID available. [Optional]
  3046. max_id:
  3047. Returns results with an ID less than (that is, older than) or
  3048. equal to the specified ID. [Optional]
  3049. count:
  3050. Specifies the number of direct messages to try and retrieve, up to a
  3051. maximum of 200. The value of count is best thought of as a limit to the
  3052. number of Tweets to return because suspended or deleted content is
  3053. removed after the count has been applied. [Optional]
  3054. include_entities:
  3055. The entities node will not be included when set to False.
  3056. [Optional]
  3057. skip_status:
  3058. When set to True statuses will not be included in the returned user
  3059. objects. [Optional]
  3060. Returns:
  3061. A sequence of twitter.DirectMessage instances
  3062. '''
  3063. url = '%s/direct_messages.json' % self.base_url
  3064. if not self._oauth_consumer:
  3065. raise TwitterError("The twitter.Api instance must be authenticated.")
  3066. parameters = {}
  3067. if since_id:
  3068. parameters['since_id'] = since_id
  3069. if max_id:
  3070. parameters['max_id'] = max_id
  3071. if count:
  3072. try:
  3073. parameters['count'] = int(count)
  3074. except ValueError:
  3075. raise TwitterError("count must be an integer")
  3076. if not include_entities:
  3077. parameters['include_entities'] = 'false'
  3078. if skip_status:
  3079. parameters['skip_status'] = 1
  3080. json = self._FetchUrl(url, parameters=parameters)
  3081. data = self._ParseAndCheckTwitter(json)
  3082. return [DirectMessage.NewFromJsonDict(x) for x in data]
  3083. def GetSentDirectMessages(self, since_id=None, max_id=None, count=None, page=None, include_entities=True):
  3084. '''Returns a list of the direct messages sent by the authenticating user.
  3085. The twitter.Api instance must be authenticated.
  3086. Args:
  3087. since_id:
  3088. Returns results with an ID greater than (that is, more recent
  3089. than) the specified ID. There are limits to the number of
  3090. Tweets which can be accessed through the API. If the limit of
  3091. Tweets has occured since the since_id, the since_id will be
  3092. forced to the oldest ID available. [Optional]
  3093. max_id:
  3094. Returns results with an ID less than (that is, older than) or
  3095. equal to the specified ID. [Optional]
  3096. count:
  3097. Specifies the number of direct messages to try and retrieve, up to a
  3098. maximum of 200. The value of count is best thought of as a limit to the
  3099. number of Tweets to return because suspended or deleted content is
  3100. removed after the count has been applied. [Optional]
  3101. page:
  3102. Specifies the page of results to retrieve.
  3103. Note: there are pagination limits. [Optional]
  3104. include_entities:
  3105. The entities node will not be included when set to False.
  3106. [Optional]
  3107. Returns:
  3108. A sequence of twitter.DirectMessage instances
  3109. '''
  3110. url = '%s/direct_messages/sent.json' % self.base_url
  3111. if not self._oauth_consumer:
  3112. raise TwitterError("The twitter.Api instance must be authenticated.")
  3113. parameters = {}
  3114. if since_id:
  3115. parameters['since_id'] = since_id
  3116. if page:
  3117. parameters['page'] = page
  3118. if max_id:
  3119. parameters['max_id'] = max_id
  3120. if count:
  3121. try:
  3122. parameters['count'] = int(count)
  3123. except ValueError:
  3124. raise TwitterError("count must be an integer")
  3125. if not include_entities:
  3126. parameters['include_entities'] = 'false'
  3127. json = self._FetchUrl(url, parameters=parameters)
  3128. data = self._ParseAndCheckTwitter(json)
  3129. return [DirectMessage.NewFromJsonDict(x) for x in data]
  3130. def PostDirectMessage(self, text, user_id=None, screen_name=None):
  3131. '''Post a twitter direct message from the authenticated user
  3132. The twitter.Api instance must be authenticated. user_id or screen_name
  3133. must be specified.
  3134. Args:
  3135. text: The message text to be posted. Must be less than 140 characters.
  3136. user_id:
  3137. The ID of the user who should receive the direct message.
  3138. [Optional]
  3139. screen_name:
  3140. The screen name of the user who should receive the direct message.
  3141. [Optional]
  3142. Returns:
  3143. A twitter.DirectMessage instance representing the message posted
  3144. '''
  3145. if not self._oauth_consumer:
  3146. raise TwitterError("The twitter.Api instance must be authenticated.")
  3147. url = '%s/direct_messages/new.json' % self.base_url
  3148. data = {'text': text}
  3149. if self.source_api == "api.twitter.com" and user_id:
  3150. data['user_id'] = user_id
  3151. elif self.source_api != "api.twitter.com" and user_id:
  3152. data['screen_name'] = user_id
  3153. elif screen_name:
  3154. data['screen_name'] = screen_name
  3155. else:
  3156. raise TwitterError("Specify at least one of user_id or screen_name.")
  3157. json = self._FetchUrl(url, post_data=data)
  3158. data = self._ParseAndCheckTwitter(json)
  3159. return DirectMessage.NewFromJsonDict(data)
  3160. def DestroyDirectMessage(self, id, include_entities=True):
  3161. '''Destroys the direct message specified in the required ID parameter.
  3162. The twitter.Api instance must be authenticated, and the
  3163. authenticating user must be the recipient of the specified direct
  3164. message.
  3165. Args:
  3166. id: The id of the direct message to be destroyed
  3167. Returns:
  3168. A twitter.DirectMessage instance representing the message destroyed
  3169. '''
  3170. url = '%s/direct_messages/destroy.json' % self.base_url
  3171. data = {'id': id}
  3172. if not include_entities:
  3173. data['include_entities'] = 'false'
  3174. json = self._FetchUrl(url, post_data=data)
  3175. data = self._ParseAndCheckTwitter(json)
  3176. return DirectMessage.NewFromJsonDict(data)
  3177. def CreateFriendship(self, user_id=None, screen_name=None, follow=True):
  3178. '''Befriends the user specified by the user_id or screen_name.
  3179. The twitter.Api instance must be authenticated.
  3180. Args:
  3181. user_id:
  3182. A user_id to follow [Optional]
  3183. screen_name:
  3184. A screen_name to follow [Optional]
  3185. follow:
  3186. Set to False to disable notifications for the target user
  3187. Returns:
  3188. A twitter.User instance representing the befriended user.
  3189. '''
  3190. url = '%s/friendships/create.json' % (self.base_url)
  3191. data = {}
  3192. if self.source_api != "api.twitter.com" and user_id:
  3193. data['screen_name'] = user_id
  3194. elif user_id:
  3195. data['user_id'] = user_id
  3196. elif screen_name:
  3197. data['screen_name'] = screen_name
  3198. else:
  3199. raise TwitterError("Specify at least one of user_id or screen_name.")
  3200. if follow:
  3201. data['follow'] = 'true'
  3202. else:
  3203. data['follow'] = 'false'
  3204. json = self._FetchUrl(url, post_data=data)
  3205. data = self._ParseAndCheckTwitter(json)
  3206. return User.NewFromJsonDict(data)
  3207. def DestroyFriendship(self, user_id=None, screen_name=None):
  3208. '''Discontinues friendship with a user_id or screen_name.
  3209. The twitter.Api instance must be authenticated.
  3210. Args:
  3211. user_id:
  3212. A user_id to unfollow [Optional]
  3213. screen_name:
  3214. A screen_name to unfollow [Optional]
  3215. Returns:
  3216. A twitter.User instance representing the discontinued friend.
  3217. '''
  3218. url = '%s/friendships/destroy.json' % self.base_url
  3219. data = {}
  3220. if self.source_api != "api.twitter.com" and user_id:
  3221. data['screen_name'] = user_id
  3222. elif user_id:
  3223. data['user_id'] = user_id
  3224. elif screen_name:
  3225. data['screen_name'] = screen_name
  3226. else:
  3227. raise TwitterError("Specify at least one of user_id or screen_name.")
  3228. json = self._FetchUrl(url, post_data=data)
  3229. data = self._ParseAndCheckTwitter(json)
  3230. return User.NewFromJsonDict(data)
  3231. def CreateFavorite(self, status=None, id=None, include_entities=True):
  3232. '''Favorites the specified status object or id as the authenticating user.
  3233. Returns the favorite status when successful.
  3234. The twitter.Api instance must be authenticated.
  3235. Args:
  3236. id:
  3237. The id of the twitter status to mark as a favorite.
  3238. [Optional]
  3239. status:
  3240. The twitter.Status object to mark as a favorite.
  3241. [Optional]
  3242. include_entities:
  3243. The entities node will be omitted when set to False.
  3244. Returns:
  3245. A twitter.Status instance representing the newly-marked favorite.
  3246. '''
  3247. url = '%s/favorites/create.json' % self.base_url
  3248. data = {}
  3249. if id:
  3250. data['id'] = id
  3251. elif isinstance(status, str):
  3252. data['id'] = status
  3253. elif status:
  3254. data['id'] = status.id
  3255. else:
  3256. raise TwitterError("Specify id or status")
  3257. if not include_entities:
  3258. data['include_entities'] = 'false'
  3259. json = self._FetchUrl(url, post_data=data)
  3260. data = self._ParseAndCheckTwitter(json)
  3261. return Status.NewFromJsonDict(data)
  3262. def DestroyFavorite(self, status=None, id=None, include_entities=True):
  3263. '''Un-Favorites the specified status object or id as the authenticating user.
  3264. Returns the un-favorited status when successful.
  3265. The twitter.Api instance must be authenticated.
  3266. Args:
  3267. id:
  3268. The id of the twitter status to unmark as a favorite.
  3269. [Optional]
  3270. status:
  3271. The twitter.Status object to unmark as a favorite.
  3272. [Optional]
  3273. include_entities:
  3274. The entities node will be omitted when set to False.
  3275. Returns:
  3276. A twitter.Status instance representing the newly-unmarked favorite.
  3277. '''
  3278. url = '%s/favorites/destroy.json' % self.base_url
  3279. data = {}
  3280. if id:
  3281. data['id'] = id
  3282. elif isinstance(status, str):
  3283. data['id'] = status
  3284. elif status:
  3285. data['id'] = status.id
  3286. else:
  3287. raise TwitterError("Specify id or status")
  3288. if not include_entities:
  3289. data['include_entities'] = 'false'
  3290. json = self._FetchUrl(url, post_data=data)
  3291. data = self._ParseAndCheckTwitter(json)
  3292. return Status.NewFromJsonDict(data)
  3293. def GetFavorites(self,
  3294. user_id=None,
  3295. screen_name=None,
  3296. count=None,
  3297. since_id=None,
  3298. max_id=None,
  3299. include_entities=True):
  3300. '''Return a list of Status objects representing favorited tweets.
  3301. By default, returns the (up to) 20 most recent tweets for the
  3302. authenticated user.
  3303. Args:
  3304. user:
  3305. The twitter name or id of the user whose favorites you are fetching.
  3306. If not specified, defaults to the authenticated user. [Optional]
  3307. page:
  3308. Specifies the page of results to retrieve.
  3309. Note: there are pagination limits. [Optional]
  3310. '''
  3311. parameters = {}
  3312. url = '%s/favorites/list.json' % self.base_url
  3313. if self.source_api == "api.twitter.com" and user_id:
  3314. parameters['user_id'] = user_id
  3315. elif self.source_api == "api.twitter.com" and screen_name:
  3316. parameters['screen_name'] = user_id
  3317. if since_id:
  3318. try:
  3319. parameters['since_id'] = long(since_id)
  3320. except ValueError:
  3321. raise TwitterError("since_id must be an integer")
  3322. if max_id:
  3323. try:
  3324. parameters['max_id'] = long(max_id)
  3325. except ValueError:
  3326. raise TwitterError("max_id must be an integer")
  3327. if count:
  3328. try:
  3329. parameters['count'] = int(count)
  3330. except ValueError:
  3331. raise TwitterError("count must be an integer")
  3332. if include_entities:
  3333. parameters['include_entities'] = True
  3334. json = self._FetchUrl(url, parameters=parameters)
  3335. data = self._ParseAndCheckTwitter(json)
  3336. return [Status.NewFromJsonDict(x) for x in data]
  3337. def GetMentions(self,
  3338. count=None,
  3339. since_id=None,
  3340. max_id=None,
  3341. trim_user=False,
  3342. contributor_details=False,
  3343. include_entities=True):
  3344. '''Returns the 20 most recent mentions (status containing @screen_name)
  3345. for the authenticating user.
  3346. Args:
  3347. count:
  3348. Specifies the number of tweets to try and retrieve, up to a maximum of
  3349. 200. The value of count is best thought of as a limit to the number of
  3350. tweets to return because suspended or deleted content is removed after
  3351. the count has been applied. [Optional]
  3352. since_id:
  3353. Returns results with an ID greater than (that is, more recent
  3354. than) the specified ID. There are limits to the number of
  3355. Tweets which can be accessed through the API. If the limit of
  3356. Tweets has occurred since the since_id, the since_id will be
  3357. forced to the oldest ID available. [Optional]
  3358. max_id:
  3359. Returns only statuses with an ID less than
  3360. (that is, older than) the specified ID. [Optional]
  3361. trim_user:
  3362. When set to True, each tweet returned in a timeline will include a user
  3363. object including only the status authors numerical ID. Omit this
  3364. parameter to receive the complete user object.
  3365. contributor_details:
  3366. If set to True, this parameter enhances the contributors element of the
  3367. status response to include the screen_name of the contributor. By
  3368. default only the user_id of the contributor is included.
  3369. include_entities:
  3370. The entities node will be disincluded when set to False.
  3371. Returns:
  3372. A sequence of twitter.Status instances, one for each mention of the user.
  3373. '''
  3374. url = '%s/statuses/mentions_timeline.json' % self.base_url
  3375. if not self._oauth_consumer:
  3376. raise TwitterError("The twitter.Api instance must be authenticated.")
  3377. parameters = {}
  3378. if count:
  3379. try:
  3380. parameters['count'] = int(count)
  3381. except ValueError:
  3382. raise TwitterError("count must be an integer")
  3383. if since_id:
  3384. try:
  3385. parameters['since_id'] = long(since_id)
  3386. except ValueError:
  3387. raise TwitterError("since_id must be an integer")
  3388. if max_id:
  3389. try:
  3390. parameters['max_id'] = long(max_id)
  3391. except ValueError:
  3392. raise TwitterError("max_id must be an integer")
  3393. if trim_user:
  3394. parameters['trim_user'] = 1
  3395. if contributor_details:
  3396. parameters['contributor_details'] = 'true'
  3397. if not include_entities:
  3398. parameters['include_entities'] = 'false'
  3399. json = self._FetchUrl(url, parameters=parameters)
  3400. data = self._ParseAndCheckTwitter(json)
  3401. return [Status.NewFromJsonDict(x) for x in data]
  3402. def CreateList(self, name, mode=None, description=None):
  3403. '''Creates a new list with the give name for the authenticated user.
  3404. The twitter.Api instance must be authenticated.
  3405. Args:
  3406. name:
  3407. New name for the list
  3408. mode:
  3409. 'public' or 'private'.
  3410. Defaults to 'public'. [Optional]
  3411. description:
  3412. Description of the list. [Optional]
  3413. Returns:
  3414. A twitter.List instance representing the new list
  3415. '''
  3416. url = '%s/lists/create.json' % self.base_url
  3417. if not self._oauth_consumer:
  3418. raise TwitterError("The twitter.Api instance must be authenticated.")
  3419. parameters = {'name': name}
  3420. if mode is not None:
  3421. parameters['mode'] = mode
  3422. if description is not None:
  3423. parameters['description'] = description
  3424. json = self._FetchUrl(url, post_data=parameters)
  3425. data = self._ParseAndCheckTwitter(json)
  3426. return List.NewFromJsonDict(data)
  3427. def DestroyList(self,
  3428. owner_screen_name=False,
  3429. owner_id=False,
  3430. list_id=None,
  3431. slug=None):
  3432. '''
  3433. Destroys the list identified by list_id or owner_screen_name/owner_id and
  3434. slug.
  3435. The twitter.Api instance must be authenticated.
  3436. Args:
  3437. owner_screen_name:
  3438. The screen_name of the user who owns the list being requested by a slug.
  3439. owner_id:
  3440. The user ID of the user who owns the list being requested by a slug.
  3441. list_id:
  3442. The numerical id of the list.
  3443. slug:
  3444. You can identify a list by its slug instead of its numerical id. If you
  3445. decide to do so, note that you'll also have to specify the list owner
  3446. using the owner_id or owner_screen_name parameters.
  3447. Returns:
  3448. A twitter.List instance representing the removed list.
  3449. '''
  3450. url = '%s/lists/destroy.json' % self.base_url
  3451. data = {}
  3452. if list_id:
  3453. try:
  3454. data['list_id']= long(list_id)
  3455. except ValueError:
  3456. raise TwitterError("list_id must be an integer")
  3457. elif slug:
  3458. data['slug'] = slug
  3459. if owner_id:
  3460. try:
  3461. data['owner_id'] = long(owner_id)
  3462. except ValueError:
  3463. raise TwitterError("owner_id must be an integer")
  3464. elif owner_screen_name:
  3465. data['owner_screen_name'] = owner_screen_name
  3466. else:
  3467. raise TwitterError("Identify list by list_id or owner_screen_name/owner_id and slug")
  3468. else:
  3469. raise TwitterError("Identify list by list_id or owner_screen_name/owner_id and slug")
  3470. json = self._FetchUrl(url, post_data=data)
  3471. data = self._ParseAndCheckTwitter(json)
  3472. return List.NewFromJsonDict(data)
  3473. def CreateSubscription(self,
  3474. owner_screen_name=False,
  3475. owner_id=False,
  3476. list_id=None,
  3477. slug=None):
  3478. '''Creates a subscription to a list by the authenticated user
  3479. The twitter.Api instance must be authenticated.
  3480. Args:
  3481. owner_screen_name:
  3482. The screen_name of the user who owns the list being requested by a slug.
  3483. owner_id:
  3484. The user ID of the user who owns the list being requested by a slug.
  3485. list_id:
  3486. The numerical id of the list.
  3487. slug:
  3488. You can identify a list by its slug instead of its numerical id. If you
  3489. decide to do so, note that you'll also have to specify the list owner
  3490. using the owner_id or owner_screen_name parameters.
  3491. Returns:
  3492. A twitter.List instance representing the list subscribed to
  3493. '''
  3494. url = '%s/lists/subscribers/create.json' % (self.base_url)
  3495. if not self._oauth_consumer:
  3496. raise TwitterError("The twitter.Api instance must be authenticated.")
  3497. data = {}
  3498. if list_id:
  3499. try:
  3500. data['list_id']= long(list_id)
  3501. except ValueError:
  3502. raise TwitterError("list_id must be an integer")
  3503. elif slug:
  3504. data['slug'] = slug
  3505. if owner_id:
  3506. try:
  3507. data['owner_id'] = long(owner_id)
  3508. except ValueError:
  3509. raise TwitterError("owner_id must be an integer")
  3510. elif owner_screen_name:
  3511. data['owner_screen_name'] = owner_screen_name
  3512. else:
  3513. raise TwitterError("Identify list by list_id or owner_screen_name/owner_id and slug")
  3514. else:
  3515. raise TwitterError("Identify list by list_id or owner_screen_name/owner_id and slug")
  3516. json = self._FetchUrl(url, post_data=data)
  3517. data = self._ParseAndCheckTwitter(json)
  3518. return List.NewFromJsonDict(data)
  3519. def DestroySubscription(self,
  3520. owner_screen_name=False,
  3521. owner_id=False,
  3522. list_id=None,
  3523. slug=None):
  3524. '''Destroys the subscription to a list for the authenticated user
  3525. The twitter.Api instance must be authenticated.
  3526. Args:
  3527. owner_screen_name:
  3528. The screen_name of the user who owns the list being requested by a slug.
  3529. owner_id:
  3530. The user ID of the user who owns the list being requested by a slug.
  3531. list_id:
  3532. The numerical id of the list.
  3533. slug:
  3534. You can identify a list by its slug instead of its numerical id. If you
  3535. decide to do so, note that you'll also have to specify the list owner
  3536. using the owner_id or owner_screen_name parameters.
  3537. Returns:
  3538. A twitter.List instance representing the removed list.
  3539. '''
  3540. url = '%s/lists/subscribers/destroy.json' % (self.base_url)
  3541. if not self._oauth_consumer:
  3542. raise TwitterError("The twitter.Api instance must be authenticated.")
  3543. data = {}
  3544. if list_id:
  3545. try:
  3546. data['list_id']= long(list_id)
  3547. except ValueError:
  3548. raise TwitterError("list_id must be an integer")
  3549. elif slug:
  3550. data['slug'] = slug
  3551. if owner_id:
  3552. try:
  3553. data['owner_id'] = long(owner_id)
  3554. except ValueError:
  3555. raise TwitterError("owner_id must be an integer")
  3556. elif owner_screen_name:
  3557. data['owner_screen_name'] = owner_screen_name
  3558. else:
  3559. raise TwitterError("Identify list by list_id or owner_screen_name/owner_id and slug")
  3560. else:
  3561. raise TwitterError("Identify list by list_id or owner_screen_name/owner_id and slug")
  3562. json = self._FetchUrl(url, post_data=data)
  3563. data = self._ParseAndCheckTwitter(json)
  3564. return List.NewFromJsonDict(data)
  3565. def GetSubscriptions(self, user_id=None, screen_name=None, count=20, cursor=-1):
  3566. '''
  3567. Obtain a collection of the lists the specified user is subscribed to, 20
  3568. lists per page by default. Does not include the user's own lists.
  3569. The twitter.Api instance must be authenticated.
  3570. Args:
  3571. user_id:
  3572. The ID of the user for whom to return results for. [Optional]
  3573. screen_name:
  3574. The screen name of the user for whom to return results for.
  3575. [Optional]
  3576. count:
  3577. The amount of results to return per page. Defaults to 20.
  3578. No more than 1000 results will ever be returned in a single page.
  3579. cursor:
  3580. "page" value that Twitter will use to start building the
  3581. list sequence from. -1 to start at the beginning.
  3582. Twitter will return in the result the values for next_cursor
  3583. and previous_cursor. [Optional]
  3584. Returns:
  3585. A sequence of twitter.List instances, one for each list
  3586. '''
  3587. if not self._oauth_consumer:
  3588. raise TwitterError("twitter.Api instance must be authenticated")
  3589. url = '%s/lists/subscriptions.json' % (self.base_url)
  3590. parameters = {}
  3591. try:
  3592. parameters['cursor'] = int(cursor)
  3593. except ValueError:
  3594. raise TwitterError("cursor must be an integer")
  3595. try:
  3596. parameters['count'] = int(count)
  3597. except ValueError:
  3598. raise TwitterError("count must be an integer")
  3599. if user_id is not None:
  3600. try:
  3601. parameters['user_id'] = long(user_id)
  3602. except ValueError:
  3603. raise TwitterError('user_id must be an integer')
  3604. elif screen_name is not None:
  3605. parameters['screen_name'] = screen_name
  3606. else:
  3607. raise TwitterError('Specify user_id or screen_name')
  3608. json = self._FetchUrl(url, parameters=parameters)
  3609. data = self._ParseAndCheckTwitter(json)
  3610. return [List.NewFromJsonDict(x) for x in data['lists']]
  3611. def GetLists(self, user_id=None, screen_name=None, count=None, cursor=-1):
  3612. '''Fetch the sequence of lists for a user.
  3613. The twitter.Api instance must be authenticated.
  3614. Args:
  3615. user_id:
  3616. The ID of the user for whom to return results for. [Optional]
  3617. screen_name:
  3618. The screen name of the user for whom to return results for.
  3619. [Optional]
  3620. count:
  3621. The amount of results to return per page. Defaults to 20. No more than
  3622. 1000 results will ever be returned in a single page.
  3623. [Optional]
  3624. cursor:
  3625. "page" value that Twitter will use to start building the
  3626. list sequence from. -1 to start at the beginning.
  3627. Twitter will return in the result the values for next_cursor
  3628. and previous_cursor. [Optional]
  3629. Returns:
  3630. A sequence of twitter.List instances, one for each list
  3631. '''
  3632. if not self._oauth_consumer:
  3633. raise TwitterError("twitter.Api instance must be authenticated")
  3634. url = '%s/lists/ownerships.json' % self.base_url
  3635. result = []
  3636. parameters = {}
  3637. if user_id is not None:
  3638. try:
  3639. parameters['user_id'] = long(user_id)
  3640. except ValueError:
  3641. raise TwitterError('user_id must be an integer')
  3642. elif screen_name is not None:
  3643. parameters['screen_name'] = screen_name
  3644. else:
  3645. raise TwitterError('Specify user_id or screen_name')
  3646. if count is not None:
  3647. parameters['count'] = count
  3648. while True:
  3649. parameters['cursor'] = cursor
  3650. json = self._FetchUrl(url, parameters=parameters)
  3651. data = self._ParseAndCheckTwitter(json)
  3652. result += [List.NewFromJsonDict(x) for x in data['lists']]
  3653. if 'next_cursor' in data:
  3654. if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
  3655. break
  3656. else:
  3657. cursor = data['next_cursor']
  3658. else:
  3659. break
  3660. return result
  3661. def VerifyCredentials(self):
  3662. '''Returns a twitter.User instance if the authenticating user is valid.
  3663. Returns:
  3664. A twitter.User instance representing that user if the
  3665. credentials are valid, None otherwise.
  3666. '''
  3667. if not self._oauth_consumer:
  3668. raise TwitterError("Api instance must first be given user credentials.")
  3669. url = '%s/account/verify_credentials.json' % self.base_url
  3670. try:
  3671. json = self._FetchUrl(url, no_cache=True)
  3672. except urllib2.HTTPError, http_error:
  3673. if http_error.code == httplib.UNAUTHORIZED:
  3674. return None
  3675. else:
  3676. raise http_error
  3677. data = self._ParseAndCheckTwitter(json)
  3678. return User.NewFromJsonDict(data)
  3679. def SetCache(self, cache):
  3680. '''Override the default cache. Set to None to prevent caching.
  3681. Args:
  3682. cache:
  3683. An instance that supports the same API as the twitter._FileCache
  3684. '''
  3685. if cache == DEFAULT_CACHE:
  3686. self._cache = _FileCache()
  3687. else:
  3688. self._cache = cache
  3689. def SetUrllib(self, urllib):
  3690. '''Override the default urllib implementation.
  3691. Args:
  3692. urllib:
  3693. An instance that supports the same API as the urllib2 module
  3694. '''
  3695. self._urllib = urllib
  3696. def SetCacheTimeout(self, cache_timeout):
  3697. '''Override the default cache timeout.
  3698. Args:
  3699. cache_timeout:
  3700. Time, in seconds, that responses should be reused.
  3701. '''
  3702. self._cache_timeout = cache_timeout
  3703. def SetUserAgent(self, user_agent):
  3704. '''Override the default user agent
  3705. Args:
  3706. user_agent:
  3707. A string that should be send to the server as the User-agent
  3708. '''
  3709. self._request_headers['User-Agent'] = user_agent
  3710. def SetXTwitterHeaders(self, client, url, version):
  3711. '''Set the X-Twitter HTTP headers that will be sent to the server.
  3712. Args:
  3713. client:
  3714. The client name as a string. Will be sent to the server as
  3715. the 'X-Twitter-Client' header.
  3716. url:
  3717. The URL of the meta.xml as a string. Will be sent to the server
  3718. as the 'X-Twitter-Client-URL' header.
  3719. version:
  3720. The client version as a string. Will be sent to the server
  3721. as the 'X-Twitter-Client-Version' header.
  3722. '''
  3723. self._request_headers['X-Twitter-Client'] = client
  3724. self._request_headers['X-Twitter-Client-URL'] = url
  3725. self._request_headers['X-Twitter-Client-Version'] = version
  3726. def SetSource(self, source):
  3727. '''Suggest the "from source" value to be displayed on the Twitter web site.
  3728. The value of the 'source' parameter must be first recognized by
  3729. the Twitter server. New source values are authorized on a case by
  3730. case basis by the Twitter development team.
  3731. Args:
  3732. source:
  3733. The source name as a string. Will be sent to the server as
  3734. the 'source' parameter.
  3735. '''
  3736. self._default_params['source'] = source
  3737. def GetRateLimitStatus(self, resources=None):
  3738. '''Fetch the rate limit status for the currently authorized user.
  3739. Args:
  3740. resources:
  3741. A comma seperated list of resource families you want to know the current
  3742. rate limit disposition of.
  3743. [Optional]
  3744. Returns:
  3745. A dictionary containing the time the limit will reset (reset_time),
  3746. the number of remaining hits allowed before the reset (remaining_hits),
  3747. the number of hits allowed in a 60-minute period (hourly_limit), and
  3748. the time of the reset in seconds since The Epoch (reset_time_in_seconds).
  3749. '''
  3750. parameters = {}
  3751. if resources is not None:
  3752. parameters['resources'] = resources
  3753. url = '%s/application/rate_limit_status.json' % self.base_url
  3754. json = self._FetchUrl(url, parameters=parameters, no_cache=True)
  3755. data = self._ParseAndCheckTwitter(json)
  3756. return data
  3757. def MaximumHitFrequency(self):
  3758. '''Determines the minimum number of seconds that a program must wait
  3759. before hitting the server again without exceeding the rate_limit
  3760. imposed for the currently authenticated user.
  3761. Returns:
  3762. The minimum second interval that a program must use so as to not
  3763. exceed the rate_limit imposed for the user.
  3764. '''
  3765. rate_status = self.GetRateLimitStatus()
  3766. reset_time = rate_status.get('reset_time', None)
  3767. limit = rate_status.get('remaining_hits', None)
  3768. if reset_time:
  3769. # put the reset time into a datetime object
  3770. reset = datetime.datetime(*rfc822.parsedate(reset_time)[:7])
  3771. # find the difference in time between now and the reset time + 1 hour
  3772. delta = reset + datetime.timedelta(hours=1) - datetime.datetime.utcnow()
  3773. if not limit:
  3774. return int(delta.seconds)
  3775. # determine the minimum number of seconds allowed as a regular interval
  3776. max_frequency = int(delta.seconds / limit) + 1
  3777. # return the number of seconds
  3778. return max_frequency
  3779. return 60
  3780. def _BuildUrl(self, url, path_elements=None, extra_params=None):
  3781. # Break url into constituent parts
  3782. (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
  3783. # Add any additional path elements to the path
  3784. if path_elements:
  3785. # Filter out the path elements that have a value of None
  3786. p = [i for i in path_elements if i]
  3787. if not path.endswith('/'):
  3788. path += '/'
  3789. path += '/'.join(p)
  3790. # Add any additional query parameters to the query string
  3791. if extra_params and len(extra_params) > 0:
  3792. extra_query = self._EncodeParameters(extra_params)
  3793. # Add it to the existing query
  3794. if query:
  3795. query += '&' + extra_query
  3796. else:
  3797. query = extra_query
  3798. # Return the rebuilt URL
  3799. return urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
  3800. def _InitializeRequestHeaders(self, request_headers):
  3801. if request_headers:
  3802. self._request_headers = request_headers
  3803. else:
  3804. self._request_headers = {}
  3805. def _InitializeUserAgent(self):
  3806. user_agent = 'Python-urllib/%s (python-twitter/%s)' % \
  3807. (self._urllib.__version__, __version__)
  3808. self.SetUserAgent(user_agent)
  3809. def _InitializeDefaultParameters(self):
  3810. self._default_params = {}
  3811. def _DecompressGzippedResponse(self, response):
  3812. raw_data = response.read()
  3813. if response.headers.get('content-encoding', None) == 'gzip':
  3814. url_data = gzip.GzipFile(fileobj=StringIO.StringIO(raw_data)).read()
  3815. else:
  3816. url_data = raw_data
  3817. return url_data
  3818. def _Encode(self, s):
  3819. if self._input_encoding:
  3820. return unicode(s, self._input_encoding).encode('utf-8')
  3821. else:
  3822. return unicode(s).encode('utf-8')
  3823. def _EncodeParameters(self, parameters):
  3824. '''Return a string in key=value&key=value form
  3825. Values of None are not included in the output string.
  3826. Args:
  3827. parameters:
  3828. A dict of (key, value) tuples, where value is encoded as
  3829. specified by self._encoding
  3830. Returns:
  3831. A URL-encoded string in "key=value&key=value" form
  3832. '''
  3833. if parameters is None:
  3834. return None
  3835. else:
  3836. return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None]))
  3837. def _EncodePostData(self, post_data):
  3838. '''Return a string in key=value&key=value form
  3839. Values are assumed to be encoded in the format specified by self._encoding,
  3840. and are subsequently URL encoded.
  3841. Args:
  3842. post_data:
  3843. A dict of (key, value) tuples, where value is encoded as
  3844. specified by self._encoding
  3845. Returns:
  3846. A URL-encoded string in "key=value&key=value" form
  3847. '''
  3848. if post_data is None:
  3849. return None
  3850. else:
  3851. return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()]))
  3852. def _ParseAndCheckTwitter(self, json):
  3853. """Try and parse the JSON returned from Twitter and return
  3854. an empty dictionary if there is any error. This is a purely
  3855. defensive check because during some Twitter network outages
  3856. it will return an HTML failwhale page."""
  3857. try:
  3858. data = simplejson.loads(json)
  3859. self._CheckForTwitterError(data)
  3860. except ValueError:
  3861. if "<title>Twitter / Over capacity</title>" in json:
  3862. raise TwitterError("Capacity Error")
  3863. if "<title>Twitter / Error</title>" in json:
  3864. raise TwitterError("Technical Error")
  3865. raise TwitterError("json decoding")
  3866. return data
  3867. def _CheckForTwitterError(self, data):
  3868. """Raises a TwitterError if twitter returns an error message.
  3869. Args:
  3870. data:
  3871. A python dict created from the Twitter json response
  3872. Raises:
  3873. TwitterError wrapping the twitter error message if one exists.
  3874. """
  3875. # Twitter errors are relatively unlikely, so it is faster
  3876. # to check first, rather than try and catch the exception
  3877. if 'error' in data:
  3878. raise TwitterError(data['error'])
  3879. if 'errors' in data:
  3880. raise TwitterError(data['errors'])
  3881. def _FetchUrl(self,
  3882. url,
  3883. post_data=None,
  3884. parameters=None,
  3885. no_cache=None,
  3886. use_gzip_compression=None):
  3887. '''Fetch a URL, optionally caching for a specified time.
  3888. Args:
  3889. url:
  3890. The URL to retrieve
  3891. post_data:
  3892. A dict of (str, unicode) key/value pairs.
  3893. If set, POST will be used.
  3894. parameters:
  3895. A dict whose key/value pairs should encoded and added
  3896. to the query string. [Optional]
  3897. no_cache:
  3898. If true, overrides the cache on the current request
  3899. use_gzip_compression:
  3900. If True, tells the server to gzip-compress the response.
  3901. It does not apply to POST requests.
  3902. Defaults to None, which will get the value to use from
  3903. the instance variable self._use_gzip [Optional]
  3904. Returns:
  3905. A string containing the body of the response.
  3906. '''
  3907. # Build the extra parameters dict
  3908. extra_params = {}
  3909. if self._default_params:
  3910. extra_params.update(self._default_params)
  3911. if parameters:
  3912. extra_params.update(parameters)
  3913. if post_data:
  3914. http_method = "POST"
  3915. else:
  3916. http_method = "GET"
  3917. if self._debugHTTP:
  3918. _debug = 1
  3919. else:
  3920. _debug = 0
  3921. http_handler = self._urllib.HTTPHandler(debuglevel=_debug)
  3922. https_handler = self._urllib.HTTPSHandler(debuglevel=_debug)
  3923. if self.http_proxy is None :
  3924. proxy_status = False
  3925. else :
  3926. proxy_status = True
  3927. opener = self._urllib.OpenerDirector()
  3928. opener.add_handler(http_handler)
  3929. opener.add_handler(https_handler)
  3930. if proxy_status is True :
  3931. proxy_handler = self._urllib.ProxyHandler({'http':str(self.http_proxy),'https': str(self.http_proxy)})
  3932. opener.add_handler(proxy_handler)
  3933. if use_gzip_compression is None:
  3934. use_gzip = self._use_gzip
  3935. else:
  3936. use_gzip = use_gzip_compression
  3937. # Set up compression
  3938. if use_gzip and not post_data:
  3939. opener.addheaders.append(('Accept-Encoding', 'gzip'))
  3940. if self._oauth_consumer is not None:
  3941. if post_data and http_method == "POST":
  3942. parameters = post_data.copy()
  3943. req = oauth.Request.from_consumer_and_token(self._oauth_consumer,
  3944. token=self._oauth_token,
  3945. http_method=http_method,
  3946. http_url=url, parameters=parameters)
  3947. req.sign_request(self._signature_method_hmac_sha1, self._oauth_consumer, self._oauth_token)
  3948. headers = req.to_header()
  3949. if http_method == "POST":
  3950. encoded_post_data = req.to_postdata()
  3951. else:
  3952. encoded_post_data = None
  3953. url = req.to_url()
  3954. else:
  3955. url = self._BuildUrl(url, extra_params=extra_params)
  3956. encoded_post_data = self._EncodePostData(post_data)
  3957. # Open and return the URL immediately if we're not going to cache
  3958. if encoded_post_data or no_cache or not self._cache or not self._cache_timeout:
  3959. response = opener.open(url, encoded_post_data)
  3960. url_data = self._DecompressGzippedResponse(response)
  3961. opener.close()
  3962. else:
  3963. # Unique keys are a combination of the url and the oAuth Consumer Key
  3964. if self._consumer_key:
  3965. key = self._consumer_key + ':' + url
  3966. else:
  3967. key = url
  3968. # See if it has been cached before
  3969. last_cached = self._cache.GetCachedTime(key)
  3970. # If the cached version is outdated then fetch another and store it
  3971. if not last_cached or time.time() >= last_cached + self._cache_timeout:
  3972. try:
  3973. response = opener.open(url, encoded_post_data)
  3974. url_data = self._DecompressGzippedResponse(response)
  3975. self._cache.Set(key, url_data)
  3976. except urllib2.HTTPError, e:
  3977. print e
  3978. opener.close()
  3979. else:
  3980. url_data = self._cache.Get(key)
  3981. # Always return the latest version
  3982. return url_data
  3983. class _FileCacheError(Exception):
  3984. '''Base exception class for FileCache related errors'''
  3985. class _FileCache(object):
  3986. DEPTH = 3
  3987. def __init__(self,root_directory=None):
  3988. self._InitializeRootDirectory(root_directory)
  3989. def Get(self,key):
  3990. path = self._GetPath(key)
  3991. if os.path.exists(path):
  3992. return open(path).read()
  3993. else:
  3994. return None
  3995. def Set(self,key,data):
  3996. path = self._GetPath(key)
  3997. directory = os.path.dirname(path)
  3998. if not os.path.exists(directory):
  3999. os.makedirs(directory)
  4000. if not os.path.isdir(directory):
  4001. raise _FileCacheError('%s exists but is not a directory' % directory)
  4002. temp_fd, temp_path = tempfile.mkstemp()
  4003. temp_fp = os.fdopen(temp_fd, 'w')
  4004. temp_fp.write(data)
  4005. temp_fp.close()
  4006. if not path.startswith(self._root_directory):
  4007. raise _FileCacheError('%s does not appear to live under %s' %
  4008. (path, self._root_directory))
  4009. if os.path.exists(path):
  4010. os.remove(path)
  4011. os.rename(temp_path, path)
  4012. def Remove(self,key):
  4013. path = self._GetPath(key)
  4014. if not path.startswith(self._root_directory):
  4015. raise _FileCacheError('%s does not appear to live under %s' %
  4016. (path, self._root_directory ))
  4017. if os.path.exists(path):
  4018. os.remove(path)
  4019. def GetCachedTime(self,key):
  4020. path = self._GetPath(key)
  4021. if os.path.exists(path):
  4022. return os.path.getmtime(path)
  4023. else:
  4024. return None
  4025. def _GetUsername(self):
  4026. '''Attempt to find the username in a cross-platform fashion.'''
  4027. try:
  4028. return os.getenv('USER') or \
  4029. os.getenv('LOGNAME') or \
  4030. os.getenv('USERNAME') or \
  4031. os.getlogin() or \
  4032. 'nobody'
  4033. except (AttributeError, IOError, OSError), e:
  4034. return 'nobody'
  4035. def _GetTmpCachePath(self):
  4036. username = self._GetUsername()
  4037. cache_directory = 'python.cache_' + username
  4038. return os.path.join(tempfile.gettempdir(), cache_directory)
  4039. def _InitializeRootDirectory(self, root_directory):
  4040. if not root_directory:
  4041. root_directory = self._GetTmpCachePath()
  4042. root_directory = os.path.abspath(root_directory)
  4043. if not os.path.exists(root_directory):
  4044. os.mkdir(root_directory)
  4045. if not os.path.isdir(root_directory):
  4046. raise _FileCacheError('%s exists but is not a directory' %
  4047. root_directory)
  4048. self._root_directory = root_directory
  4049. def _GetPath(self,key):
  4050. try:
  4051. hashed_key = md5(key).hexdigest()
  4052. except TypeError:
  4053. hashed_key = md5.new(key).hexdigest()
  4054. return os.path.join(self._root_directory,
  4055. self._GetPrefix(hashed_key),
  4056. hashed_key)
  4057. def _GetPrefix(self,hashed_key):
  4058. return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])