
    gb
                       d Z ddlmZ ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZmZ ddlZddlZddlmZ ddlZ	 ddlmZmZmZmZ ddlmZ ddlmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1 ejd                  dkD  re3Z4dZ5 e6       Z7 e
jp                  e9      Z: G d de6      Z;y# e$ r dd	lmZmZ dd
lmZmZ ddlmZ Y w xY w)z=A library that provides a Python interface to the Twitter API    )division)print_functionN)OAuth1OAuth2)uuid4)urlparse
urlunparse	urlencode
quote_plus)__version__)r   r	   )r
   r   )	r   
_FileCacheCategoryDirectMessageListStatusTrendUser
UserStatus)	RateLimit)calc_expected_status_lengthis_urlparse_media_fileenf_typeparse_arg_list)TwitterError"PythonTwitterDeprecationWarning330)   i  c                      e Zd ZdZdZdZdddddddeddddddddddfdZed	        Z		 	 	 dd
Z
d ZddZd Z	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 ddZddZddZd Zd Z	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 ddZ	 	 	 ddZ	 	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 ddZ	 ddZ	 	 ddZd Zd Z	 	 dd Z e!fd!Z"	 dd"Z#dd#Z$	 	 	 	 dd$Z%	 	 	 	 dd%Z&	 	 dd&Z'	 	 	 dd'Z(	 	 	 	 	 	 dd(Z)	 	 	 	 dd)Z*	 	 dd*Z+	 	 	 dd+Z,	 dd,Z-	 	 dd-Z.	 	 dd.Z/	 	 	 dd/Z0	 dd0Z1	 	 dd1Z2	 	 	 	 dd2Z3	 	 	 	 dd3Z4	 	 	 	 dd4Z5	 	 	 	 dd5Z6	 	 	 	 dd6Z7d7 Z8	 	 	 	 	 dd8Z9	 	 	 	 	 dd9Z:	 	 	 	 	 	 	 dd:Z;	 	 	 	 	 	 dd;Z<	 	 	 	 	 	 dd<Z=	 	 	 	 	 	 	 dd=Z>	 	 	 	 	 	 dd>Z?	 	 	 	 	 	 dd?Z@	 	 	 	 	 	 	 	 dd@ZA	 	 	 	 	 	 	 ddAZB	 	 	 	 	 	 	 ddBZC	 	 	 	 	 ddCZD	 	 	 	 ddDZE	 	 	 	 	 	 	 	 ddEZF	 	 	 	 	 	 ddFZG	 	 	 ddGZHddHZIddIZJ	 	 	 	 	 ddJZK	 	 	 	 ddKZLddLZM	 	 	 	 ddMZN	 	 	 ddNZO	 	 ddOZP	 	 ddPZQ	 	 	 ddQZR	 	 	 ddRZS	 	 	 	 	 	 	 ddSZT	 	 	 	 	 	 	 ddTZUedU        ZVddVZW	 	 	 	 ddWZX	 	 	 	 ddXZY	 	 	 	 ddYZZ	 	 	 	 	 	 	 	 	 ddZZ[	 	 	 	 	 dd[Z\	 	 	 	 	 	 dd\Z]	 	 	 	 dd]Z^	 	 	 	 	 	 	 	 	 	 dd^Z_	 	 	 	 	 	 	 	 dd_Z`	 	 	 	 	 	 dd`Za	 	 	 	 	 	 ddaZb	 	 	 	 	 	 ddbZc	 	 	 	 ddcZd	 	 dddZe	 	 	 	 	 	 	 ddeZf	 	 ddfZg	 	 ddgZhddhZi	 	 	 	 	 	 	 ddiZj	 	 	 	 	 	 	 	 	 	 ddjZkddkZldl Zmdm Zndn Zodo Zpdp Zqdq Zrdr Zsds ZtddtZudu Zvdv Zwdw Zxedx        Zyedy        Zzdz Z{ed{        Z|d| Z}dd}Z~dd~Zy)Apia  A python interface into the Twitter API

    By default, the Api caches results for 1 minute.

    Example usage:

      To create an instance of the twitter.Api class, with no authentication:

        >>> import twitter
        >>> api = twitter.Api()

      To fetch a single user's public status messages, where "user" is either
      a Twitter "short name" or their user id.

        >>> statuses = api.GetUserTimeline(user)
        >>> print([s.text for s in statuses])

      To use authentication, instantiate the twitter.Api class with a
      consumer key and secret; and the oAuth key and secret:

        >>> api = twitter.Api(consumer_key='twitter consumer key',
                              consumer_secret='twitter consumer secret',
                              access_token_key='the_key_given',
                              access_token_secret='the_key_secret')

      To fetch your friends (after being authenticated):

        >>> users = api.GetFriends()
        >>> print([u.name for u in users])

      To post a twitter status message (after being authenticated):

        >>> status = api.PostUpdate('I love python-twitter!')
        >>> print(status.text)
        I love python-twitter!

      There are many other methods, including:

        >>> api.PostUpdates(status)
        >>> api.PostDirectMessage(user, text)
        >>> api.GetUser(user)
        >>> api.GetReplies()
        >>> api.GetUserTimeline(user)
        >>> api.GetHomeTimeline()
        >>> api.GetStatus(status_id)
        >>> api.GetStatuses(status_ids)
        >>> api.DestroyStatus(status_id)
        >>> api.GetFriends(user)
        >>> api.GetFollowers()
        >>> api.GetFeatured()
        >>> api.GetDirectMessages()
        >>> api.GetSentDirectMessages()
        >>> api.PostDirectMessage(user, text)
        >>> api.DestroyDirectMessage(message_id)
        >>> api.DestroyFriendship(user)
        >>> api.CreateFriendship(user)
        >>> api.LookupFriendship(user)
        >>> api.VerifyCredentials()
    <   zTwitter APINFi   compatc                    t         j                  rJdt         j                  j                         v r*ddl}|j                  j
                  j                          d}| j                  |       t        j                  | _
        || _        || _        || _        d| _        |r|dk  rt        j                   d       || _        d| _        | j'                  |       | j)                          | j+                          t-               | _        || _        || _        || _        |	d| _        n|	| _        |
d| _        n|
| _        |d	| _        n|| _        || _        | j<                  d
k  rt        j                   d       |r|st?        ||g      stA        ddi      | jC                  |||||       |r	 ddl"m#} d|jL                  _'        tQ        jR                          tQ        jT                         jW                  tP        jX                         tQ        jT                  d      }|jW                  tP        jX                         d|_-        t]        j^                         | _0        y# tH        $ r ddl%}Y w xY w)a
  Instantiate a new twitter.Api object.

        Args:
          consumer_key (str):
            Your Twitter user's consumer_key.
          consumer_secret (str):
            Your Twitter user's consumer_secret.
          access_token_key (str):
            The oAuth access token key value you retrieved
            from running get_access_token.py.
          access_token_secret (str):
            The oAuth access token's secret, also retrieved
            from the get_access_token.py run.
          application_only_auth:
             Use Application-Only Auth instead of User Auth.
             Defaults to False [Optional]
          input_encoding (str, optional):
            The encoding used to encode input strings.
          request_header (dict, optional):
            A dictionary of additional HTTP request headers.
          cache (object, optional):
            The cache instance to use. Defaults to DEFAULT_CACHE.
            Use None to disable caching.
          base_url (str, optional):
            The base URL to use to contact the Twitter API.
            Defaults to https://api.twitter.com.
          stream_url (str, optional):
            The base URL to use for streaming endpoints.
            Defaults to 'https://stream.twitter.com/1.1'.
          upload_url (str, optional):
            The base URL to use for uploads. Defaults to 'https://upload.twitter.com/1.1'.
          chunk_size (int, optional):
            Chunk size to use for chunked (multi-part) uploads of images/videos/gifs.
            Defaults to 1MB. Anything under 16KB and you run the risk of erroring out
            on 15MB files.
          use_gzip_compression (bool, optional):
            Set to True to tell enable gzip compression for any call
            made to Twitter.  Defaults to False.
          debugHTTP (bool, optional):
            Set to True to enable debug output from urllib2 when performing
            any HTTP requests.  Defaults to False.
          timeout (int, optional):
            Set timeout (in seconds) of the http/https requests. If None the
            requests lib default will be used.  Defaults to None.
          sleep_on_rate_limit (bool, optional):
            Whether to sleep an appropriate amount of time if a rate limit is hit for
            an endpoint.
          tweet_mode (str, optional):
            Whether to use the new (as of Sept. 2016) extended tweet mode. See docs for
            details. Choices are ['compatibility', 'extended'].
          proxies (dict, optional):
            A dictionary of proxies for the request to pass through, if not specified
            allows requests lib to use environmental variables for proxy if any.
        APPENGINE_RUNTIMEr   N      zVWarning: The Twitter streaming API sends 30s keepalives, the given timeout is shorter!zhttps://api.twitter.com/1.1zhttps://stream.twitter.com/1.1zhttps://upload.twitter.com/1.1i @  zA chunk size lower than 16384 may result in too many requests to the Twitter API when uploading videos. You are strongly advised to increase it above 16384messagez*Missing oAuth Consumer Key or Access Token   zrequests.packages.urllib3T)1osenvironkeys$requests_toolbelt.adapters.appengineadapters	appenginemonkeypatchSetCacher   DEFAULT_CACHE_TIMEOUT_cache_timeout_input_encoding	_use_gzip
_debugHTTP_shortlink_sizewarningswarn_timeout
_Api__auth_InitializeRequestHeaders_InitializeUserAgent_InitializeDefaultParametersr   
rate_limitsleep_on_rate_limit
tweet_modeproxiesbase_url
stream_url
upload_url
chunk_sizeallr   SetCredentialshttp.clientclientImportErrorhttplibHTTPConnection
debuglevelloggingbasicConfig	getLoggersetLevelDEBUG	propagaterequestsSession_session)selfconsumer_keyconsumer_secretaccess_token_keyaccess_token_secretapplication_only_authinput_encodingrequest_headerscacherA   rB   rC   rD   use_gzip_compression	debugHTTPtimeoutr>   r?   r@   requests_toolbelthttp_clientrequests_logs                          /opt/Tautulli/lib/twitter/api.py__init__zApi.__init__   s   X ::"bjjoo&77;!**44@@Be!77--#!w|MMrs&&7!!#))+#+#6 $9DM$DM>DO(DO>DO(DO$??Y&MM>@
 !S*:<O)P%Q	+WXYYL/;KM`1	3 .1 56K&&1!((7",,-HIL!!'--0%)L" ((*  .-.s   0I! !I10I1c                 4   t        |       }t        |      }t        j                  dj                  ||      j	                  d            }dj                  |j                  d            dd}t        j                  dddi|	      }|j                         }|S )
zO
        Generate a Bearer Token from consumer_key and consumer_secret
        z{}:{}utf8z	Basic {0}z/application/x-www-form-urlencoded;charset=UTF-8)AuthorizationContent-Typez$https://api.twitter.com/oauth2/token
grant_typeclient_credentials)urldataheaders)	r   base64	b64encodeformatencodedecoderS   postjson)rW   rX   keysecretbearer_tokenpost_headersresbearer_credss           re   GetAppOnlyAuthTokenzApi.GetAppOnlyAuthToken)  s    
 &O,''sF(C(J(J6(RS )//0C0CF0KLM

 mm F".0D!E$02 xxz    c                 
   || _         || _        || _        || _        |r:| j	                  ||      | _        t        | j
                        | _        d| _
        y||||g}t        |      rt        ||||      | _        d| _
        y)ao  Set the consumer_key and consumer_secret for this instance

        Args:
          consumer_key:
            The consumer_key of the twitter account.
          consumer_secret:
            The consumer_secret for the twitter account.
          access_token_key:
            The oAuth access token key value you retrieved
            from running get_access_token.py.
          access_token_secret:
            The oAuth access token's secret, also retrieved
            from the get_access_token.py run.
          application_only_auth:
            Whether to generate a bearer token and use Application-Only Auth
        )tokenN)_consumer_key_consumer_secret_access_token_key_access_token_secretr}   _bearer_tokenr   r9   rE   r   _config)rV   rW   rX   rY   rZ   r[   	auth_lists          re   rF   zApi.SetCredentials=  s    , * /!1$7! !%!9!9,!XD t'9'9:DK  &)+>@I9~$\?%57JL r~   c                     | j                   Rd| j                  z  }| j                  |d      }| j                  |j                  j                  d            }|| _         | j                   S )zGet basic help configuration details from Twitter.

        Args:
            None

        Returns:
            dict: Sets self._config and returns dict of help config values.
        z%s/help/configuration.jsonGETutf-8)r   rA   _RequestUrl_ParseAndCheckTwittercontentrt   )rV   rm   resprn   s       re   GetHelpConfigurationzApi.GetHelpConfigurationd  s^     <<.>C##C/D--dll.A.A'.JKDDL||r~   c                 :    | j                         }|r|d   S |d   S )ag  Returns number of characters reserved per URL included in a tweet.

        Args:
            https (bool, optional):
                If True, return number of characters reserved for https urls
                or, if False, return number of character reserved for http urls.
        Returns:
            (int): Number of characters reserved per URL.
        short_url_length_httpsshort_url_length)r   )rV   httpsconfigs      re   GetShortUrlLengthzApi.GetShortUrlLengtht  s-     **,233,--r~   c                 X    d| _         d| _        d| _        d| _        d| _        d| _        y)z0Clear any credentials for this instance
        N)r   r   r   r   r   r9   rV   s    re   ClearCredentialszApi.ClearCredentials  s3     " $!%$(!!r~   c                    d| j                   z  }i }|rt        dt        |      |d<   |rt        dt        |      |d<   |rt        dt        |      |d<   |rt        dt        |      |d<   |	rt        dt        |	      |d<   |
rt        dt        |
      |d<   |||g S |||d<   |`t	        |t
              st	        |t              r,d	j                  |D cg c]  }t        |       c}      |d
<   nt        d
t        |      |d
<   |rt        dt        |      |d<   t        dt        |      |d<   |dv r||d<   |&dj                  ||      }| j                  |d      }n| j                  |d|      }| j                  |j                  j                  d            }|r|S |j                  dd      D cg c]  }t        j                   |       c}S c c}w c c}w )aO  Return twitter search results for a given term. You must specify one
        of term, geocode, or raw_query.

        Args:
          term (str, optional):
            Term to search by. Optional if you include geocode.
          raw_query (str, optional):
            A raw query as a string. This should be everything after the "?" in
            the URL (i.e., the query parameters). You are responsible for all
            type checking and ensuring that the query string is properly
            formatted, as it will only be URL-encoded before be passed directly
            to Twitter with no other checks performed. For advanced usage only.
            *This will override any other parameters passed*
          since_id (int, optional):
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occurred since the since_id, the since_id will be
            forced to the oldest ID available.
          max_id (int, optional):
            Returns only statuses with an ID less than (that is, older
            than) or equal to the specified ID.
          until (str, optional):
            Returns tweets generated before the given date. Date should be
            formatted as YYYY-MM-DD.
          since (str, optional):
            Returns tweets generated since the given date. Date should be
            formatted as YYYY-MM-DD.
          geocode (str or list or tuple, optional):
            Geolocation within which to search for tweets. Can be either a
            string in the form of "latitude,longitude,radius" where latitude
            and longitude are floats and radius is a string such as "1mi" or
            "1km" ("mi" or "km" are the only units allowed). For example:
              >>> api.GetSearch(geocode="37.781157,-122.398720,1mi").
            Otherwise, you can pass a list of either floats or strings for
            lat/long and a string for radius:
              >>> api.GetSearch(geocode=[37.781157, -122.398720, "1mi"])
              >>> # or:
              >>> api.GetSearch(geocode=(37.781157, -122.398720, "1mi"))
              >>> # or:
              >>> api.GetSearch(geocode=("37.781157", "-122.398720", "1mi"))
          count (int, optional):
            Number of results to return.  Default is 15 and maxmimum that
            Twitter returns is 100 irrespective of what you type in.
          lang (str, optional):
            Language for results as ISO 639-1 code.  Default is None
            (all languages).
          locale (str, optional):
            Language of the search query. Currently only 'ja' is effective.
            This is intended for language-specific consumers and the default
            should work in the majority of cases.
          result_type (str, optional):
            Type of result which should be returned. Default is "mixed".
            Valid options are "mixed, "recent", and "popular".
          include_entities (bool, optional):
            If True, each tweet will include a node called "entities".
            This node offers a variety of metadata about the tweet in a
            discrete structure, including: user_mentions, urls, and
            hashtags.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.Userret
        Returns:
          list: A sequence of twitter.Status instances, one for each message
          containing the term, within the bounds of the geocoded area, or
          given by the raw_query.
        z%s/search/tweets.jsonsince_idmax_iduntilsincelanglocaleq,geocodeinclude_entitiescount)mixedpopularrecentresult_typez{url}?{raw_query})rm   	raw_queryr   rn   r   statuses )rA   r   intstr
isinstancelisttuplejoinboolrr   r   r   r   rt   getr   NewFromJsonDict)rV   termr   r   r   r   r   r   r   r   r   r   r   return_jsonrm   
parametersgeor   rn   xs                       re   	GetSearchzApi.GetSearch  s   b &5
%-j#x%HJz"#+Hc6#BJx "*7C"?Jw"*7C"?Jw!)&#t!<Jv#+Hc6#BJx <GO	0AI"JsO'4(Jw,F(+g1Ns#c(1N(O
9%(0C(I
9%-56H6:6F.HJ)* 'wU;
788(3J}% %,,# - %C ##C/D##CZ#@D))$,,*=*=g*FGK7;xx
B7OP!F**1-PP5 2O4 Qs   G8Gc                 r   i }|||d<   |dk7  r||d<   |rd|d<   	 t        |      |d<   d| j                  z  }| j	                  |d	|
      }| j                  |j                  j                  d            }|D 	cg c]  }	t        j                  |	       c}	S # t        $ r t        ddi      w xY wc c}	w )a  Return twitter user search results for a given term.

        Args:
          term:
            Term to search by.
          page:
            Page of results to return. Default is 1
            [Optional]
          count:
            Number of results to return.  Default is 20
            [Optional]
          include_entities:
            If True, each tweet will include a node called "entities,".
            This node offers a variety of metadata about the tweet in a
            discrete structure, including: user_mentions, urls, and hashtags.
            [Optional]

        Returns:
          A sequence of twitter.User instances, one for each message containing
          the term
        r   r'   pager   r   r&   count must be an integerz%s/users/search.jsonr   r   r   )
r   
ValueErrorr   rA   r   r   r   rt   r   r   )
rV   r   r   r   r   r   rm   r   rn   r   s
             re   GetUsersSearchzApi.GetUsersSearch  s    6 
"JsO19!%Jv-.J)*	H"%e*Jw
 %t}}4U<))$,,*=*=g*FG156A$$Q'66  	H	+EFGG	H 7s   B ;B4B1c                 (    | j                  d|      S )a/  Get the current top trending topics (global)

        Args:
          exclude:
            Appends the exclude parameter as a request parameter.
            Currently only exclude=hashtags is supported. [Optional]

        Returns:
          A list with 10 entries. Each entry contains a trend.
        r'   )woeidexclude)GetTrendsWoeid)rV   r   s     re   GetTrendsCurrentzApi.GetTrendsCurrentI  s     ""G"<<r~   c                 0   d| j                   z  }d|i}|r||d<   | j                  |d|      }| j                  |j                  j	                  d            }g }|d   d   }|d   d	   D ](  }	|j                  t        j                  |	|
             * |S )a  Return the top 10 trending topics for a specific WOEID, if trending
        information is available for it.

        Args:
          woeid:
            the Yahoo! Where On Earth ID for a location.
          exclude:
            Appends the exclude parameter as a request parameter.
            Currently only exclude=hashtags is supported. [Optional]

        Returns:
          A list with 10 entries. Each entry contains a trend.
        z%s/trends/place.jsonidr   r   )verbrn   r   r   as_oftrends)	timestamp)rA   r   r   r   rt   appendr   r   )
rV   r   r   rm   r   r   rn   r   r   trends
             re   r   zApi.GetTrendsWoeidV  s     %6E]
$+Jy!%jA))$,,*=*=g*FGGG$	!WX& 	MEMM%//KL	Mr~   c                     d| j                   z  }| j                  |d      }| j                  |j                  j	                  d            }g }|D ]&  }|j                  t        j                  |             ( |S )z Return the list of suggested user categories, this can be used in
            GetUserSuggestion function
        Returns:
            A list of categories
        z%s/users/suggestions.jsonr   r   r   )rA   r   r   r   rt   r   r   r   )rV   rm   r   rn   
categoriescategorys         re   GetUserSuggestionCategorieszApi.GetUserSuggestionCategoriess  s{     *T]];%0))$,,*=*=g*FG
 	BHh66x@A	Br~   c                    | j                   d|j                  d}| j                  |d      }| j                  |j                  j                  d            }g }|d   D ]&  }|j                  t        j                  |             ( |S )z Returns a list of users in a category
        Args:
            category:
                The Category object to limit the search by
        Returns:
            A list of users in that category
        z/users/suggestions/.jsonr   r   r   users)	rA   slugr   r   r   rt   r   r   r   )rV   r   rm   r   rn   r   users          re   GetUserSuggestionzApi.GetUserSuggestion  s~     15x}}M%0))$,,*=*=g*FGM 	5DLL--d34	5r~   c                 P   d| j                   z  }i }	|"	 t        |      dkD  rt        ddi      	 ||	d<   |r	 t        |      |	d<   |r	 t        |      |	d	<   |rd|	d<   |rd|	d<   |rd|	d<   |sd|	d<   | j	                  |d|	      }
| j                  |
j                  j                  d            }|D cg c]  }t        j                  |       c}S # t        $ r t        ddi      w xY w# t        $ r t        ddi      w xY w# t        $ r t        dd
i      w xY wc c}w )aH  Fetch a collection of the most recent Tweets and retweets posted
        by the authenticating user and the users they follow.

        The home timeline is central to how most users interact with Twitter.

        Args:
          count:
            Specifies the number of statuses to retrieve. May not be
            greater than 200. Defaults to 20. [Optional]
          since_id:
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occurred since the since_id, the since_id will be
            forced to the oldest ID available. [Optional]
          max_id:
            Returns results with an ID less than (that is, older than) or
            equal to the specified ID. [Optional]
          trim_user:
            When True, each tweet returned in a timeline will include a user
            object including only the status authors numerical ID. Omit this
            parameter to receive the complete user object. [Optional]
          exclude_replies:
            This parameter will prevent replies from appearing in the
            returned timeline. Using exclude_replies with the count
            parameter will mean you will receive up-to count tweets -
            this is because the count parameter retrieves that many
            tweets before filtering out retweets and replies. [Optional]
          contributor_details:
            This parameter enhances the contributors element of the
            status response to include the screen_name of the contributor.
            By default only the user_id of the contributor is included. [Optional]
          include_entities:
            The entities node will be disincluded when set to false.
            This node offers a variety of metadata about the tweet in a
            discreet structure, including: user_mentions, urls, and
            hashtags. [Optional]

        Returns:
          A sequence of twitter.Status instances, one for each message
        z%s/statuses/home_timeline.json   r&   z#'count' may not be greater than 200'count' must be an integerr   r   z'since_id' must be an integerr   z'max_id' must be an integerr'   	trim_userexclude_repliescontributor_detailsfalser   r   r   r   )
rA   r   r   r   r   r   r   rt   r   r   )rV   r   r   r   r   r   r   r   rm   r   r   rn   r   s                re   GetHomeTimelinezApi.GetHomeTimeline  s{   b />
Nu:#&	3X'YZZ $ #(JwQ),X
:& O'*6{
8$ &'J{#,-J()01J,--4J)*U<))$,,*=*=g*FG378a&&q)881  N"I/K#LMMN  Q"I/N#OPPQ
  O"I/L#MNNO 9s(   C C/ 
D	 6D#C,/D	D c	                 (   d| j                   z  }	i }
|rt        dt        |      |
d<   n|r||
d<   |rt        dt        |      |
d<   |rt        dt        |      |
d<   |rt        dt        |      |
d<   t        dt        |      |
d<   t        dt        |      |
d<   t        d	t        |      |
d	<   | j	                  |	d
|
      }| j                  |j                  j                  d            }|D cg c]  }t        j                  |       c}S c c}w )as  Fetch the sequence of public Status messages for a single user.

        The twitter.Api instance must be authenticated if the user is private.

        Args:
          user_id (int, optional):
            Specifies the ID of the user for whom to return the
            user_timeline. Helpful for disambiguating when a valid user ID
            is also a valid screen name.
          screen_name (str, optional):
            Specifies the screen name of the user for whom to return the
            user_timeline. Helpful for disambiguating when a valid screen
            name is also a user ID.
          since_id (int, optional):
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occurred since the since_id, the since_id will be
            forced to the oldest ID available.
          max_id (int, optional):
            Returns only statuses with an ID less than (that is, older
            than) or equal to the specified ID.
          count (int, optional):
            Specifies the number of statuses to retrieve. May not be
            greater than 200.
          include_rts (bool, optional):
            If True, the timeline will contain native retweets (if they
            exist) in addition to the standard stream of tweets.
          trim_user (bool, optional):
            If True, statuses will only contain the numerical user ID only.
            Otherwise a full user object will be returned for each status.
          exclude_replies (bool, optional)
            If True, this will prevent replies from appearing in the returned
            timeline. Using exclude_replies with the count parameter will mean you
            will receive up-to count tweets - this is because the count parameter
            retrieves that many tweets before filtering out retweets and replies.
            This parameter is only supported for JSON and XML responses.

        Returns:
          A sequence of Status instances, one for each message up to count
        z%s/statuses/user_timeline.jsonuser_idscreen_namer   r   r   include_rtsr   r   r   r   r   
rA   r   r   r   r   r   r   rt   r   r   )rV   r   r   r   r   r   r   r   r   rm   r   r   rn   r   s                 re   GetUserTimelinezApi.GetUserTimeline  s   d /$--@
$,YW$EJy!(3J}%%-j#x%HJz"#+Hc6#BJx "*7C"?Jw$,]D+$N
=!"*;i"H
;(01BD/(Z
$%U<))$,,*=*=g*FG378a&&q)888s   0Dc           	      l   d| j                   z  }t        dt        |      t        dt        |      t        dt        |      t        dt        |      t        dt        |      d}| j	                  |d|	      }| j                  |j                  j                  d
            }	t        j                  |	      S )a1  Returns a single status message, specified by the status_id parameter.

        Args:
          status_id:
            The numeric ID of the status you are trying to retrieve.
          trim_user:
            When set to True, each tweet returned in a timeline will include
            a user object including only the status authors numerical ID.
            Omit this parameter to receive the complete user object. [Optional]
          include_my_retweet:
            When set to True, any Tweets returned that have been retweeted by
            the authenticating user will include an additional
            current_user_retweet node, containing the ID of the source status
            for the retweet. [Optional]
          include_entities:
            If False, the entities node will be disincluded.
            This node offers a variety of metadata about the tweet in a
            discreet structure, including: user_mentions, urls, and
            hashtags. [Optional]
        Returns:
          A twitter.Status instance representing that status message
        z%s/statuses/show.json	status_idr   include_my_retweetr   include_ext_alt_text)r   r   r   r   r   r   r   r   r   )
rV   r   r   r   r   r   rm   r   r   rn   s
             re   	GetStatuszApi.GetStatus0  s    8 &7 ;Y7!+tY?"*+?GY"Z ();TCS T$,-CTK_$`

 U<))$,,*=*=g*FG%%d++r~   c                    d| j                   z  }t        dt        |      }|ri }ng }d}t        dt        |      t        dt        |      |d}|t        |      k  rdj	                  |||dz    D 	cg c]  }	t        t        d	t        |	             c}	      |d
<   | j                  |d|      }
| j                  |
j                  j                  d            }|rW|j                  |d
   j                         D ci c](  \  }}t        |      |rt        j                  |      nd* c}}       n&||D cg c]  }t        j                  |       c}z  }|dz  }|t        |      k  r|S c c}	w c c}}w c c}w )a  Returns a list of status messages, specified by the status_ids parameter.

        Args:
          status_ids:
            A list of the numeric ID of the statuses you are trying to retrieve.
          trim_user:
            When set to True, each tweet returned in a timeline will include
            a user object including only the status authors numerical ID.
            Omit this parameter to receive the complete user object. [Optional]
          include_entities:
            If False, the entities node will be disincluded.
            This node offers a variety of metadata about the tweet in a
            discreet structure, including: user_mentions, urls, and
            hashtags. [Optional]
          map:
            If True, returns a dictionary with status id as key and returned
            status data (or None if tweet does not exist or is inaccessible)
            as value. Otherwise returns an unordered list of successfully
            retrieved Tweets. [Optional]
        Returns:
          A dictionary or unordered list (depending on the parameter 'map') of
          twitter Status instances representing the status messages.
        z%s/statuses/lookup.jsonmapr   r   r   )r   r   r   r   d   r   r   r   r   r   N)rA   r   r   lenr   r   r   r   r   r   rt   updateitemsr   r   )rV   
status_idsr   r   r   rm   resultoffsetr   r   r   rn   rw   valuedataitems                  re   GetStatuseszApi.GetStatuses[  s   8 (4==9udC(FF!+tY? ();TCS T


 s:&"xxeopvw}  AD  xD  fE  )FXaXk3	-R)S  )F   GJt##CZ#@D--dll.A.A'.JKDnrswnxn~n~  oA  B`j`cejs3x5&*@*@*GVZZ  B  CDQ611(;QQcMF s:&  )F
 BQs   2!E1>-E6
9E<c
                 ,   d| j                   z  }
i }|	 t        |      |d<   n|||d<   nt        ddi      |||d<   |du rd	|d
<   |du rd	|d<   |du rd	|d<   ||dvrt        ddi      ||d<   |r"t	        |t
              st        ddi      ||d<   |	"t	        |	t
              st        ddi      |	|d<   | j                  |
d|d      }| j                  |j                  j                  d            }|S # t        $ r t        ddi      w xY w)a`  Returns information allowing the creation of an embedded representation of a
        Tweet on third party sites.

        Specify tweet by the id or url parameter.

        Args:
          status_id:
            The numeric ID of the status you are trying to embed.
          url:
            The url of the status you are trying to embed.
          maxwidth:
            The maximum width in pixels that the embed should be rendered at.
            This value is constrained to be between 250 and 550 pixels. [Optional]
          hide_media:
            Specifies whether the embedded Tweet should automatically expand images. [Optional]
          hide_thread:
            Specifies whether the embedded Tweet should automatically show the original
            message in the case that the embedded Tweet is a reply. [Optional]
          omit_script:
            Specifies whether the embedded Tweet HTML should include a <script>
            element pointing to widgets.js. [Optional]
          align:
            Specifies whether the embedded Tweet should be left aligned, right aligned,
            or centered in the page. [Optional]
          related:
            A comma sperated string of related screen names. [Optional]
          lang:
            Language code for the rendered embed. [Optional]

        Returns:
          A dictionary with the response.
        z%s/statuses/oembed.jsonr   r&   z'status_id' must be an integer.rm   z(Must specify either 'status_id' or 'url'maxwidthTtrue
hide_mediahide_threadomit_script)leftcenterrightnonez4'align' must be 'left', 'center', 'right', or 'none'alignz<'related' should be a string of comma separated screen namesrelatedz 'lang' should be string instancer   r   F)rn   enforce_authr   )
rA   r   r   r   r   r   r   r   r   rt   )rV   r   rm   r   r   r   r   r  r  r   request_urlr   r   rn   s                 re   GetStatusOembedzApi.GetStatusOembed  sy   T 04==A
 S#&y>
4  _ #Ju	+UVWW%-Jz"'-J|$$(.J}%$(.J}%??"I/e#fgg"'Jwgs+"I/m#noo$+Jy!dC("I/Q#RSS!%JvURWX))$,,*=*=g*FG?  S"I/P#QRRSs   C< <Dc                    | j                   d|d}t        dt        |      t        dt        |      d}| j	                  |d|      }| j                  |j                  j                  d            }t        j                  |      S )	a%  Destroys the status specified by the required ID parameter.

        The authenticating user must be the author of the specified
        status.

        Args:
          status_id (int):
            The numerical ID of the status you're trying to destroy.
          trim_user (bool, optional):
            When set to True, each tweet returned in a timeline will include
            a user object including only the status authors numerical ID.

        Returns:
          A twitter.Status instance representing the destroyed status message
        z/statuses/destroy/r   r   r   )r   r   POSTr   r   r   )rV   r   r   rm   	post_datar   rn   s          re   DestroyStatuszApi.DestroyStatus  s|      04}}iH ;Y7!+tY?
	
 V)<))$,,*=*=g*FG%%d++r~   c                 d   d| j                   z  }t        |t              s| j                  |}nt        || j                        }|rt	        |      t
        kD  rt        d      |r|st        d      ||||
||dj                  |xs g D cg c]  }t        |       c}      d}|r||d<   |rg d}g }t        |t        t        f      r|j                  |       n*t        |t              r|D ]  }t        |t        t        f      r|j                  |       +t        |      \  }}}}|dk(  s|d	k(  rt        |      d
kD  rt        d      || j                  kD  s||v r| j                  |||      }n| j!                  |||      }|j                  |        njt        |      \  }}}}|| j                  kD  s||v r$|j                  | j                  |||             n#|j                  | j!                  |||             dj                  |D cg c]  }t        |       c}      |d<   ||	t        |      |d<   t        |	      |d<   | j#                  |d|      }| j%                  |j&                  j)                  d            }t+        j,                  |      S c c}w c c}w )a  Post a twitter status message from the authenticated user.

        https://dev.twitter.com/docs/api/1.1/post/statuses/update

        Args:
            status (str):
                The message text to be posted. Must be less than or equal to
                CHARACTER_LIMIT characters.
            media (int, str, fp, optional):
                A URL, a local file, or a file-like object (something with a
                read() method), or a list of any combination of the above.
            media_additional_owners (list, optional):
                A list of user ids representing Twitter users that should be able
                to use the uploaded media in their tweets. If you pass a list of
                media, then additional_owners will apply to each object. If you
                need more granular control, please use the UploadMedia* methods.
            media_category (str, optional):
                Only for use with the AdsAPI. See
                https://dev.twitter.com/ads/creative/promoted-video-overview if
                this applies to your application.
            in_reply_to_status_id (int, optional):
                The ID of an existing status that the status to be posted is
                in reply to.  This implicitly sets the in_reply_to_user_id
                attribute of the resulting status to the user ID of the
                message being replied to.  Invalid/missing status IDs will be
                ignored.
            auto_populate_reply_metadata (bool, optional):
                Automatically include the @usernames of the users mentioned or
                participating in the tweet to which this tweet is in reply.
            exclude_reply_user_ids (list, optional):
                Remove given user_ids (*not* @usernames) from the tweet's
                automatically generated reply metadata.
            attachment_url (str, optional):
                URL to an attachment resource: one to four photos, a GIF,
                video, Quote Tweet, or DM deep link. If not specified and
                media parameter is not None, we will attach the first media
                object as the attachment URL. If a bad URL is passed, Twitter
                will raise an error.
            latitude (float, optional):
                Latitude coordinate of the tweet in degrees. Will only work
                in conjunction with longitude argument. Both longitude and
                latitude will be ignored by twitter if the user has a false
                geo_enabled setting.
            longitude (float, optional):
                Longitude coordinate of the tweet in degrees. Will only work
                in conjunction with latitude argument. Both longitude and
                latitude will be ignored by twitter if the user has a false
                geo_enabled setting.
            place_id (int, optional):
                A place in the world. These IDs can be retrieved from
                GET geo/reverse_geocode.
            display_coordinates (bool, optional):
                Whether or not to put a pin on the exact coordinates a tweet
                has been sent from.
            trim_user (bool, optional):
                If True the returned payload will only contain the user IDs,
                otherwise the payload will contain the full user data item.
            verify_status_length (bool, optional):
                If True, api throws a hard error that the status is over
                CHARACTER_LIMIT characters. If False, Api will attempt to post
                the status.
        Returns:
            (twitter.Status) A twitter.Status instance representing the
            message posted.
        z%s/statuses/update.jsonz>Text must be less than or equal to CHARACTER_LIMIT characters.zKIf auto_populate_reply_metadata is True, you must set in_reply_to_status_idr   )statusin_reply_to_status_idauto_populate_reply_metadataplace_iddisplay_coordinatesr   exclude_reply_user_idsattachment_url)	video/mp4zvideo/quicktime	image/gifr  r  r'   z>You cannot post more than 1 GIF or 1 video in a single status.mediaadditional_ownersmedia_category)r  	media_idslatlongr  r   r   )rA   r   r   r2   r   CHARACTER_LIMITr   r   r   r  r   r   r   r   rD   UploadMediaChunkedUploadMediaSimpler   r   r   rt   r   r   )rV   r  r  media_additional_ownersr  r  r  r  latitude	longituder  r  r   verify_status_lengthr  rm   u_statusur   chunked_typesr  
media_file_	file_size
media_typemedia_idmidr   rn   s                                re   
PostUpdatezApi.PostUpdate  s   ` ($--7fc"d&:&:&BH64#7#78H$?$IO$[_``'0Elmm %:,H #6"&)hh@V@\Z\/]1A/]&^

 +9J'(IMI%#t-  'E4("' /J "*sDk:!((4 2B:2N/Aq)Z"k1Z;5NTWX]T^abTb*\^ ^ 4??2jM6Q#'#:#:",.E+9 $; $;
 $(#9#9",.E+9 $: $; $$X.+/. /?u.E+1it.*2M$$T%<%<6~ &= &  $$T%;%;6~ &< &  '*hhI/NSC/N&OJ{#I$9 #HJu!$YJvV*=))$,,*=*=g*FG%%d++m 0^Z 0Os   J(J-c                 |   d| j                   z  }i }t        |      \  }}}}|j                         |d<   |rt        |      dkD  rt	        ddi      |r||d<   |r||d<   | j                  |d|	      }| j                  |j                  j                  d
            }		 |	d   S # t        $ r t	        ddi      w xY w)a   Upload a media file to Twitter in one request. Used for small file
        uploads that do not require chunked uploads.

        Args:
            media:
                File-like object to upload.
            additional_owners: additional Twitter users that are allowed to use
                The uploaded media. Should be a list of integers. Maximum
                number of additional owners is capped at 100 by Twitter.
            media_category:
                Category with which to identify media upload. Only use with Ads
                API & video files.

        Returns:
            media_id:
                ID of the uploaded media returned by the Twitter API or 0.

        %s/media/upload.jsonr  r   r&   DMaximum of 100 additional owners may be specified for a Media objectr  r  r  r   r   r*  Media could not be uploaded.)
rC   r   readr   r   r   r   r   rt   KeyError)
rV   r  r  r  rm   r   media_fpr'  r   rn   s
             re   r  zApi.UploadMediaSimple  s    . %t6
,U3!Q&mmo
7%6!7#!=	+qrss.?J*++9J'(V*=))$,,*=*=g*FG	L
## 	L	+IJKK	Ls   B$ $B;c                 l    d| j                   z  }i }||d<   |rd|i|d<   | j                  |d|      }|S )zProvide addtional data for uploaded media.

        Args:
            media_id:
                ID of a previously uploaded media item.
            alt_text:
                Image Alternate Text.
        z%s/media/metadata/create.jsonr*  textalt_textr  rv   )rC   r   )rV   r*  r6  rm   r   r   s         re   PostMediaMetadatazApi.PostMediaMetadata  sO     .?
!)
:&,h%7Jz"V*=r~   c                    d| j                   z  }t        |d      \  }}}}t        ||||g      st        ddi      i }	|rt	        |      dkD  rt        ddi      |r||	d<   |r||	d	<   d
|	d<   ||	d<   ||	d<   | j                  |d|	      }
| j                  |
j                  j                  d            }	 |d   }|||fS # t        $ r t        ddi      w xY w)a  Start a chunked upload to Twitter.

        Args:
            media:
                File-like object to upload.
            additional_owners: additional Twitter users that are allowed to use
                The uploaded media. Should be a list of integers. Maximum
                number of additional owners is capped at 100 by Twitter.
            media_category:
                Category with which to identify media upload. Only use with Ads
                API & video files.

        Returns:
            tuple: media_id (returned from Twitter), file-handler object (i.e., has .read()
            method), filename media file.
        r.  T)async_uploadr&   zCould not process media filer   r/  r  r  INITcommandr)  total_bytesr  r   r   r*  zMedia could not be uploaded)
rC   r   rE   r   r   r   r   r   rt   r2  )rV   r  r  r  rm   r3  filenamer(  r)  r   r   rn   r*  s                re   _UploadMediaChunkedInitzApi._UploadMediaChunkedInit  s%   ( %t64DUY]4^1(IzHh	:>?	+IJKK
%6!7#!=	+qrss.?J*++9J'( !'
9#-
< $-
=!V*=))$,,*=*=g*FG	KJ'H (H--  	K	+HIJJ	Ks   9C Cc                 \   d| j                   z  }dj                  t               j                        j	                  d      }t        |      j	                  d      }ddj                  |j                  d      dd       i}d	}	 	 |j                  | j                        }	|	sn|ddd|dd||ddt        |      j	                  d      |dj                  |      j	                  d      dd|	|dz   g}
dj                  |
      }t        t        |            |d<   | j                  |||      }|j                  j                  d      r*| j                  |j                  j                  d            S |dz  }	 |j                          y
# t        $ r Y w xY w# t         $ r
}Y d}~y
d}~ww xY w)a  Appends (i.e., actually uploads) media file to Twitter.

        Args:
            media_id (int):
                ID of the media file received from Init method.
            media_fp (file):
                File-like object representing media file (must have .read() method)
            filename (str):
                Filename of the media file being uploaded.

        Returns:
            True if successful. Raises otherwise.
        r.  z--{0}r   rj   z!multipart/form-data; boundary={0}rh      Nr   Ts.   Content-Disposition: form-data; name="command"r~   s   APPENDs/   Content-Disposition: form-data; name="media_id"s4   Content-Disposition: form-data; name="segment_index"z>Content-Disposition: form-data; name="media"; filename="{0!r}"s&   Content-Type: application/octet-streams   --s   
zContent-Length)rm   ro   rn   r'   )rC   rr   r   hexrs   r   rt   r1  rD   r   r   r   _RequestChunkedUploadr   r   close	Exception)rV   r*  r3  r>  rm   boundarymedia_id_bytesro   
segment_idrn   body	body_datar   es                 re   _UploadMediaChunkedAppendzApi._UploadMediaChunkedAppend  s   " %t6>>%'++.55g>X--g6!#F#M#MOOF#AB'$
  
}}T__5 ABGJ&&w/PWWX`ahhiop95 %D(  T*I(+C	N(;G$%--#6=3< . >D ||""7+11$,,2E2Eg2NOO!OJQ T	NN Y  R  		s$   F	 8F 		FF	F+&F+c                     d| j                   z  }d|d}| j                  |d|      }| j                  |j                  j	                  d            }|S )zFinalize chunked upload to Twitter.

        Args:
            media_id (int):
                ID of the media file for which to finalize the upload.

        Returns:
            json: JSON string of data from Twitter.
        r.  FINALIZE)r<  r*  r  r   r   )rC   r   r   r   rt   )rV   r*  rm   r   r   rn   s         re   _UploadMediaChunkedFinalizezApi._UploadMediaChunkedFinalize`  s^     %t6 " 


 V*=))$,,*=*=g*FGr~   c                     | j                  |||      \  }}}| j                  |||      }|st        d       | j                  |      }	 |d   S # t        $ r t        d      w xY w)a  Upload a media file to Twitter in multiple requests.

        Args:
            media:
                File-like object to upload.
            additional_owners: additional Twitter users that are allowed to use
                The uploaded media. Should be a list of integers. Maximum
                number of additional owners is capped at 100 by Twitter.
            media_category:
                Category with which to identify media upload. Only use with Ads
                API & video files.

        Returns:
            media_id:
                ID of the uploaded media returned by the Twitter API. Raises if
                unsuccesful.
        r  )r*  r3  r>  r0  r*  )r?  rL  r   rO  r2  )	rV   r  r  r  r*  r3  r>  r   rn   s	            re   r  zApi.UploadMediaChunkedv  s    , (,'C'C%VgSa (D (c$(H //9A9A 0 C 78//9	?
## 	?=>>	?s   A A&c                    | j                   s| j                          g }g }d}t        j                  d|      }t	        |      dk(  r`t        |d         sRt	        |d         t        kD  r't        dj                  t	        |d         |            |j                  |d          |S |D ]  }t	        |      |kD  r$t        dj                  t	        |      |            |}t        |      r|| j                   d   z   dz   }n|t	        |      dz   z  }|t        kD  r)|j                  dj                  |             |g}||z
  }|j                  |       |} |j                  dj                  |             |S )Nr   z\sr'   z>Unable to split status into tweetable parts. Word was: {0}/{1}r    )r   r   resplitr   r   r  r   rr   r   r   )	rV   r  char_limtweetslineline_lengthwordswordnew_lens	            re   _TweetTextWrapzApi._TweetTextWrap  sx    ||%%''u:?6%(#358}."#c#j#jknotuvowkx  {C  $D  E  EeAh' 	&D4y8#"#c#j#jknosktv~#  A  A!Gd|%5M(NNQRR3t9q=((chhtn-v%3D!%!	&$ 	chhtn%r~   c           	         t               }|d}t        t        |      z
  }| j                  ||      }t        |      dk(  r(|j	                   | j
                  dd|d   i|       |S |dd D ](  }|j	                   | j
                  dd||z   i|       * |j	                   | j
                  dd|d   i|       |S )uI  Post one or more twitter status messages from the authenticated user.

        Unlike api.PostUpdate, this method will post multiple status updates
        if the message is longer than CHARACTER_LIMIT characters.

        Args:
          status:
            The message text to be posted.
            May be longer than CHARACTER_LIMIT characters.
          continuation:
            The character string, if any, to be appended to all but the
            last message.  Note that Twitter strips trailing '...' strings
            from messages.  Consider using the unicode … character
            (horizontal ellipsis) instead. [Defaults to None]
          **kwargs:
            See api.PostUpdate for a list of accepted parameters.

        Returns:
          A of list twitter.Status instance representing the messages posted.
        r   )r  rU  r'   r  r    )r   r  r   r\  r   r,  )rV   r  continuationkwargsresults
char_limitrV  tweets           re   PostUpdateszApi.PostUpdates  s    0 &L$s<'88
$$FZ$Hv;!NN?4??F&)FvFGNAb\ 	SENN?4??Q%,2FQ&QR	StCfRjCFCDr~   c                 P   	 t        |      dk  rt        ddi      	 | j                  d|d}d|i}|rd|d	<   | j	                  |d
|      }| j                  |j                  j                  d            }t        j                  |      S # t        $ r t        ddi      w xY w)a  Retweet a tweet with the Retweet API.

        Args:
          status_id:
            The numerical id of the tweet that will be retweeted
          trim_user:
            If True the returned payload will only contain the user IDs,
            otherwise the payload will contain the full user data item.
            [Optional]

        Returns:
          A twitter.Status instance representing the original tweet with retweet details embedded.
        r   r&   z%'status_id' must be a positive numberz'status_id' must be an integerz/statuses/retweet/r   r   r   r   r  r   r   )
r   r   r   rA   r   r   r   rt   r   r   )rV   r   r   rm   rn   r   s         re   PostRetweetzApi.PostRetweet  s    	N9~""I/V#WXX #
 04}}iHi  &DV$7))$,,*=*=g*FG%%d++  	N	+KLMM	Ns   B B%c                 0    | j                  ||||dd      S )a  Fetch the sequence of retweets made by the authenticated user.

        Args:
          count:
            The number of status messages to retrieve. [Optional]
          since_id:
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occurred since the since_id, the since_id will be
            forced to the oldest ID available. [Optional]
          max_id:
            Returns results with an ID less than (that is, older than) or
            equal to the specified ID. [Optional]
          trim_user:
            If True the returned payload will only contain the user IDs,
            otherwise the payload will contain the full user data item.
            [Optional]

        Returns:
          A sequence of twitter.Status instances, one for each message up to count
        Tr   r   r   r   r   r   r   )rV   r   r   r   r   s        re   GetUserRetweetszApi.GetUserRetweets  s.    6 ##  $  	r~   c                 0    | j                  ||||dd      S )a  Get a sequence of status messages representing the 20 most
        recent replies (status updates prefixed with @twitterID) to the
        authenticating user.

        Args:
          since_id:
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occurred since the since_id, the since_id will be
            forced to the oldest ID available. [Optional]
          max_id:
            Returns results with an ID less than (that is, older than) or
            equal to the specified ID. [Optional]
          trim_user:
            If True the returned payload will only contain the user IDs,
            otherwise the payload will contain the full user data item.
            [Optional]

        Returns:
          A sequence of twitter.Status instances, one for each reply to the user.
        Fri  rj  )rV   r   r   r   r   s        re   
GetReplieszApi.GetReplies0  s,    6 ##XU6]f49u $ N 	Nr~   c                 D   | j                   d|d}dt        dt        |      i}|rt        dt        |      |d<   | j	                  |d|      }| j                  |j                  j                  d            }|D cg c]  }t        j                  |       c}S c c}w )a=  Returns up to 100 of the first retweets of the tweet identified
        by statusid

        Args:
          statusid (int):
            The ID of the tweet for which retweets should be searched for
          count (int, optional):
            The number of status messages to retrieve.
          trim_user (bool, optional):
            If True the returned payload will only contain the user IDs,
            otherwise the payload will contain the full user data item.

        Returns:
          A list of twitter.Status instances, which are retweets of statusid
        z/statuses/retweets/r   r   r   r   r   r   )
rA   r   r   r   r   r   r   rt   r   r   )	rV   statusidr   r   rm   r   r   rn   ss	            re   GetRetweetszApi.GetRetweetsN  s    & 15xH+tY?

 "*7C"?JwU<))$,,*=*=g*FG378a&&q)888s   >Bc                    d| j                   z  }t        dt        |      t        dt        |      |d}g }d}	 |r	 t        |      |d<   | j                  |d	|
      }	| j                  |	j                  j                  d            }
||
d   D cg c]  }| c}z  }d|
v r4|
d   dk(  s|
d   |
d   k(  r	 |S |
d   }|t        |
d         z  }|dk  r	 |S 	 |S # t        $ r t        ddi      w xY wc c}w )a  Returns a collection of up to 100 user IDs belonging to users who have
        retweeted the tweet specified by the status_id parameter.

        Args:
          status_id:
            the tweet's numerical ID
          cursor:
            breaks the ids into pages of no more than 100.
          stringify_ids:
            returns the IDs as unicode strings. [Optional]

        Returns:
          A list of user IDs
        z%s/statuses/retweeters/ids.jsonr   stringify_ids)r   rs  r   r   cursorr&   cursor must be an integerr   r   r   idsnext_cursorprevious_cursorr'   )rA   r   r   r   r   r   r   r   r   rt   r   )rV   r   rt  r   rs  rm   r   r   total_countr   rn   r   s               re   GetRetweeterszApi.GetRetweetersn  sC   & 04==A4i0%ot]K

 Q+.v;Jx( ##CZ#@D--dll.A.A'.JKD$u+.Qq..F$&!+tM/BdK\F]/]  "-0F3tE{#33K"Q  )  " Q&	3N'OPPQ /s   C 	C4C1c                    d| j                   z  }|	 t        |      dkD  rt        ddi      	 |||t	        |      t	        |      t	        |      d}| j                  |d|      }	| j                  |	j                  j                  d	            }
|
D cg c]  }t        j                  |       c}S # t        $ r t        ddi      w xY wc c}w )
a  Returns up to 100 of the most recent tweets of the user that have been
        retweeted by others.

        Args:
          count:
            The number of retweets to retrieve, up to 100.
            Defaults to 20. [Optional]
          since_id:
            Returns results with an ID greater than
            (newer than) this ID. [Optional]
          max_id:
            Returns results with an ID less than or equal
            to this ID. [Optional]
          trim_user:
            When True, the user object for each tweet will
            only be an ID. [Optional]
          include_entities:
            When True, the tweet entities will be included. [Optional]
          include_user_entities:
            When True, the user entities will be included. [Optional]
        z%s/statuses/retweets_of_me.jsonr   r&   z#'count' may not be greater than 100r   )r   r   r   r   r   include_user_entitiesr   r   r   )rA   r   r   r   r   r   r   r   rt   r   r   )rV   r   r   r   r   r   r|  rm   r   r   rn   rp  s               re   GetRetweetsOfMezApi.GetRetweetsOfMe  s    8 0$--?Nu:#&	3X'YZZ $
  i $%5 6%)*?%@

 U<))$,,*=*=g*FG378a&&q)88  N"I/K#LMMN 9s   B4 C4Cc                 6   d| j                   z  d| j                   z  dd| j                   z  d| j                   z  dd}||   |   }g }	t        |      t        |      t        |      |d}
| j                  |d|
	      }| j                  |j                  j                  d
            }|dk(  r|	|j                  d      z  }	n)|	|d   D cg c]  }t        j                  |       c}z  }	|j                  dd      }|j                  dd      }|||	fS c c}w )an   Fetch a page of the users (as twitter.User instances)
        blocked or muted by the currently authenticated user.

        Args:
          endpoint (str):
            Either "mute" or "block".
          action (str):
            Either 'list' or 'ids' depending if you want to return fully-hydrated
            twitter.User objects or a list of user IDs as ints.
          cursor (int, optional):
            Should be set to -1 if you want the first page, thereafter denotes
            the page of users that you want to return.
          skip_status (bool, optional):
            If True the statuses will not be returned in the user items.
          include_entities (bool, optional):
            When True, the user entities will be included.

        Returns:
          next_cursor, previous_cursor, list of twitter.User instances,
          one for each user.
        z%s/mutes/users/list.jsonz%s/mutes/users/ids.json)r   rv  z%s/blocks/list.jsonz%s/blocks/ids.json)muteblock)skip_statusr   rs  rt  r   r   r   rv  r   rw  r   rx  )	rA   r   r   r   r   rt   r   r   r   )rV   endpointactionrt  r  r   rs  urlsrm   r   r   r   rn   r   rw  rx  s                   re   _GetBlocksMutesPagedzApi._GetBlocksMutesPaged  s(   < 3T]]B04==@
 .=+dmm;	
 8nV$, $%5 6!-0	

 U<))$,,*=*=g*FGU?dhhuo%FWF1t++A.FFFhh}a0((#4a8OV33	 Gs   Dc                 f    g }d}	 | j                  |||      \  }}}||z  }|dk(  s||k(  r	 |S |}-)a   Fetch the sequence of all users (as twitter.User instances),
        blocked by the currently authenticated user.

        Args:
          skip_status (bool, optional):
            If True the statuses will not be returned in the user items.
          include_entities (bool, optional):
            When True, the user entities will be included.

        Returns:
          A list of twitter.User instances, one for each blocked user.
        r^  rt  r  r   r   )GetBlocksPagedrV   r  r   r   rt  rw  rx  r   s           re   	GetBlockszApi.GetBlocks  sg     262E2E'!1 3F 33/K% eOFa;/#A  % r~   c                 .    | j                  dd|||      S )a   Fetch a page of the users (as twitter.User instances)
        blocked by the currently authenticated user.

        Args:
          cursor (int, optional):
            Should be set to -1 if you want the first page, thereafter denotes
            the page of blocked users that you want to return.
          skip_status (bool, optional):
            If True the statuses will not be returned in the user items.
          include_entities (bool, optional):
            When True, the user entities will be included.

        Returns:
          next_cursor, previous_cursor, list of twitter.User instances,
          one for each blocked user.
        r  r   r  r  rt  r  r   r  rV   rt  r  r   s       re   r  zApi.GetBlocksPaged.  s,    ( (('06065@:J	 ) L 	Lr~   c                 d    g }d}	 | j                  ||      \  }}}||z  }|dk(  s||k(  r	 |S |},)a.  Fetch the sequence of all user IDs blocked by the
        currently authenticated user.

        Args:
          stringify_ids (bool, optional):
            If True user IDs will be returned as strings rather than integers.

        Returns:
          A list of user IDs for all blocked users.
        r^  rt  rs  r   )GetBlocksIDsPagedrV   rs  r   rt  rw  rx  user_idss          re   GetBlocksIDszApi.GetBlocksIDsH  se     595K5K+ 6L 6-2K( hFa;/#A  % r~   c                 ,    | j                  dd||      S )a   Fetch a page of the user IDs blocked by the currently
        authenticated user.

        Args:
          cursor (int, optional):
            Should be set to -1 if you want the first page, thereafter denotes
            the page of blocked users that you want to return.
          stringify_ids (bool, optional):
            If True user IDs will be returned as strings rather than integers.

        Returns:
          next_cursor, previous_cursor, list of user IDs of blocked users.
        r  rv  r  r  rt  rs  r  rV   rt  rs  s      re   r  zApi.GetBlocksIDsPagedc  s)      (('05067D ) F 	Fr~   c                 f    g }d}	 | j                  |||      \  }}}||z  }|dk(  s||k(  r	 |S |}-)a   Fetch the sequence of all users (as twitter.User instances),
        muted by the currently authenticated user.

        Args:
          skip_status (bool, optional):
            If True the statuses will not be returned in the user items.
          include_entities (bool, optional):
            When True, the user entities will be included.

        Returns:
          A list of twitter.User instances, one for each muted user.
        r^  r  r   )GetMutesPagedr  s           re   GetMuteszApi.GetMutesx  sg     262D2D'!1 3E 33/K% eOFa;/#A  % r~   c                 .    | j                  dd|||      S )a   Fetch a page of the users (as twitter.User instances)
        muted by the currently authenticated user.

        Args:
          cursor (int, optional):
            Should be set to -1 if you want the first page, thereafter denotes
            the page of muted users that you want to return.
          skip_status (bool, optional):
            If True the statuses will not be returned in the user items.
          include_entities (bool, optional):
            When True, the user entities will be included.

        Returns:
          next_cursor, previous_cursor, list of twitter.User instances,
          one for each muted user.
        r  r   r  r  r  s       re   r  zApi.GetMutesPaged  s,    * ((&06065@:J	 ) L 	Lr~   c                 d    g }d}	 | j                  ||      \  }}}||z  }|dk(  s||k(  r	 |S |},)a*  Fetch the sequence of all user IDs muted by the
        currently authenticated user.

        Args:
          stringify_ids (bool, optional):
            If True user IDs will be returned as strings rather than integers.

        Returns:
          A list of user IDs for all muted users.
        r^  r  r   )GetMutesIDsPagedr  s          re   GetMutesIDszApi.GetMutesIDs  se     595J5J+ 6K 6-2K( hFa;/#A  % r~   c                 ,    | j                  dd||      S )a   Fetch a page of the user IDs muted by the currently
        authenticated user.

        Args:
          cursor (int, optional):
            Should be set to -1 if you want the first page, thereafter denotes
            the page of muted users that you want to return.
          stringify_ids (bool, optional):
            If True user IDs will be returned as strings rather than integers.

        Returns:
          next_cursor, previous_cursor, list of user IDs of muted users.
        r  rv  r  r  r  s      re   r  zApi.GetMutesIDsPaged  s)      ((&05067D ) F 	Fr~   c                    d| j                   z  d| j                   z  dd| j                   z  d| j                   z  dd}||   |   }i }	|rt        dt        |      |	d<   n|r||	d<   nt        d	      |rt        d
t        |      |	d
<   |rt        dt        |      |	d<   | j                  |d|	      }
| j                  |
j                  j                  d            }t        j                  |      S )a  Create or destroy a block or mute on behalf of the authenticated user.

        Args:
          action (str):
            Either 'create' or 'destroy'.
          endpoint (str):
            Either 'block' or 'mute'.
          user_id (int, optional)
            The numerical ID of the user to block/mute.
          screen_name (str, optional):
            The screen name of the user to block/mute.
          include_entities (bool, optional):
            The entities node will not be included if set to False.
          skip_status (bool, optional):
              When set to False, the blocked User's statuses will not be included
              with the returned User object.
        Returns:
          twitter.User: twitter.User object representing the blocked/muted user.
        z%s/blocks/create.jsonz%s/blocks/destroy.json)createdestroyz%s/mutes/users/create.jsonz%s/mutes/users/destroy.json)r  r  r   r   z0You must specify either a user_id or screen_namer   r  r  r   r   )rA   r   r   r   r   r   r   r   rt   r   r   )rV   r  r  r   r   r   r  r  rm   r	  r   rn   s               re   
_BlockMutezApi._BlockMute  s   : 2T]]C3t}}E
 7$--H8DMMJ	
 8nV$	#+IsG#DIi '2Im$QRR,45GO_,`I()'/t['QIm$V)<))$,,*=*=g*FG##D))r~   c                 0    | j                  dd||||      S )ah  Blocks the user specified by either user_id or screen_name.

        Args:
          user_id (int, optional)
            The numerical ID of the user to block.
          screen_name (str, optional):
            The screen name of the user to block.
          include_entities (bool, optional):
            The entities node will not be included if set to False.
          skip_status (bool, optional):
            When set to False, the blocked User's statuses will not be included
            with the returned User object.

        Returns:
          A twitter.User instance representing the blocked user.
        r  r  r  r  r   r   r   r  r  rV   r   r   r   r  s        re   CreateBlockzApi.CreateBlock  s+    * h(/'.+60@+6  8 	8r~   c                 0    | j                  dd||||      S )ai  Unlocks the user specified by either user_id or screen_name.

        Args:
          user_id (int, optional)
            The numerical ID of the user to block.
          screen_name (str, optional):
            The screen name of the user to block.
          include_entities (bool, optional):
            The entities node will not be included if set to False.
          skip_status (bool, optional):
            When set to False, the blocked User's statuses will not be included
            with the returned User object.

        Returns:
          A twitter.User instance representing the blocked user.
        r  r  r  r  r  s        re   DestroyBlockzApi.DestroyBlock8  s+    * i(/'.+60@+6  8 	8r~   c                 0    | j                  dd||||      S )aa  Mutes the user specified by either user_id or screen_name.

        Args:
          user_id (int, optional)
            The numerical ID of the user to mute.
          screen_name (str, optional):
            The screen name of the user to mute.
          include_entities (bool, optional):
            The entities node will not be included if set to False.
          skip_status (bool, optional):
            When set to False, the muted User's statuses will not be included
            with the returned User object.

        Returns:
          A twitter.User instance representing the muted user.
        r  r  r  r  r  s        re   
CreateMutezApi.CreateMuteT  s+    * h(.'.+60@+6  8 	8r~   c                 0    | j                  dd||||      S )ac  Unlocks the user specified by either user_id or screen_name.

        Args:
          user_id (int, optional)
            The numerical ID of the user to mute.
          screen_name (str, optional):
            The screen name of the user to mute.
          include_entities (bool, optional):
            The entities node will not be included if set to False.
          skip_status (bool, optional):
            When set to False, the muted User's statuses will not be included
            with the returned User object.

        Returns:
          A twitter.User instance representing the muted user.
        r  r  r  r  r  s        re   DestroyMutezApi.DestroyMutep  s+    * i(.'.+60@+6  8 	8r~   c                 l   g }i }|||d<   |||d<   |||d<   ||d<   ||d<   | j                  |d|      }	| j                  |	j                  j                  d            }
d	|
v r"|j	                  |
d	   D cg c]  }| c}       |
j                  d
d      }|
j                  dd      }|||fS c c}w )a$  
        This is the lowest level paging logic for fetching IDs. It is used
        solely by GetFollowerIDsPaged and GetFriendIDsPaged. It is not intended
        for other use.

        See GetFollowerIDsPaged or GetFriendIDsPaged for an explanation of the
        input arguments.
        r   r   r   rs  rt  r   r   r   rv  rw  r   rx  )r   r   r   rt   extendr   )rV   rm   r   r   rt  rs  r   r   r   r   rn   r   rw  rx  s                 re   _GetIDsPagedzApi._GetIDsPaged  s     
$+Jy!"(3J}%"'Jw&3
?#%
8U<))$,,*=*=g*FGD=MMd5k2123hh}a0((#4a8OV33 3s   8	B1c                 N    d| j                   z  }| j                  ||||||      S )a  Make a cursor driven call to return a list of one page followers.

        The caller is responsible for handling the cursor value and looping
        to gather all of the data

        Args:
          user_id:
            The twitter id of the user whose followers you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          screen_name:
            The twitter name of the user whose followers you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          cursor:
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          stringify_ids:
            if True then twitter will return the ids as strings instead of
            integers. [Optional]
          count:
            The number of user id's to retrieve per API request. Please be aware
            that this might get you rate-limited if set to a small number.
            By default Twitter will retrieve 5000 UIDs per call. [Optional]

        Returns:
          next_cursor, previous_cursor, data sequence of user ids,
          one for each follower
        %s/followers/ids.jsonrm   r   r   rt  rs  r   rA   r  rV   r   r   rt  rs  r   rm   s          re   GetFollowerIDsPagedzApi.GetFollowerIDsPaged  s<    B &5  S)0-8(./<', ! . 	.r~   c                 L    d| j                   z  }| j                  ||||||      S )a  Make a cursor driven call to return the list of all friends

        The caller is responsible for handling the cursor value and looping
        to gather all of the data

        Args:
          user_id:
            The twitter id of the user whose friends you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          screen_name:
            The twitter name of the user whose friends you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          cursor:
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          stringify_ids:
            if True then twitter will return the ids as strings instead of
            integers. [Optional]
          count:
            The number of user id's to retrieve per API request. Please be aware
            that this might get you rate-limited if set to a small number.
            By default Twitter will retrieve 5000 UIDs per call. [Optional]

        Returns:
          next_cursor, previous_cursor, data sequence of twitter.User instances,
          one for each friend
        %s/friends/ids.jsonr  r  s          re   GetFriendIDsPagedzApi.GetFriendIDsPaged  s7    B $dmm3  !(!,!'!.!&( 	(r~   c                    d}d}g }|rt        dt        |      }|r||k  r|}	 |t        |      |z   |kD  r	 |S | j                  ||||||      \  }	}
}|j	                  |D cg c]  }| c}       |	dk(  s|	|
k(  r	 |S |	}`c c}w )z3 Common method for GetFriendIDs and GetFollowerIDs   r^  ry  r  r   )r   r   r   r  r  )rV   rm   r   r   rt  r   rs  ry  r   rw  rx  rn   r   s                re   _GetFriendFollowerIDszApi._GetFriendFollowerIDs	  s     "=#{CK;.E&3v;+>+L"  261B1B'+ 2C 2.K$ MMd+1+,a;/#A  %#  ,s   $	Bc           	      P    d| j                   z  }| j                  |||||||      S )a  Returns a list of twitter user id's for every person
        that is following the specified user.

        Args:
          user_id:
            The id of the user to retrieve the id list for. [Optional]
          screen_name:
            The screen_name of the user to retrieve the id list for. [Optional]
          cursor:
            Specifies the Twitter API Cursor location to start at.
            Note: there are pagination limits. [Optional]
          stringify_ids:
            if True then twitter will return the ids as strings instead of
            integers. [Optional]
          count:
            The number of user id's to retrieve per API request. Please be aware
            that this might get you rate-limited if set to a small number.
            By default Twitter will retrieve 5000 UIDs per call. [Optional]
          total_count:
            The total amount of UIDs to retrieve. Good if the account has many
            followers and you don't want to get rate limited. The data returned
            might contain more UIDs if total_count is not a multiple of count
            (5000 by default). [Optional]

        Returns:
          A list of integers, one for each user id.
        r  )rm   r   r   rt  rs  r   ry  rA   r  )rV   r   r   rt  rs  r   ry  rm   s           re   GetFollowerIDszApi.GetFollowerIDs-	  sA    D &5))c296A178E056A * C 	Cr~   c           	      N    d| j                   z  }| j                  |||||||      S )a*   Fetch a sequence of user ids, one for each friend.
        Returns a list of all the given user's friends' IDs. If no user_id or
        screen_name is given, the friends will be those of the authenticated
        user.

        Args:
          user_id:
            The id of the user to retrieve the id list for. [Optional]
          screen_name:
            The screen_name of the user to retrieve the id list for. [Optional]
          cursor:
            Specifies the Twitter API Cursor location to start at.
            Note: there are pagination limits. [Optional]
          stringify_ids:
            if True then twitter will return the ids as strings instead of integers.
            [Optional]
          count:
            The number of user id's to retrieve per API request. Please be aware that
            this might get you rate-limited if set to a small number.
            By default Twitter will retrieve 5000 UIDs per call. [Optional]
          total_count:
            The total amount of UIDs to retrieve. Good if the account has many followers
            and you don't want to get rate limited. The data returned might contain more
            UIDs if total_count is not a multiple of count (5000 by default). [Optional]

        Returns:
          A list of integers, one for each user id.
        r  r  )rV   r   r   rt  r   rs  ry  rm   s           re   GetFriendIDszApi.GetFriendIDsX	  s:    F $dmm3))#*1*5*0*/*7*57 	7r~   c                    |r|rt        j                  dd       i }|||d<   |||d<   	 t        |      |d<   ||d	<   ||d
<   ||d<   | j                  |d|      }	| j                  |	j                  j                  d            }
d|
v r&|
d   D cg c]  }t        j                  |       }}ng }d|
v r|
d   }nd}d|
v r|
d   }nd}|||fS # t        $ r t	        ddi      w xY wc c}w )a  Make a cursor driven call to return the list of 1 page of friends
        or followers.

        Args:
          url:
            Endpoint from which to get data. Either
            base_url+'/followers/list.json' or base_url+'/friends/list.json'.
          user_id:
            The twitter id of the user whose followers you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          screen_name:
            The twitter name of the user whose followers you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          cursor:
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          count:
            The number of users to return per page, up to a maximum of 200.
            Defaults to 200. [Optional]
          skip_status:
            If True the statuses will not be returned in the user items.
            [Optional]
          include_user_entities:
            When True, the user entities will be included. [Optional]

        Returns:
          next_cursor, previous_cursor, data sequence of twitter.User
          instances, one for each follower
        zIf both user_id and screen_name are specified, Twitter will return the followers of the user specified by screen_name, however this behavior is undocumented by Twitter and might change without warning.rA  )
stacklevelr   r   r   r&   r   r  r|  rt  r   r   r   r   rw  r   rx  )r6   r7   r   r   r   r   r   r   rt   r   r   )rV   rm   r   r   rt  r   r  r|  r   r   rn   r   r   rw  rx  s                  re   _GetFriendsFollowersPagedzApi._GetFriendsFollowersPaged	  sE   N {MM* 78	9 
$+Jy!"(3J}%	H"%e*Jw %0
=!.C
*+%
8U<))$,,*=*=g*FGd?<@MJDT))$/JEJED }-KK$"#45OOOU221  	H	+EFGG	H Ks   C C+C(c           	      N    d| j                   z  }| j                  |||||||      S )a$  Make a cursor driven call to return the list of all followers

        Args:
          user_id:
            The twitter id of the user whose followers you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          screen_name:
            The twitter name of the user whose followers you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          cursor:
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          count:
            The number of users to return per page, up to a maximum of 200.
            Defaults to 200. [Optional]
          skip_status:
            If True the statuses will not be returned in the user items.
            [Optional]
          include_user_entities:
            When True, the user entities will be included. [Optional]

        Returns:
          next_cursor, previous_cursor, data sequence of twitter.User
          instances, one for each follower
        %s/followers/list.jsonrA   r  rV   r   r   rt  r   r  r|  rm   s           re   GetFollowersPagedzApi.GetFollowersPaged	  s<    @ '6--c.5.9.4.3.9.CE 	Er~   c           	      N    d| j                   z  }| j                  |||||||      S )a'  Make a cursor driven call to return the list of all friends.

        Args:
          user_id:
            The twitter id of the user whose friends you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          screen_name:
            The twitter name of the user whose friends you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          cursor:
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          count:
            The number of users to return per page, up to a current maximum of
            200. Defaults to 200. [Optional]
          skip_status:
            If True the statuses will not be returned in the user items.
            [Optional]
          include_user_entities:
            When True, the user entities will be included. [Optional]

        Returns:
          next_cursor, previous_cursor, data sequence of twitter.User
          instances, one for each follower
        %s/friends/list.jsonr  r  s           re   GetFriendsPagedzApi.GetFriendsPaged	  s<    @ %t}}4--c.5.9.4.3.9.CE 	Er~   c	           	      R   ||t        j                  dt               d}d}g }	|r	 t        |      }|dk  r|}	 |t        |	      |z   |kD  r	 |	S | j                  |||||||      \  }
}}|
r|
}|	j                  |       |
dk(  s|
|k(  r	 |	S T# t        $ r t        ddi      w xY w)a   Fetch the sequence of twitter.User instances, one for each friend
        or follower.

        Args:
          url:
            URL to get. Either base_url + ('/followers/list.json' or
            '/friends/list.json').
          user_id:
            The twitter id of the user whose friends you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          screen_name:
            The twitter name of the user whose friends you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          cursor:
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          count:
            The number of users to return per page, up to a maximum of 200.
            Defaults to 200. [Optional]
          total_count:
            The upper bound of number of users to return, defaults to None.
          skip_status:
            If True the statuses will not be returned in the user items.
            [Optional]
          include_user_entities:
            When True, the user entities will be included. [Optional]

        Returns:
          A sequence of twitter.User instances, one for each friend or follower
        zUse of 'cursor' and 'count' parameters are deprecated as of python-twitter 3.0. Please use GetFriendsPaged or GetFollowersPaged instead.r   r^  r&   ztotal_count must be an integerr   )	r6   r7   r   r   r   r   r   r  r  )rV   rm   r   r   rt  r   ry  r  r|  r   rw  rx  rn   s                re   _GetFriendsFollowerszApi._GetFriendsFollowers'
  s    R !2MM- 3	4 R!+. c!#&3v;+>+L& # 261O1O%2'.K$ $MM$a;/#A+   R"I/O#PQQRs   B B&c           
      P    d| j                   z  }| j                  ||||||||      S )a:  Fetch the sequence of twitter.User instances, one for each follower.

        If both user_id and screen_name are specified, this call will return
        the followers of the user specified by screen_name, however this
        behavior is undocumented by Twitter and may change without warning.

        Args:
          user_id:
            The twitter id of the user whose followers you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          screen_name:
            The twitter name of the user whose followers you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          cursor:
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          count:
            The number of users to return per page, up to a maximum of 200.
            Defaults to 200. [Optional]
          total_count:
            The upper bound of number of users to return, defaults to None.
          skip_status:
            If True the statuses will not be returned in the user items. [Optional]
          include_user_entities:
            When True, the user entities will be included. [Optional]

        Returns:
          A sequence of twitter.User instances, one for each follower
        r  rA   r  	rV   r   r   rt  r   ry  r  r|  rm   s	            re   GetFollowerszApi.GetFollowers{
  s?    J '6(()0)4)/).)4)4)>@ 	@r~   c           
      P    d| j                   z  }| j                  ||||||||      S )a>  Fetch the sequence of twitter.User instances, one for each friend.

        If both user_id and screen_name are specified, this call will return
        the followers of the user specified by screen_name, however this
        behavior is undocumented by Twitter and may change without warning.

        Args:
          user_id:
            The twitter id of the user whose friends you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          screen_name:
            The twitter name of the user whose friends you are fetching.
            If not specified, defaults to the authenticated user. [Optional]
          cursor:
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          count:
            The number of users to return per page, up to a maximum of 200.
            Defaults to 200. [Optional]
          total_count:
            The upper bound of number of users to return, defaults to None.
          skip_status:
            If True the statuses will not be returned in the user items.
            [Optional]
          include_user_entities:
            When True, the user entities will be included. [Optional]

        Returns:
          A sequence of twitter.User instances, one for each friend
        r  r  r  s	            re   
GetFriendszApi.GetFriends
  s?    L %t}}4(()0)4)/).)4)4)>@ 	@r~   c                    t        |||g      st        d      d| j                  z  }d|i}t               }|r|j	                  |       |r)|j	                  |D 	cg c]  }	|	j
                   c}	       t        |      r+dj                  |D 	cg c]  }	t        |	       c}	      |d<   |rt        |d      |d<   t        |      dkD  rt        d      | j                  |d	|
      }
| j                  |
j                  j                  d            }|r|S |D 	cg c]  }	t        j                  |	       c}	S c c}	w c c}	w c c}	w )a  Fetch extended information for the specified users.

        Users may be specified either as lists of either user_ids,
        screen_names, or twitter.User objects. The list of users that
        are queried is the union of all specified parameters.

        No more than 100 users may be given per request.

        Args:
          user_id (int, list, optional):
            A list of user_ids to retrieve extended information.
          screen_name (str, list, optional):
            A list of screen_names to retrieve extended information.
          users (list, optional):
            A list of twitter.User objects to retrieve extended information.
          include_entities (bool, optional):
            The entities node that may appear within embedded statuses will be
            excluded when set to False.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          A list of twitter.User objects for the requested users
        z7Specify at least one of user_id, screen_name, or users.z%s/users/lookup.jsonr   r   r   r   r   z4No more than 100 users may be requested per request.r   r   r   )anyr   rA   r   r  r   r   r   r   r   r   r   r   rt   r   r   )rV   r   r   r   r   r   rm   r   uidsr$  r   rn   s               re   UsersLookupzApi.UsersLookup
  s+   < G[%01XYY$t}}4 0

 vKK KKu-!-.t9$'HHd-Cc!f-C$DJy!(6{M(RJ}%t9s?UVVU<))$,,*=*=g*FGK59:D((+:: .-C ;s   D:D?Ec                    d| j                   z  }d|i}|r||d<   n|r||d<   nt        d      | j                  |d|      }| j                  |j                  j                  d            }|r|S t        j                  |      S )	a^  Returns a single user.

        Args:
          user_id (int, optional):
            The id of the user to retrieve.
          screen_name (str, optional):
            The screen name of the user for whom to return results for.
            Either a user_id or screen_name is required for this method.
          include_entities (bool, optional):
            The entities node will be omitted when set to False.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          A twitter.User instance representing that user
        z%s/users/show.jsonr   r   r   /Specify at least one of user_id or screen_name.r   r   r   rA   r   r   r   r   rt   r   r   )	rV   r   r   r   r   rm   r   r   rn   s	            re   GetUserzApi.GetUser  s    * #dmm4 0

 $+Jy!(3J}%PQQU<))$,,*=*=g*FGK''--r~   c	                    d| j                   z  }	t        |      t        |      ||t        |      d}
|rt        dt        |      |
d<   |rt        dt        |      |
d<   | j	                  |	d|
      }| j                  |j                  j                  d            }|r|S |D cg c]  }t        j                  |       c}S c c}w )a8  Returns a list of the direct messages sent to the authenticating user.

        Args:
          since_id:
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occurred since the since_id, the since_id will be
            forced to the oldest ID available. [Optional]
          max_id:
            Returns results with an ID less than (that is, older than) or
            equal to the specified ID. [Optional]
          count:
            Specifies the number of direct messages to try and retrieve, up to a
            maximum of 200. The value of count is best thought of as a limit to the
            number of Tweets to return because suspended or deleted content is
            removed after the count has been applied. [Optional]
          include_entities:
            The entities node will be omitted when set to False.
            [Optional]
          skip_status:
            When set to True statuses will not be included in the returned user
            objects. [Optional]
          full_text:
            When set to True full message will be included in the returned message
            object if message length is bigger than CHARACTER_LIMIT characters. [Optional]
          page:
            If you want more than 200 messages, you can use this and get 20 messages
            each time. You must recall it and increment the page value until it
            return nothing. You can't use count option with it. First value is 1 and
            not 0.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          A sequence of twitter.DirectMessage instances
        z%s/direct_messages.json)	full_textr   r   r   r  r   r   r   r   r   
rA   r   r   r   r   r   r   rt   r   r   )rV   r   r   r   r   r  r  r   r   rm   r   r   rn   r   s                 re   GetDirectMessageszApi.GetDirectMessages<  s    \ ($--7i $%5 6 ,

 "*7C"?Jw!)&#t!<JvU<))$,,*=*=g*FGK>BCM11!4CCCs   %Cc                 j   d| j                   z  }t        |      ||d}|rt        dt        |      |d<   |rt        dt        |      |d<   | j	                  |d|      }	| j                  |	j                  j                  d            }
|r|
S |
D cg c]  }t        j                  |       c}S c c}w )aj  Returns a list of the direct messages sent by the authenticating user.

        Args:
          since_id (int, optional):
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occured since the since_id, the since_id will be
            forced to the oldest ID available.
          max_id (int, optional):
            Returns results with an ID less than (that is, older than) or
            equal to the specified ID.
          count (int, optional):
            Specifies the number of direct messages to try and retrieve, up to a
            maximum of 200. The value of count is best thought of as a limit to the
            number of Tweets to return because suspended or deleted content is
            removed after the count has been applied.
          page (int, optional):
            Specifies the page of results to retrieve.
            Note: there are pagination limits. [Optional]
          include_entities (bool, optional):
            The entities node will be omitted when set to False.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          A sequence of twitter.DirectMessage instances
        z%s/direct_messages/sent.json)r   r   r   r   r   r   r   r   r  )rV   r   r   r   r   r   r   rm   r   r   rn   r   s               re   GetSentDirectMessageszApi.GetSentDirectMessages  s    F -t}}< !%%5 6 

 "*7C"?Jw!)&#t!<JvU<))$,,*=*=g*FGK>BCM11!4CCCs   B0c                 X   d| j                   z  }||| j                  |      j                  }ddd|id|iddi}| j                  |d	|
      }|j	                         }|r|S t        |d   d   |d   d   |d   d   d   d   |d   d   d   |d   d   d   d         }	||	_        |	S )a  Post a twitter direct message from the authenticated user.

        Args:
          text: The message text to be posted.
          user_id:
            The ID of the user who should receive the direct message.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.DirectMessage
        Returns:
          A twitter.DirectMessage instance representing the message posted
        z"%s/direct_messages/events/new.json)r   eventmessage_createrecipient_idr5  )targetmessage_data)typer  r  r7  created_timestampr   r  	sender_idr  )
created_atr   r  r  r5  )rA   r  r   r   rv   r   _json)
rV   r5  r   r   r   rm   r  r   rn   dms
             re   PostDirectMessagezApi.PostDirectMessage  s     3T]]B ?{6ll{l;>>G ( ' %	#

 V%8yy{K=)<==&!']+;<XF~Vw-(89+F']#34^DVLB BHIr~   c                    d| j                   z  }t        dt        |      t        dt        |      d}| j	                  |d|      }| j                  |j                  j                  d            }|r|S t        j                  |      S )a  Destroys the direct message specified in the required ID parameter.

        The twitter.Api instance must be authenticated, and the
        authenticating user must be the recipient of the specified direct
        message.

        Args:
          message_id:
            The id of the direct message to be destroyed
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          A twitter.DirectMessage instance representing the message destroyed
        z%s/direct_messages/destroy.json
message_idr   )r   r   r  r   r   )
rA   r   r   r   r   r   r   rt   r   r   )rV   r  r   r   rm   rn   r   s          re   DestroyDirectMessagezApi.DestroyDirectMessage  s      0$--?<j9 ();TCS T

 V$7))$,,*=*=g*FGK 0066r~   c                 0     | j                   d||||d|S )a  Befriends the user specified by the user_id or screen_name.

        Args:
          user_id (int, optional):
            A user_id to follow
          screen_name (str, optional)
            A screen_name to follow
          follow (bool, optional):
            Set to False to disable notifications for the target user
          retweets (bool, optional):
            Enable or disable retweets from the target user.

        Returns:
          A twitter.User instance representing the befriended user.
        )r   r   followretweetsr_  _AddOrEditFriendshiprV   r   r   r  r  ra  s         re   CreateFriendshipzApi.CreateFriendship  s3      )t(( 35@062:3 ,2	3 	3r~   c                 |   | j                   d|d}i }|r||d<   n|r||d<   nt        d      t        j                  |      }	|	|dj	                  |      <    |j
                  d
i | | j                  |d|      }
| j                  |
j                  j                  d	            }t        j                  |      S )z+Shared method for Create/Update Friendship.z/friendships/r   r   r   r  z{}r  r   r   r_  )rA   r   rv   dumpsrr   r   r   r   r   rt   r   r   )rV   r   r   uri_end
follow_keyr  ra  rm   rn   follow_jsonr   s              re   r  zApi._AddOrEditFriendship!  s     +/--A%DO"-DPQQjj((3T[[$%fV$7))$,,*=*=g*FG##D))r~   c           
      4     | j                   d|||d|dd|S )aj  Updates a friendship with the user specified by the user_id or screen_name.

        Args:
          user_id (int, optional):
            A user_id to update
          screen_name (str, optional):
            A screen_name to update
          follow (bool, optional):
            Set to False to disable notifications for the target user
          retweets (bool, optional):
            Enable or disable retweets from the target user.
          device:
            Set to False to disable notifications for the target user

        Returns:
          A twitter.User instance representing the befriended user.
        devicer   )r   r   r  r  r  r  r_  r  r  s         re   UpdateFriendshipzApi.UpdateFriendship;  s9    . )t(( 35@064<2:193 ,23 	3r~   c                     d| j                   z  }i }|r||d<   n|r||d<   nt        d      | j                  |d|      }| j                  |j                  j                  d            }t        j                  |      S )a0  Discontinues friendship with a user_id or screen_name.

        Args:
          user_id:
            A user_id to unfollow [Optional]
          screen_name:
            A screen_name to unfollow [Optional]

        Returns:
          A twitter.User instance representing the discontinued friend.
        z%s/friendships/destroy.jsonr   r   r  r  r   r   r  )rV   r   r   rm   rn   r   s         re   DestroyFriendshipzApi.DestroyFriendshipZ  s     ,dmm;%DO"-DPQQV$7))$,,*=*=g*FG##D))r~   c                    d| j                   z  }i }|r||d<   n|r||d<   nt        ddi      |r||d<   n|r||d<   nt        ddi      | j                  |d	|
      }| j                  |j                  j                  d            }|S )a  Returns information about the relationship between the two users.

        Args:
          source_id:
            The user_id of the subject user [Optional]
          source_screen_name:
            The screen_name of the subject user [Optional]
          target_id:
            The user_id of the target user [Optional]
          target_screen_name:
            The screen_name of the target user [Optional]

        Returns:
          A Twitter Json structure.
        z%s/friendships/show.json	source_idsource_screen_namer&   z=Specify at least one of source_user_id or source_screen_name.	target_idtarget_screen_namez=Specify at least one of target_user_id or target_screen_name.r   r   r   )rA   r   r   r   r   rt   )rV   source_user_idr  target_user_idr	  rm   rn   r   s           re   ShowFriendshipzApi.ShowFriendshipt  s    ( )4==8 .D);D%&	+jkll .D);D%&	+jkllU6))$,,*=*=g*FGr~   c                 F   d| j                   z  }i }|rt        |t        t        f      rt               }|D ]N  }t        |t              r|j                  |j                         /|j                  t        dt        |             P dj                  |D cg c]  }t        |       c}      |d<   n4t        |t              r|j                  |d<   nt        dt        |      |d<   |rt        |t        t        f      rrt               }	|D ]N  }t        |t              r|	j                  |j                         /|	j                  t        dt        |             P dj                  |	      |d<   n4t        |t              r|j                  |d<   nt        dt        |      |d<   |s|st        d      | j                  |d|      }
| j                  |
j                  j!                  d            }|r|S |D cg c]  }t#        j$                  |       c}S c c}w c c}w )	ay  Lookup friendship status for user to authed user.

        Users may be specified either as lists of either user_ids,
        screen_names, or twitter.User objects. The list of users that
        are queried is the union of all specified parameters.

        Up to 100 users may be specified.

        Args:
          user_id (int, User, or list of ints or Users, optional):
            A list of user_ids to retrieve extended information.
          screen_name (string, User, or list of strings or Users, optional):
            A list of screen_names to retrieve extended information.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          list: A list of twitter.UserStatus instance representing the
          friendship status between the specified users and the authenticated
          user.
        z%s/friendships/lookup.jsonr   r   r   r  r   r   r   )rA   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rt   r   r   )rV   r   r   r   rm   r   r  r   uidsn_listr   rn   r   s                re   LookupFriendshipzApi.LookupFriendship  s   2 +dmm<
'D%=1v# DD!$-DGG,HYT$BC	D
 ),d1Ks#c(1K(L
9%gt,,3JJJy),4YW,MJy)+e}5&' KD!$-t'7'78xsD'IJ	K
 -0HHW,=
=)k400;0G0GJ}-08[0YJ}-{PQQU<))$,,*=*=g*FGK;?@aJ..q1@@; 2L: As   H:Hc                    d| j                   z  }i }|rd|d<   g }d}	 |r	 t        |      |d<   | j	                  |d|	      }| j                  |j                  j                  d
            }||d   D 	cg c]  }	|	 c}	z  }d|v r4|d   dk(  s|d   |d   k(  r	 |S |d   }|t        |d         z  }|dk  r	 |S 	 |S # t        $ r t        ddi      w xY wc c}	w )a_  Returns a collection of user IDs belonging to users who have
        pending request to follow the authenticated user.

        Args:
          cursor:
            breaks the ids into pages of no more than 5000.
          stringify_ids:
            returns the IDs as unicode strings. [Optional]

        Returns:
          A list of user IDs
        z%s/friendships/incoming.jsonr   rs  r   r   r&   ru  r   r   r   rv  rw  rx  r'   	rA   r   r   r   r   r   r   rt   r   
rV   rt  rs  rm   r   r   ry  r   rn   r   s
             re   IncomingFriendshipzApi.IncomingFriendship  1    ->
*0J'Q*-f+Jw' ##CZ#@D--dll.A.A'.JKD$u+.Qq..F$&!+tM/BdK\F]/]  "-0F3tE{#33K"Q  )  " Q&	3N'OPPQ /   B? 5	C?Cc                    d| j                   z  }i }|rd|d<   g }d}	 |r	 t        |      |d<   | j	                  |d|	      }| j                  |j                  j                  d
            }||d   D 	cg c]  }	|	 c}	z  }d|v r4|d   dk(  s|d   |d   k(  r	 |S |d   }|t        |d         z  }|dk  r	 |S 	 |S # t        $ r t        ddi      w xY wc c}	w )ah  Returns a collection of user IDs for every protected user
        for whom the authenticated user has a pending follow request.

        Args:
          cursor:
            breaks the ids into pages of no more than 5000.
          stringify_ids:
            returns the IDs as unicode strings. [Optional]

        Returns:
          A list of user IDs
        z%s/friendships/outgoing.jsonr   rs  r   r   r&   ru  r   r   r   rv  rw  rx  r'   r  r  s
             re   OutgoingFriendshipzApi.OutgoingFriendship  r  r  c                 @   d| j                   z  }i }|r||d<   n|r|j                  |d<   nt        ddi      t        dt        |      |d<   | j                  |d|      }| j                  |j                  j                  d            }t        j                  |      S )	a0  Favorites the specified status object or id as the authenticating user.

        Returns the favorite status when successful.

        Args:
          status_id (int, optional):
            The id of the twitter status to mark as a favorite.
          status (twitter.Status, optional):
            The twitter.Status object to mark as a favorite.
          include_entities (bool, optional):
            The entities node will be omitted when set to False.

        Returns:
          A twitter.Status instance representing the newly-marked favorite.
        z%s/favorites/create.jsonr   r&   Specify status_id or statusr   r  r   r   rA   r   r   r   r   r   r   r   rt   r   r   rV   r  r   r   rm   rn   r   s          re   CreateFavoritezApi.CreateFavorite7  s    & )4==8"DJDJ	+HIJJ#+,>FV#W V$7))$,,*=*=g*FG%%d++r~   c                 @   d| j                   z  }i }|r||d<   n|r|j                  |d<   nt        ddi      t        dt        |      |d<   | j                  |d|      }| j                  |j                  j                  d            }t        j                  |      S )	a9  Un-Favorites the specified status object or id as the authenticating user.

        Returns the un-favorited status when successful.

        Args:
          status_id (int, optional):
            The id of the twitter status to mark as a favorite.
          status (twitter.Status, optional):
            The twitter.Status object to mark as a favorite.
          include_entities (bool, optional):
            The entities node will be omitted when set to False.

        Returns:
          A twitter.Status instance representing the newly-unmarked favorite.
        z%s/favorites/destroy.jsonr   r&   r  r   r  r   r   r  r  s          re   DestroyFavoritezApi.DestroyFavoriteY  s    & *DMM9"DJDJ	+HIJJ#+,>FV#W V$7))$,,*=*=g*FG%%d++r~   c                    i }d| j                   z  }	|rt        dt        |      |d<   n|r||d<   |rt        dt        |      |d<   |rt        dt        |      |d<   |rt        dt        |      |d<   t        dt        |      |d<   | j	                  |	d|	      }
| j                  |
j                  j                  d
            }|r|S |D cg c]  }t        j                  |       c}S c c}w )a#  Return a list of Status objects representing favorited tweets.

        Returns up to 200 most recent tweets for the authenticated user.

        Args:
          user_id (int, optional):
            Specifies the ID of the user for whom to return the
            favorites. Helpful for disambiguating when a valid user ID
            is also a valid screen name.
          screen_name (str, optional):
            Specifies the screen name of the user for whom to return the
            favorites. Helpful for disambiguating when a valid screen
            name is also a user ID.
          since_id (int, optional):
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occurred since the since_id, the since_id will be
            forced to the oldest ID available.
          max_id (int, optional):
            Returns only statuses with an ID less than (that is, older
            than) or equal to the specified ID.
          count (int, optional):
            Specifies the number of statuses to retrieve. May not be
            greater than 200.
          include_entities (bool, optional):
            The entities node will be omitted when set to False.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          A sequence of Status instances, one for each favorited tweet up to count
        z%s/favorites/list.jsonr   r   r   r   r   r   r   r   r   r   )rV   r   r   r   r   r   r   r   r   rm   r   rn   r   s                re   GetFavoriteszApi.GetFavorites|  s    R 
&6$,YW$EJy!(3J}%%-j#x%HJz"#+Hc6#BJx "*7C"?Jw)12DdL\)]
%&U<))$,,*=*=g*FGK7;<!F**1-<<<s   C+c                 f   d| j                   z  }t        |      t        |      ||t        |      d}	|rt        dt        |      |	d<   | j	                  |d|	      }
| j                  |
j                  j                  d            }|r|S |D cg c]  }t        j                  |       c}S c c}w )a  Returns the 20 most recent mentions (status containing @screen_name)
        for the authenticating user.

        Args:
          count:
            Specifies the number of tweets to try and retrieve, up to a maximum of
            200. The value of count is best thought of as a limit to the number of
            tweets to return because suspended or deleted content is removed after
            the count has been applied. [Optional]
          since_id:
            Returns results with an ID greater than (that is, more recent
            than) the specified ID. There are limits to the number of
            Tweets which can be accessed through the API. If the limit of
            Tweets has occurred since the since_id, the since_id will be
            forced to the oldest ID available. [Optional]
          max_id:
            Returns only statuses with an ID less than
            (that is, older than) the specified ID. [Optional]
          trim_user:
            When set to True, each tweet returned in a timeline will include a user
            object including only the status authors numerical ID. Omit this
            parameter to receive the complete user object. [Optional]
          contributor_details:
            If set to True, this parameter enhances the contributors element of the
            status response to include the screen_name of the contributor. By
            default only the user_id of the contributor is included. [Optional]
          include_entities:
            The entities node will be disincluded when set to False. [Optional]
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          A sequence of twitter.Status instances, one for each mention of the user.
        z"%s/statuses/mentions_timeline.json)r   r   r   r   r   r   r   r   r   )
rA   r   r   r   r   r   r   rt   r   r   )rV   r   r   r   r   r   r   r   rm   r   r   rn   r   s                re   GetMentionszApi.GetMentions  s    T 3T]]B $((;#< $%5 6 i

 "*7C"?JwU<))$,,*=*=g*FGK7;<!F**1-<<<s   B.c                     i }| t        dt        |       |d<   |S |3||d<   |t        dt        |      |d<   |S |||d<   |S t        ddi      t        ddi      )Nlist_idr   owner_idowner_screen_namer&   zRIf specifying a list by slug, an owner_id or owner_screen_name must also be given.zPEither list_id or slug and one of owner_id and owner_screen_name must be passed.)r   r   r   )r%  r   r&  r'  r   s        re   _IDListzApi._IDList  s    
$,YW$EJy!   !%Jv#)1*c8)L
:&  #.2C
./  #I<$> ? ? 	4 6 7 7r~   c                     d| j                   z  }d|i}|||d<   |||d<   | j                  |d|      }| j                  |j                  j	                  d            }t        j                  |      S )a  Creates a new list with the give name for the authenticated user.

        Args:
          name (str):
            New name for the list
          mode (str, optional):
            'public' or 'private'. Defaults to 'public'.
          description (str, optional):
            Description of the list.

        Returns:
          twitter.list.List: A twitter.List instance representing the new list
        z%s/lists/create.jsonnamemodedescriptionr  r   r   )rA   r   r   r   rt   r   r   )rV   r*  r+  r,  rm   r   r   rn   s           re   
CreateListzApi.CreateList  s     %t}}4d^
!%Jv"(3J}%V*=))$,,*=*=g*FG##D))r~   c                    d| j                   z  }i }|j                  | j                  ||||             | j                  |d|      }| j	                  |j
                  j                  d            }t        j                  |      S )aK  Destroys the list identified by list_id or slug and one of
        owner_screen_name or owner_id.

        Args:
          owner_screen_name (str, optional):
            The screen_name of the user who owns the list being requested
            by a slug.
          owner_id (int, optional):
            The user ID of the user who owns the list being requested
            by a slug.
          list_id (int, optional):
            The numerical id of the list.
          slug (str, optional):
            You can identify a list by its slug instead of its numerical id.
            If you decide to do so, note that you'll also have to specify
            the list owner using the owner_id or owner_screen_name parameters.

        Returns:
          twitter.list.List: A twitter.List instance representing the
          removed list.
        z%s/lists/destroy.jsonr%  r   r&  r'  r  r   r   	rA   r   r(  r   r   r   rt   r   r   	rV   r'  r&  r%  r   rm   r   r   rn   s	            re   DestroyListzApi.DestroyList*  s    4 &5
$,,w,0089J ' L 	M
 V*=))$,,*=*=g*FG##D))r~   c                    d| j                   z  }i }|j                  | j                  ||||             | j                  |d|      }| j	                  |j
                  j                  d            }t        j                  |      S )a  Creates a subscription to a list by the authenticated user.

        Args:
          owner_screen_name (str, optional):
            The screen_name of the user who owns the list being requested
            by a slug.
          owner_id (int, optional):
            The user ID of the user who owns the list being requested
            by a slug.
          list_id (int, optional):
            The numerical id of the list.
          slug (str, optional):
            You can identify a list by its slug instead of its numerical id.
            If you decide to do so, note that you'll also have to specify
            the list owner using the owner_id or owner_screen_name parameters.

        Returns:
          twitter.user.User: A twitter.User instance representing the user subscribed
        z %s/lists/subscribers/create.jsonr/  r  r   r   )	rA   r   r(  r   r   r   rt   r   r   r1  s	            re   CreateSubscriptionzApi.CreateSubscriptionQ  s    0 14==@
$,,w,0089J ' L 	M
 V*=))$,,*=*=g*FG##D))r~   c                    d| j                   z  }i }|j                  | j                  ||||             | j                  |d|      }| j	                  |j
                  j                  d            }t        j                  |      S )a)  Destroys the subscription to a list for the authenticated user.

        Args:
          owner_screen_name (str, optional):
            The screen_name of the user who owns the list being requested
            by a slug.
          owner_id (int, optional):
            The user ID of the user who owns the list being requested
            by a slug.
          list_id (int, optional):
            The numerical id of the list.
          slug (str, optional):
            You can identify a list by its slug instead of its numerical id.
            If you decide to do so, note that you'll also have to specify the
            list owner using the owner_id or owner_screen_name parameters.

        Returns:
          twitter.list.List: A twitter.List instance representing
          the removed list.
        z!%s/lists/subscribers/destroy.jsonr/  r  r   r   r0  r1  s	            re   DestroySubscriptionzApi.DestroySubscriptionv  s    2 2T]]C
$,,w,0089J ' L 	M
 V*=))$,,*=*=g*FG##D))r~   c
                 r   d| j                   z  }
i }|j                  | j                  ||||             |rt        dt        |      |d<   n|r||d<   |rd|d<   |rd|d<   | j                  |
d|	      }| j                  |j                  j                  d
            }|	r|S t        j                  |      S )a  Check if the specified user is a subscriber of the specified list.

        Returns the user if they are subscriber.

        Args:
          owner_screen_name (str, optional):
            The screen_name of the user who owns the list being requested
            by a slug.
          owner_id (int, optional):
            The user ID of the user who owns the list being requested
            by a slug.
          list_id (int, optional):
            The numerical ID of the list.
          slug (str, optional):
            You can identify a list by its slug instead of its numerical ID.
            If you decide to do so, note that you'll also have to specify
            the list owner using the owner_id or owner_screen_name parameters.
          user_id (int, optional):
            The user_id or a list of user_id's to add to the list.
            If not given, then screen_name is required.
          screen_name (str, optional):
            The screen_name or a list of screen_name's to add to the list.
            If not given, then user_id is required.
          include_entities (bool, optional):
            If False, the timeline will not contain additional metadata.
            Defaults to True.
          skip_status (bool, optional):
            If True the statuses will not be returned in the user items.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          twitter.user.User: A twitter.User instance representing the user
          requested.
        z%s/lists/subscribers/show.jsonr/  r   r   Tr  r   r   r   r   )rA   r   r(  r   r   r   r   r   rt   r   r   )rV   r'  r&  r%  r   r   r   r   r  r   rm   r   r   rn   s                 re   ShowSubscriptionzApi.ShowSubscription  s    Z /$--@
$,,w,0089J ' L 	M
 $,YW$EJy!(3J}%(,J}%-1J)*U<))$,,*=*=g*FGK''--r~   c                    d| j                   z  }i }t        dt        |      |d<   t        dt        |      |d<   |t        dt        |      |d<   n|||d<   | j                  |d|      }| j	                  |j
                  j                  d            }	|r|	S |	d	   D 
cg c]  }
t        j                  |
       c}
S c c}
w )
a  Obtain a collection of the lists the specified user is
        subscribed to. If neither user_id or screen_name is specified, the
        data returned will be for the authenticated user.

        The list will contain a maximum of 20 lists per page by default.

        Does not include the user's own lists.

        Args:
          user_id (int, optional):
            The ID of the user for whom to return results for.
          screen_name (str, optional):
            The screen name of the user for whom to return results for.
          count (int, optional):
           The amount of results to return per page.
           No more than 1000 results will ever be returned in a single
           page. Defaults to 20.
          cursor (int, optional):
            The "page" value that Twitter will use to start building the
            list sequence from. Use the value of -1 to start at the
            beginning. Twitter will return in the result the values for
            next_cursor and previous_cursor.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          twitter.list.List: A sequence of twitter.List instances,
          one for each list
        z%s/lists/subscriptions.jsonrt  r   r   r   r   r   r   lists)	rA   r   r   r   r   r   rt   r   r   )rV   r   r   r   rt  r   rm   r   r   rn   r   s              re   GetSubscriptionszApi.GetSubscriptions  s    F ,t}}=
'#v>
8&wU;
7$,YW$EJy!$(3J}%U<))$,,*=*=g*FGK59']CD((+CCCs   !C c                    d| j                   z  }i }|t        dt        |      |d<   |t        dt        |      |d<   |rt        dt        |      |d<   |t        dt        |      |d<   n|||d<   | j	                  |d|      }	| j                  |	j                  j                  d	            }
|r|
S |
d
   D cg c]  }t        j                  |       c}S c c}w )a  Obtain the lists the specified user is a member of. If no user_id or
        screen_name is specified, the data returned will be for the
        authenticated user.

        Returns a maximum of 20 lists per page by default.

        Args:
          user_id (int, optional):
            The ID of the user for whom to return results for.
          screen_name (str, optional):
            The screen name of the user for whom to return
            results for.
          count (int, optional):
           The amount of results to return per page.
           No more than 1000 results will ever be returned in a single page.
           Defaults to 20.
          cursor (int, optional):
            The "page" value that Twitter will use to start building the list
            sequence from. Use the value of -1 to start at the beginning.
            Twitter will return in the result the values for next_cursor and
            previous_cursor.
          filter_to_owned_lists (bool, optional):
            Set to True to return only the lists the authenticating user
            owns, and the user specified by user_id or screen_name is a
            member of. Default value is False.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          list: A list of twitter.List instances, one for each list in which
          the user specified by user_id or screen_name is a member
        z%s/lists/memberships.jsonrt  r   filter_to_owned_listsr   r   r   r   r   r:  
rA   r   r   r   r   r   r   rt   r   r   )rV   r   r   r   rt  r=  r   rm   r   r   rn   r   s               re   GetMembershipszApi.GetMemberships  s    N *T]];
#+Hc6#BJx "*7C"?Jw 2:'/D3FJ./ $,YW$EJy!$(3J}%U<))$,,*=*=g*FGK59']CD((+CCCs   ;Cc                 `   d| j                   z  }i }|rt        dt        |      |d<   n|r||d<   |rt        dt        |      |d<   | j	                  |d|      }| j                  |j                  j                  d            }|r|S |D 	cg c]  }	t        j                  |	       c}	S c c}	w )a  Returns all lists the user subscribes to, including their own.
        If no user_id or screen_name is specified, the data returned will be
        for the authenticated user.

        Args:
          screen_name (str, optional):
            Specifies the screen name of the user for whom to return the
            user_timeline. Helpful for disambiguating when a valid screen
            name is also a user ID.
          user_id (int, optional):
            Specifies the ID of the user for whom to return the
            user_timeline. Helpful for disambiguating when a valid user ID
            is also a valid screen name.
          reverse (bool, optional):
            If False, the owned lists will be returned first, othewise
            subscribed lists will be at the top. Returns a maximum of 100
            entries regardless. Defaults to False.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          list: A sequence of twitter.List instances.
        z%s/lists/list.jsonr   r   reverser   r   r   r>  )
rV   r   r   rA  r   rm   r   r   rn   r   s
             re   GetListsListzApi.GetListsListT  s    8 #dmm4
$,YW$EJy!(3J}%$,Yg$FJy!U<))$,,*=*=g*FGK59:D((+:::s   B+c                    d| j                   z  }i }|j                  | j                  ||||             |rt        dt        |      |d<   |rt        dt        |      |d<   |rt        dt        |      |d<   |st        dt
        |      |d<   |	st        dt
        |	      |d<   | j                  |d|	      }| j                  |j                  j                  d
            }|
r|S |D cg c]  }t        j                  |       c}S c c}w )a  Fetch the sequence of Status messages for a given List ID.

        Args:
          list_id (int, optional):
            Specifies the ID of the list to retrieve.
          slug (str, optional):
            The slug name for the list to retrieve. If you specify None for the
            list_id, then you have to provide either a owner_screen_name or
            owner_id.
          owner_id (int, optional):
            Specifies the ID of the user for whom to return the
            list timeline. Helpful for disambiguating when a valid user ID
            is also a valid screen name.
          owner_screen_name (str, optional):
            Specifies the screen name of the user for whom to return the
            user_timeline. Helpful for disambiguating when a valid screen
            name is also a user ID.
          since_id (int, optional):
            Returns results with an ID greater than (that is, more recent than)
            the specified ID. There are limits to the number of Tweets which
            can be accessed through the API.
            If the limit of Tweets has occurred since the since_id, the
            since_id will be forced to the oldest ID available.
          max_id (int, optional):
            Returns only statuses with an ID less than (that is, older than) or
            equal to the specified ID.
          count (int, optional):
            Specifies the number of statuses to retrieve.
            May not be greater than 200.
          include_rts (bool, optional):
            If True, the timeline will contain native retweets (if they exist)
            in addition to the standard stream of tweets.
          include_entities (bool, optional):
            If False, the timeline will not contain additional metadata.
            Defaults to True.
          return_json (bool, optional):
            If True JSON data will be returned, instead of twitter.User

        Returns:
          list: A list of twitter.status.Status instances, one for each
          message up to count.
        z%s/lists/statuses.jsonr/  r   r   r   r   r   r   r   r   )rA   r   r(  r   r   r   r   r   r   rt   r   r   )rV   r%  r   r&  r'  r   r   r   r   r   r   rm   r   r   rn   r   s                   re   GetListTimelinezApi.GetListTimeline  s   j '6
$,,w,0089J ' L 	M
 %-j#x%HJz"#+Hc6#BJx "*7C"?Jw(0k(RJ}%-56H$P`-aJ)*U<))$,,*=*=g*FGK7;<!F**1-<<<s   *D	c	                 P   d| j                   z  }	i }
|
j                  | j                  ||||             |rt        dt        |      |
d<   |rt        dt        |      |
d<   t        dt
        |      |
d<   t        dt
        |      |
d<   | j                  |	d|
      }| j                  |j                  j                  d	            }|j                  d
d      }|j                  dd      }|j                  dg       D cg c]  }t        j                  |       }}|||fS c c}w )a  Fetch the sequence of twitter.User instances, one for each member
        of the given list_id or slug.

        Args:
          list_id (int, optional):
            Specifies the ID of the list to retrieve.
          slug (str, optional):
            The slug name for the list to retrieve. If you specify None for the
            list_id, then you have to provide either a owner_screen_name or
            owner_id.
          owner_id (int, optional):
            Specifies the ID of the user for whom to return the
            list timeline. Helpful for disambiguating when a valid user ID
            is also a valid screen name.
          owner_screen_name (str, optional):
            Specifies the screen name of the user for whom to return the
            user_timeline. Helpful for disambiguating when a valid screen
            name is also a user ID.
          cursor (int, optional):
            Should be set to -1 for the initial call and then is used to
            control what result page Twitter returns.
          skip_status (bool, optional):
            If True the statuses will not be returned in the user items.
          include_entities (bool, optional):
            If False, the timeline will not contain additional metadata.
            Defaults to True.

        Returns:
          list: A sequence of twitter.user.User instances, one for each
          member of the twitter.list.List.
        z%s/lists/members.jsonr/  r   rt  r  r   r   r   r   rw  r   rx  r   )rA   r   r(  r   r   r   r   r   r   rt   r   r   r   )rV   r%  r   r&  r'  rt  r   r  r   rm   r   r   rn   rw  rx  r   r   s                    re   GetListMembersPagedzApi.GetListMembersPaged  s-   P &5
$,,w,0089J ' L 	M
 "*7C"?Jw#+Hc6#BJx $,]D+$N
=!)12DdL\)]
%&U<))$,,*=*=g*FGhh}a0((#4a88<"8MN%%d+NNOU22 Os    D#c           	      n    d}g }	 | j                  |||||||      \  }	}
}||z  }|	dk(  s|	|
k(  r	 |S |	}1)a  Fetch the sequence of twitter.User instances, one for each member
        of the given list_id or slug.

        Args:
          list_id (int, optional):
            Specifies the ID of the list to retrieve.
          slug (str, optional):
            The slug name for the list to retrieve. If you specify None for the
            list_id, then you have to provide either a owner_screen_name or
            owner_id.
          owner_id (int, optional):
            Specifies the ID of the user for whom to return the
            list timeline. Helpful for disambiguating when a valid user ID
            is also a valid screen name.
          owner_screen_name (str, optional):
            Specifies the screen name of the user for whom to return the
            user_timeline. Helpful for disambiguating when a valid screen
            name is also a user ID.
          skip_status (bool, optional):
            If True the statuses will not be returned in the user items.
          include_entities (bool, optional):
            If False, the timeline will not contain additional metadata.
            Defaults to True.

        Returns:
          list: A sequence of twitter.user.User instances, one for each
          member of the twitter.list.List.
        r^  )r%  r   r&  r'  rt  r  r   r   )rF  )rV   r%  r   r&  r'  r  r   rt  r   rw  rx  r   s               re   GetListMemberszApi.GetListMembers  st    F 262J2J!"3'!1 3K 33/K% eOFa;/#A  % r~   c           
         d}i }|j                  | j                  ||||             |rst        |t              st        |t              r>d}|D 	cg c]  }	t        t        dt        |	             }
}	dj                  |
      |d<   nSt        dt        |      |d<   n>|r<t        |t              st        |t              rd}dj                  |      |d<   n||d<   |rd| j                  z  }nd| j                  z  }| j                  |d	|
      }| j                  |j                  j                  d            }t        j                  |      S c c}	w )ap  Add a new member (or list of members) to the specified list.

        Args:
          list_id (int, optional):
            The numerical id of the list.
          slug (str, optional):
            You can identify a list by its slug instead of its numerical id.
            If you decide to do so, note that you'll also have to specify the
            list owner using the owner_id or owner_screen_name parameters.
          user_id (int, optional):
            The user_id or a list of user_id's to add to the list.
            If not given, then screen_name is required.
          screen_name (str, optional):
            The screen_name or a list of screen_name's to add to the list.
            If not given, then user_id is required.
          owner_screen_name (str, optional):
            The screen_name of the user who owns the list being requested by
            a slug.
          owner_id (int, optional):
            The user ID of the user who owns the list being requested by
            a slug.

        Returns:
          twitter.list.List: A twitter.List instance representing the list
          subscribed to.
        Fr/  Tr   r   r   z %s/lists/members/create_all.jsonz%s/lists/members/create.jsonr  r   r   r   r(  r   r   r   r   r   r   r   rA   r   r   r   rt   r   r   )rV   r%  r   r   r   r'  r&  is_listr   r  r  rm   r   rn   s                 re   CreateListsMemberzApi.CreateListsMemberH  sA   B 
$,,w,0089J ' L 	M
 '4(Jw,FFMNsHYS9:NN(+
9%(0C(I
9%+t,
;0N,/HH[,A
=),7
=)4t}}DC04==@CV*=))$,,*=*=g*FG##D))' Os   !Ec           
         d}i }|j                  | j                  ||||             |rmt        |t              st        |t              r>d}|D 	cg c]  }	t        t        dt        |	             }
}	dj                  |
      |d<   nMt        |      |d<   n>|r<t        |t              st        |t              rd}dj                  |      |d<   n||d<   |rd| j                  z  }nd| j                  z  }| j                  |d	|
      }| j                  |j                  j                  d            }t        j                  |      S c c}	w )ak  Destroys the subscription to a list for the authenticated user.

        Args:
          list_id (int, optional):
            The numerical id of the list.
          slug (str, optional):
            You can identify a list by its slug instead of its numerical id.
            If you decide to do so, note that you'll also have to specify
            the list owner using the owner_id or owner_screen_name parameters.
          owner_screen_name (str, optional):
            The screen_name of the user who owns the list being requested by a
            slug.
          owner_id (int, optional):
            The user ID of the user who owns the list being requested by a slug.
          user_id (int, optional):
            The user_id or a list of user_id's to remove from the list.
            If not given, then screen_name is required.
          screen_name (str, optional):
            The screen_name or a list of Screen_name's to remove from the list.
            If not given, then user_id is required.

        Returns:
          twitter.list.List: A twitter.List instance representing the
          removed list.
        Fr/  Tr   r   r   z!%s/lists/members/destroy_all.jsonz%s/lists/members/destroy.jsonr  r   r   rJ  )rV   r%  r   r'  r&  r   r   rK  r   r  r  rm   r   rn   s                 re   DestroyListsMemberzApi.DestroyListsMember  s<   @ 
$,,w,0089J ' L 	M
 '4(Jw,FFMNsHYS9:NN(+
9%(+G
9%+t,
;0N,/HH[,A
=),7
=)5EC1DMMACV*=))$,,*=*=g*FG##D))' Os   !E
c                    d| j                   z  }i }|t        dt        |      |d<   n|||d<   |t        dt        |      |d<   t        dt        |      |d<   | j                  |d|      }| j	                  |j
                  j                  d            }|j                  d	d
      }	|j                  dd
      }
|j                  dg       D cg c]  }t        j                  |       }}|	|
|fS c c}w )a   Fetch the sequence of lists for a user. If no user_id or
        screen_name is passed, the data returned will be for the
        authenticated user.

        Args:
          user_id (int, optional):
            The ID of the user for whom to return results for.
          screen_name (str, optional):
            The screen name of the user for whom to return results
            for.
          count (int, optional):
            The amount of results to return per page. No more than 1000 results
            will ever be returned in a single page. Defaults to 20.
          cursor (int, optional):
            The "page" value that Twitter will use to start building the list
            sequence from. Use the value of -1 to start at the beginning.
            Twitter will return in the result the values for next_cursor and
            previous_cursor.

        Returns:
          next_cursor (int), previous_cursor (int), list of twitter.List
          instances, one for each list
        z%s/lists/ownerships.jsonr   r   r   rt  r   r   r   rw  r   rx  r:  )
rA   r   r   r   r   r   rt   r   r   r   )rV   r   r   rt  r   rm   r   r   rn   rw  rx  r   r:  s                re   GetListsPagedzApi.GetListsPaged  s    8 )4==8
$,YW$EJy!$(3J}%"*7C"?Jw'#v>
8U<))$,,*=*=g*FGhh}a0((#4a826((7B2GHQ%%a(HHOU22 Is   C3c                 f    g }d}	 | j                  |||      \  }}}||z  }|dk(  s||k(  r	 |S |}-)a  Fetch the sequence of lists for a user. If no user_id or screen_name
        is passed, the data returned will be for the authenticated user.

        Args:
          user_id:
            The ID of the user for whom to return results for. [Optional]
          screen_name:
            The screen name of the user for whom to return results
            for. [Optional]
          count:
            The amount of results to return per page.
            No more than 1000 results will ever be returned in a single page.
            Defaults to 20. [Optional]
          cursor:
            The "page" value that Twitter will use to start building the list
            sequence from. Use the value of -1 to start at the beginning.
            Twitter will return in the result the values for next_cursor and
            previous_cursor. [Optional]

        Returns:
          A sequence of twitter.List instances, one for each list
        r^  )r   r   rt  r   )rP  )rV   r   r   r   rt  rw  prev_cursorr:  s           re   GetListszApi.GetLists  sg    2 .2.@.@' /A /+Ke eOFa;+#=  % r~   c                     d| j                   z  }|||||||d}	| j                  |d|	      }
| j                  |
j                  j	                  d            }	t        j                  |	      S )a1  Update's the authenticated user's profile data.

        Args:
          name (str, optional):
            Full name associated with the profile.
          profileURL (str, optional):
            URL associated with the profile.
            Will be prepended with "http://" if not present.
          location (str, optional):
            The city or country describing where the user of the account is located.
            The contents are not normalized or geocoded in any way.
          description (str, optional):
            A description of the user owning the account.
          profile_link_color (str, optional):
            hex value of profile color theme. formated without '#' or '0x'. Ex:  FF00FF
          include_entities (bool, optional):
            The entities node will be omitted when set to False.
          skip_status (bool, optional):
            When set to either True, t or 1 then statuses will not be included
            in the returned user objects.

        Returns:
          A twitter.User instance representing the modified user.
        z%s/account/update_profile.json)r*  rm   locationr,  profile_link_colorr   r  r  r   r   )rA   r   r   r   rt   r   r   )rV   r*  
profileURLrU  r,  rV  r   r  rm   rn   r   s              re   UpdateProfilezApi.UpdateProfile#  sx    @ /$--@ &"4 0&
 V$7))$,,*=*=g*FG##D))r~   c                    d| j                   z  }t        |d      5 }t        j                  |j	                               }ddd       di}|rd|d<   |rd|d<   | j                  |d|	      }|j                  d
v ry|j                  dk(  rt        ddi      |j                  dk(  rt        ddi      y# 1 sw Y   wxY w)a  Update a User's profile image. Change may not be immediately
        reflected due to image processing on Twitter's side.

        Args:
            image (str):
                Location of local image file to use.
            include_entities (bool, optional):
                Include the entities node in the return data.
            skip_status (bool, optional):
                Include the User's last Status in the User entity returned.

        Returns:
            (twitter.models.User): Updated User object.
        z$%s/account/update_profile_image.jsonrbNimager'   r   r  r  r   r         T  r&   !Image data could not be processed  /The image could not be resized or is too large.rA   openrp   rq   r1  r   status_coder   	rV   r[  r   r  rm   
image_fileencoded_imagern   r   s	            re   UpdateImagezApi.UpdateImageS  s    & 5F% 	@*",,Z__->?M	@ ]
 '(D#$"#DV$7.s"	+NOPPs"	+\]^^ #!	@ 	@s   $B66B?c                    d| j                   z  }t        |d      5 }t        j                  |j	                               }ddd       di}|rd|d<   |rd|d<   | j                  |d|	      }|j                  d
v ry|j                  dk(  rt        ddi      |j                  dk(  rt        ddi      t        ddi      # 1 sw Y   xY w)a  Updates the authenticated users profile banner.

        Args:
          image:
            Location of image in file system
          include_entities:
            If True, each tweet will include a node called "entities."
            This node offers a variety of metadata about the tweet in a
            discrete structure, including: user_mentions, urls, and hashtags.
            [Optional]

        Returns:
          A twitter.List instance representing the list subscribed to
        z%%s/account/update_profile_banner.jsonrZ  Nbannerr'   r   r  r  r   r\  Tr_  r&   r`  ra  rb  z Unkown banner image upload issuerc  rf  s	            re   UpdateBannerzApi.UpdateBannerz  s    $ 6G% 	@*",,Z__->?M	@ m	
 '(D#$"#DV$7.s"	+NOPPs"	+\]^^I'IJKK-	@ 	@s   $CCc              #      K   d| j                   z  }t        |      t        |      d}| j                  |d|      }|j                         D ])  }|s| j	                  |j                  d            }| + yw)a  Returns a small sample of public statuses.

        Args:
          delimited:
            Specifies a message length. [Optional]
          stall_warnings:
            Set to True to have Twitter deliver stall warnings. [Optional]

        Returns:
          A Twitter stream
        z%s/statuses/sample.json)	delimitedstall_warningsr   r   r   N)rB   r   _RequestStream
iter_linesr   rt   )rV   rn  ro  rm   r   r   rW  rn   s           re   GetStreamSamplezApi.GetStreamSample  s|      ($//9i">2

 ""3J"?OO% 	D11$++g2FG
	s   AA:'A:c              #     K   t        |du |du |du f      rt        ddi      d| j                  z  }i }	|dj                  |      |	d<   |dj                  |      |	d<   |dj                  |      |	d<   |t	        |      |	d	<   |t	        |      |	d
<   |dj                  |      |	d<   |||	d<   | j                  |d|	      }
|
j                         D ])  }|s| j                  |j                  d            }	|	 + yw)a  Returns a filtered view of public statuses.

        Args:
          follow:
            A list of user IDs to track. [Optional]
          track:
            A list of expressions to track. [Optional]
          locations:
            A list of Longitude,Latitude pairs (as strings) specifying
            bounding boxes for the tweets' origin. [Optional]
          delimited:
            Specifies a message length. [Optional]
          stall_warnings:
            Set to True to have Twitter deliver stall warnings. [Optional]
          languages:
            A list of Languages.
            Will only return Tweets that have been detected as being
            written in the specified languages. [Optional]
          filter_level:
            Specifies level of filtering applied to stream.
            Set to None, 'low' or 'medium'. [Optional]

        Returns:
          A twitter stream
        Nr&   zNo filter parameters specified.z%s/statuses/filter.jsonr   r  track	locationsrn  ro  languagefilter_levelr  r   r   )	rE   r   rB   r   r   rp  rq  r   rt   )rV   r  rt  ru  	languagesrn  ro  rw  rm   rn   r   rW  s               re   GetStreamFilterzApi.GetStreamFilter  s2    B $yD/@ABi)JKLL'$//9 XXf-DNHHUODM  # 3D  #ID%%(%8D!" "xx	2D##/D ""3T":OO% 	D11$++g2FG
	s   CD'Dc              #     K   d}i }|rd|d<   |||d<   |||d<   |dj                  |      |d<   |dj                  |      |d	<   |t        |      |d
<   |t        |      |d<   |||d<   | j                  |d||	      }|j                         D ]0  }|r%| j	                  |j                  d            }| *|
s-d 2 yw)aZ  Returns the data from the user stream.

        Args:
          replies:
            Specifies whether to return additional @replies in the stream.
            Defaults to 'all'.
          withuser:
            Specifies whether to return information for just the authenticating
            user, or include messages from accounts the user follows. [Optional]
          track:
            A list of expressions to track. [Optional]
          locations:
            A list of Latitude,Longitude pairs (as strings) specifying
            bounding boxes for the tweets' origin. [Optional]
          delimited:
            Specifies a message length. [Optional]
          stall_warnings:
            Set to True to have Twitter deliver stall warnings. [Optional]
          stringify_friend_ids:
            Specifies whether to send the friends list preamble as an array of
            integers or an array of strings. [Optional]
          filter_level:
            Specifies level of filtering applied to stream.
            Set to None, low or medium. [Optional]

        Returns:
          A twitter stream
        z,https://userstream.twitter.com/1.1/user.jsonr   stringify_friend_idsNreplieswithr   rt  ru  rn  ro  rw  r  )rn   sessionr   )r   r   rp  rq  r   rt   )rV   r|  withuserrt  ru  rn  ro  r{  rw  r~  include_keepaliverm   rn   r   rW  s                  re   GetUserStreamzApi.GetUserStream  s    N =+1D'(%DO#DLHHUODM  # 3D  #ID%%(%8D!"##/D ""3T7"K OO% 	D11$++g2FG
"
	s   B>CCc                 2   d| j                   z  }t        dt        |      t        dt        |      t        dt        |      rdndd}| j                  |d|      }| j	                  |j
                  j                  d	            }t        j                  |      S )
a  Returns a twitter.User instance if the authenticating user is valid.

        Args:
          include_entities:
            Specifies whether to return additional @replies in the stream.
          skip_status:
            When set to either true, t or 1 statuses will not be included in the
            returned user object.
          include_email:
            Use of this parameter requires whitelisting.
            When set to true email will be returned in the user objects as a string.
            If the user does not have an email address on their account, or if the
            email address is un-verified, null will be returned. If your app is
            not whitelisted, then the 'email' key will not be present in the json
            response.

        Returns:
          A twitter.User instance representing that user if the
          credentials are valid, None otherwise.
        z"%s/account/verify_credentials.jsonr   r  include_emailr   r   )r   r  r  r   r   )	rA   r   r   r   r   r   rt   r   r   )rV   r   r  r  rm   rn   r   s          re   VerifyCredentialszApi.VerifyCredentials?  s    * 3T]]B ();TCS T#M4E'/}'UV[b
 UD1))$,,*=*=g*FG##D))r~   c                 D    |t         k(  rt               | _        y|| _        y)zOverride the default cache.  Set to None to prevent caching.

        Args:
          cache:
            An instance that supports the same API as the twitter._FileCache
        N)DEFAULT_CACHEr   _cache)rV   r^   s     re   r/   zApi.SetCache`  s     M!$,DKDKr~   c                     || _         y)zOverride the default urllib implementation.

        Args:
          urllib:
            An instance that supports the same API as the urllib2 module
        N)_urllib)rV   urllibs     re   	SetUrllibzApi.SetUrllibl  s     r~   c                     || _         y)zOverride the default cache timeout.

        Args:
          cache_timeout:
            Time, in seconds, that responses should be reused.
        N)r1   )rV   cache_timeouts     re   SetCacheTimeoutzApi.SetCacheTimeoutu  s     ,r~   c                 "    || j                   d<   y)zOverride the default user agent.

        Args:
          user_agent:
            A string that should be send to the server as the user-agent.
        z
User-AgentN_request_headersrV   
user_agents     re   SetUserAgentzApi.SetUserAgent~  s     /9l+r~   c                 ^    || j                   d<   || j                   d<   || j                   d<   y)a  Set the X-Twitter HTTP headers that will be sent to the server.

        Args:
          client:
             The client name as a string.  Will be sent to the server as
             the 'X-Twitter-Client' header.
          url:
             The URL of the meta.xml as a string.  Will be sent to the server
             as the 'X-Twitter-Client-URL' header.
          version:
             The client version as a string.  Will be sent to the server
             as the 'X-Twitter-Client-Version' header.
        zX-Twitter-ClientzX-Twitter-Client-URLzX-Twitter-Client-VersionNr  )rV   rH   rm   versions       re   SetXTwitterHeaderszApi.SetXTwitterHeaders  s7     5;018;45<C89r~   c                 "    || j                   d<   y)a  Suggest the "from source" value to be displayed on the Twitter web site.

        The value of the 'source' parameter must be first recognized by
        the Twitter server.

        New source values are authorized on a case by case basis by the
        Twitter development team.

        Args:
          source:
            The source name as a string.  Will be sent to the server as
            the 'source' parameter.
        sourceN_default_params)rV   r  s     re   	SetSourcezApi.SetSource  s     *0X&r~   c                    | j                   }| j                   rd| _         d| j                  z  }| j                  |d      }| j                  |j                  j                  d            }|| _         t        di || _        y)z Make a call to the Twitter API to get the rate limit
        status for the currently authenticated user or application.

        Returns:
            None.

        Fz%%s/application/rate_limit_status.jsonr   r   Nr_  )r>   rA   r   r   r   rt   r   r=   )rV   _sleeprm   r   rn   s        re   InitializeRateLimitzApi.InitializeRateLimit  sv     ))##',D$5EU+))$,,*=*=g*FG#) #+d+r~   c                     | j                   j                  j                  dd      s| j                          |r| j                   j	                  |      }S )z Checks a URL to see the rate limit status for that endpoint.

        Args:
            url (str):
                URL to check against the current rate limits.

        Returns:
            namedtuple: EndpointRateLimit namedtuple.

        	resourcesN)r=   __dict__r   r  	get_limit)rV   rm   limits      re   CheckRateLimitzApi.CheckRateLimit  sF     ''++K>$$&OO--c2Er~   c                 *   t        |      \  }}}}}}	|r<|D 
cg c]  }
|
s|
	 }}
|j                  d      s|dz  }|dj                  |      z  }|r,t        |      dkD  r| j	                  |      }|r	|d|z   z  }n|}t        ||||||	f      S c c}
w )N/r   &)r   endswithr   r   _EncodeParametersr	   )rV   rm   path_elementsextra_paramsschemenetlocpathparamsqueryfragmentifiltered_elementsextra_querys                re   	_BuildUrlzApi._BuildUrl  s    :B3-7vuh ,9 ?qQ ? ?==%CHH.//D C-100>K{**# 664IJJ !@s
   BBc                 &    |r|| _         y i | _         y Nr  )rV   r]   s     re   r:   zApi._InitializeRequestHeaders  s    $3D!$&D!r~   c                 H    dt         dt        d}| j                  |       y )NzPython-urllib/z (python-twitter/))urllib_versionr   r  r  s     re   r;   zApi._InitializeUserAgent  s    $k3
*%r~   c                     i | _         y r  r  r   s    re   r<   z Api._InitializeDefaultParameters  s
    !r~   c                     | j                         }| j                  j                  dd       dk(  r9t        j                  t        j                  |            j                         }|S |}|S )Nzcontent-encodinggzip)fileobj)r1  ro   r   r  GzipFileioStringIO)responseraw_dataurl_datas      re   _DecompressGzippedResponsezApi._DecompressGzippedResponse  s\    ==? 2D9VC}}R[[-BCHHJH   Hr~   c                     | yt        | t              st        d      t               }| j                         D ]9  \  }}|	t	        |dd      r|j                  d      }|j                  ||i       ; t        |      S )a[  Return a string in key=value&key=value form.

        Values of None are not included in the output string.

        Args:
          parameters (dict): dictionary of query parameters to be converted into a
          string for encoding and sending to Twitter.

        Returns:
          A URL-encoded string in "key=value&key=value" form
        Nz`parameters` must be a dict.rs   rh   )r   dictr   r   getattrrs   r   r
   )r   r  kvs       re   r  zApi._EncodeParameters  s     *d+=>>VF"((* *1=q(D1HHV,MM1a&)	*
 V$$r~   c                 .   	 t        j                  |      }| j                  |       |S # t        $ ra d|v rt        ddi      d|v rt        ddi      d|v rt        ddi      d|v rt        ddi      t        d	d
j	                  |      i      w xY w)zTry and parse the JSON returned from Twitter and return
        an empty dictionary if there is any error.

        This is a purely defensive check because during some Twitter
        network outages it will return an HTML failwhale page.
        z&<title>Twitter / Over capacity</title>r&   zCapacity Errorz<title>Twitter / Error</title>zTechnical Errorz"Exceeded connection limit for userzError 401 UnauthorizedUnauthorizedzUnknown errorz{0})rv   loadsr   r   rr   _CheckForTwitterError)rV   	json_datarn   s      re   r   zApi._ParseAndCheckTwitter  s    	K::i(D 	""4(  		K79D"I/?#@AA/9<"I/@#ABB3y@"I/S#TUU'94"I~#>??i1HIJJ		Ks
   * A*Bc                 L    d| v rt        | d         d| v rt        | d         y)a0  Raises a TwitterError if twitter returns an error message.

        Args:
            data (dict):
                A python dict created from the Twitter json response

        Raises:
            (twitter.TwitterError): TwitterError wrapping the twitter error
            message if one exists.
        errorerrorsN)r   r   s    re   r  zApi._CheckForTwitterError/  s6     d?tG}--ttH~.. r~   c                     	 t        j                  |||| j                  | j                  | j                        S # t         j
                  $ r}t        t        |            d }~ww xY w)N)ro   rn   authra   r@   )rS   ru   r9   r8   r@   RequestExceptionr   r   )rV   rm   ro   rn   rK  s        re   rC  zApi._RequestChunkedUploadB  s]    
	'==[[  (( 	's1v&&	's   8; A'A""A'c                    |r| j                   st        d      |r| j                  r| j                  |      }|j                  dk(  rd	 t        t        |j                  t        j                         z
        dz   d      }t        j                  d||       t        j                  |       |si }|dk(  r$|rd|v rX| j                  |d|d   i      }| j                  j                  ||| j                   | j                   | j"                        }n-d	|v r?| j                  j                  ||| j                   | j                   | j"                  
      }n| j                  j                  ||| j                   | j                   | j"                        }n|r?| j                  j                  ||| j                   | j                   | j"                        }njd}ng|dk(  r`| j$                  |d<   | j                  ||      }| j                  j'                  || j                   | j                   | j"                        }nd}|r~| j(                  rr|j*                  j'                  dd      }|j*                  j'                  dd      }	|j*                  j'                  dd      }
| j(                  j-                  |||	|
       |S # t        $ r Y #w xY w)a  Request a url.

        Args:
            url:
                The web location we want to retrieve.
            verb:
                Either POST or GET.
            data:
                A dict of (str, unicode) key/value pairs.

        Returns:
            A JSON object.
        z/The twitter.Api instance must be authenticated.r   
   z/Rate limited requesting [%s], sleeping for [%s]r  r  r  )rn   r  ra   r@   r  )filesr  ra   r@   )rv   r  ra   r@   r   r?   )r  ra   r@   zx-rate-limit-limitzx-rate-limit-remainingzx-rate-limit-reset)r9   r   r>   r  	remainingmaxr   resettimeloggerdebugsleepr   r  rU   ru   r8   r@   r?   r   r=   ro   	set_limit)rV   rm   r   rn   rv   r  r  stimer   r  r  s              re   r   zApi._RequestUrlO  so    ;;"#TUUt//++C0??a' #Cdiik(A$BR$G K%VX[]bc

5) D6>$&..KkIZ;[.\C==--c4;;X\XeXeoso{o{-|D_==--cDKKY]YfYfptp|p|-}D==--c4;;X\XeXeoso{o{-|D}}))#Dt{{TXTaTakokwkw)xU]!%D..4.8C==$$St{{DMM[_[g[g$hD D4??LL$$%91=E(()A1EILL$$%91=EOO%%c5)UCG & s   	A#K 	KKc                     |xs t        j                         }|dk(  r6	 |j                  ||d| j                  | j                  | j
                        S |dk(  rH| j                  ||      }	 |j                  |d| j                  | j                  | j
                        S y# t         j                  $ r}t        t        |            d}~ww xY w# t         j                  $ r}t        t        |            d}~ww xY w)	a1  Request a stream of data.

           Args:
             url:
               The web location we want to retrieve.
             verb:
               Either POST or GET.
             data:
               A dict of (str, unicode) key/value pairs.

           Returns:
             A twitter stream.
        r  T)rn   streamr  ra   r@   Nr   r  )r  r  ra   r@   r   )rS   rT   ru   r9   r8   r@   r  r   r   r  r   )rV   rm   r   rn   r~  rK  s         re   rp  zApi._RequestStream  s     /X--/6>+||Cd4)-,0MM,0LL $ : : 5=..4.8C+{{3t$+++/==$,, # P P  ,, +"3q6**+ ,, +"3q6**+s/   4B" -3C "C5C		CC=$C88C=)NNF)F)NNNNNNN   NNr   NF)Nr'      Nr  )NNNFFFT)NNNNNTFF)FTTT)FTF)	NNNFFFNNN)NNNNFNNNNFFTN)NN)NNNF)NF)Nr   F)NNNFTT)r^  FTF)FF)r^  FF)r^  F)NNTF)NNr^  Fr  )NNNNNFN)NNNFNN)NNNNFN)NNNr^  r   FT)NNr^  r   FT)NNNNNNFT)NNNNNFT)NNNTF)NNNTFFNF)NNNNTF)TF)NNTT)NNr  r  T)NNNN)NNT)NNNNNTF)NNNFFTF)	NNNNNNFFF)NNr  r^  F)NNr  r^  FF)NNFF)
NNNNNNNTTF)NNNNr^  r   FT)NNNNFF)NNNNNN)NNr^  r  )NNNNNFF)FT)NNNNNNN)
rE   r   NNNNFNNF)NNN)__name__
__module____qualname____doc__r0   
_API_REALMr  rf   staticmethodr}   rF   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r
  r,  r  r8  r?  rL  rO  r  r  r\  re  rg  rk  rm  rq  rz  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r!  r#  r(  r-  r2  r4  r6  r8  r;  r?  rB  rD  rF  rH  rL  rN  rP  rS  rX  ri  rl  rr  ry  r  r  r/   r  r  r  r  r  r  r  r  r:   r;   r<   r  r  r   r  rC  r   rp  r_  r~   re   r   r   S   sU   :x J #!%"&%)', $!%$  '&+ %*$%T+l  , )-+/-2%N .   %#'#HQV !(,	/7b=: & #!%#"'(-,1)-P9f !%$(!%#"$("'(-G9V "%)#''+),Z $%)	6r #' !%#($)$)" $!Pd,< +/"&)-05*. ! ',"(,"&Z,| -1)-+L^ $(2 37/32.hIV0 .2*.&?T !0&T "&(T,< #!%#"'	!H !"	N@ #9D "$)	1h #!%#"')-.2/9h %')..2+0;4| $#(@ !#((-L6 $)8 "$(-F, #"'@  "'',L8 #(8 !#',F0  #$($8*v ! $%) %	8: "!%&*!&	8:  #$($	8: ! $%) %	88$4N %)(,#%*/"&'.T #'&*!#(- $'(T #'&**.%)$(,1*.'T  $#'"%*!#')CX "!% #(!%*7Z '+*..2)+(+.38<O3d #'&*!# #&+04'ET !%$(!!$).2'ET "&%))-$(#')-).37Rj "!% !%!&+/-@`  ##$)-.@b ! $%) %8;v  !%!	&.R $(!% $+/&+$)#&+BDJ (,%)$(#'/3*/6Dt #'&*&+	3j7<3. &*)-%-(0$(*6 "&%) $"&	3>*6 '+*.&**.	&R "&%)%*AAH #')-*Z #')-*Z #!%(, ,F  $"&)-!,H "!%" &*!&==@ !#(-%) %==~  **6 '+! 	%*P .2$(#' $	#*L /3%)$(!%	$*N ,0"&!%"!%%)*/%*%*D.N "&%)! "%*2Dj  $#' -2#(<D~ "&!"!&	+;\ !%!!%*.!%#"$()-$)N=b %)!%%).2#%"%(--1>3B  $  $)-#((-5p #'#"&&*,0#'?*D $( $-1$(#''+>*B #"&	/3d !'T  !%#"&)-',"'.*d &+ %%_R ',!&)LV0  $""&"&"&'+%)8v $%  $ $%)+0#'"(-GR*B
 ,9D$0 ,(&K0'&
"   % %2, / /$'=~r~   r   )<r  
__future__r   r   rv   sysr  r  rp   rS  rM   rS   requests_oauthlibr   r   r  r6   uuidr   r(   urllib.parser   r	   r
   r   urllib.requestr   r  rI   r  twitterr   r   r   r   r   r   r   r   twitter.ratelimitr   twitter.twitter_utilsr   r   r   r   r   twitter.errorr   r   version_infor   r  r  objectr  rO   r  r  r   r_  r~   re   <module>r     s   & D  %  
    	   , 	   	5HH<
 
 
 ( 
 dD 			8	$ZM& ZMU  5-,45s   
C C$#C$