示例#1
0
    def filter(self, *, follow=None, track=None, locations=None,
               filter_level=None, languages=None, stall_warnings=False,
               threaded=False):
        if self.running:
            raise TweepyException("Stream is already connected")

        method = "POST"
        endpoint = "statuses/filter"
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        body = {}
        if follow:
            body["follow"] = ','.join(map(str, follow))
        if track:
            body["track"] = ','.join(map(str, track))
        if locations and len(locations) > 0:
            if len(locations) % 4:
                raise TweepyException(
                    "Number of location coordinates should be a multiple of 4"
                )
            body["locations"] = ','.join(f"{l:.4f}" for l in locations)
        if filter_level:
            body["filter_level"] = filter_level
        if languages:
            body["language"] = ','.join(map(str, languages))
        if stall_warnings:
            body["stall_warnings"] = stall_warnings

        if threaded:
            return self._threaded_connect(method, endpoint, headers=headers,
                                          body=body)
        else:
            self._connect(method, endpoint, headers=headers, body=body)
示例#2
0
    def parse(self, payload, *, api=None, payload_list=False,
              payload_type=None, return_cursors=False):
        try:
            if payload_type is None:
                return
            model = getattr(self.model_factory, payload_type)
        except AttributeError:
            raise TweepyException(
                f'No model for this payload type: {payload_type}'
            )

        json = JSONParser.parse(self, payload, return_cursors=return_cursors)
        if isinstance(json, tuple):
            json, cursors = json
        else:
            cursors = None

        try:
            if payload_list:
                result = model.parse_list(api, json)
            else:
                result = model.parse(api, json)
        except KeyError:
            raise TweepyException(
                f"Unable to parse response payload: {json}"
            ) from None

        if cursors:
            return result, cursors
        else:
            return result
示例#3
0
文件: cursor.py 项目: thumpri/tweepy
 def prev(self):
     if self.current_page is None:
         raise TweepyException('Can not go back more, at first page')
     if self.page_index == 0:
         # At the beginning of the current page, move to next...
         self.current_page = self.page_iterator.prev()
         self.page_index = len(self.current_page)
         if self.page_index == 0:
             raise TweepyException('No more items')
     self.page_index -= 1
     self.num_tweets -= 1
     return self.current_page[self.page_index]
示例#4
0
文件: cursor.py 项目: thumpri/tweepy
 def prev(self):
     if self.prev_cursor == 0:
         raise TweepyException('Can not page back more, at first page')
     data, self.next_cursor, self.prev_cursor = self.method(
         cursor=self.prev_cursor, *self.args, **self.kwargs)
     self.num_tweets -= 1
     return data
示例#5
0
文件: cursor.py 项目: thumpri/tweepy
 def __init__(self, method, *args, **kwargs):
     if hasattr(method, 'pagination_mode'):
         if method.pagination_mode == 'cursor':
             self.iterator = CursorIterator(method, *args, **kwargs)
         elif method.pagination_mode == 'dm_cursor':
             self.iterator = DMCursorIterator(method, *args, **kwargs)
         elif method.pagination_mode == 'id':
             self.iterator = IdIterator(method, *args, **kwargs)
         elif method.pagination_mode == "next":
             self.iterator = NextIterator(method, *args, **kwargs)
         elif method.pagination_mode == 'page':
             self.iterator = PageIterator(method, *args, **kwargs)
         else:
             raise TweepyException('Invalid pagination mode.')
     else:
         raise TweepyException('This method does not perform pagination')
示例#6
0
 def _get_request_token(self, access_type=None):
     try:
         url = self._get_oauth_url('request_token')
         if access_type:
             url += f'?x_auth_access_type={access_type}'
         return self.oauth.fetch_request_token(url)
     except Exception as e:
         raise TweepyException(e)
示例#7
0
    def sample(self, *, languages=None, stall_warnings=False, threaded=False):
        """Sample realtime Tweets

        .. deprecated:: 4.9
            `The Twitter API v1.1 endpoint this method uses is now deprecated
            and will be retired on October 29, 2022.`_ Twitter API v2 can be
            used instead with :meth:`StreamingClient.sample`.

        Parameters
        ----------
        languages : list[str] | None
            Setting this parameter to a comma-separated list of `BCP 47`_
            language identifiers corresponding to any of the languages listed
            on Twitter’s `advanced search`_ page will only return Tweets that
            have been detected as being written in the specified languages. For
            example, connecting with language=en will only stream Tweets
            detected to be in the English language.
        stall_warnings : bool
            Specifies whether stall warnings should be delivered
        threaded : bool
            Whether or not to use a thread to run the stream

        Raises
        ------
        TweepyException
            When the stream is already connected

        Returns
        -------
        threading.Thread | None
            The thread if ``threaded`` is set to ``True``, else ``None``

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/v1/tweets/sample-realtime/api-reference/get-statuses-sample

        .. _BCP 47: https://tools.ietf.org/html/bcp47
        .. _advanced search: https://twitter.com/search-advanced
        .. _The Twitter API v1.1 endpoint this method uses is now deprecated
            and will be retired on October 29, 2022.: https://twittercommunity.com/t/deprecation-announcement-removing-compliance-messages-from-statuses-filter-and-retiring-statuses-sample-from-the-twitter-api-v1-1/170500
        """
        if self.running:
            raise TweepyException("Stream is already connected")

        method = "GET"
        endpoint = "statuses/sample"

        params = {}
        if languages:
            params["language"] = ','.join(map(str, languages))
        if stall_warnings:
            params["stall_warnings"] = "true"

        if threaded:
            return self._threaded_connect(method, endpoint, params=params)
        else:
            self._connect(method, endpoint, params=params)
示例#8
0
    def sample(self, *, languages=None, stall_warnings=False):
        """Sample realtime Tweets

        .. deprecated:: 4.10
            `The Twitter API v1.1 endpoint this method uses is now deprecated
            and will be retired on October 29, 2022.`_ Twitter API v2 can be
            used instead with :meth:`AsyncStreamingClient.sample`.

        Parameters
        ----------
        languages : list[str] | None
            Setting this parameter to a comma-separated list of `BCP 47`_
            language identifiers corresponding to any of the languages listed
            on Twitter’s `advanced search`_ page will only return Tweets that
            have been detected as being written in the specified languages. For
            example, connecting with language=en will only stream Tweets
            detected to be in the English language.
        stall_warnings: bool | None
            Specifies whether stall warnings should be delivered. See
            https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/basic-stream-parameters
            for more information.

        Raises
        ------
        TweepyException
            When the stream is already connected

        Returns
        -------
        asyncio.Task
            The task running the stream

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/v1/tweets/sample-realtime/api-reference/get-statuses-sample

        .. _BCP 47: https://tools.ietf.org/html/bcp47
        .. _advanced search: https://twitter.com/search-advanced
        .. _The Twitter API v1.1 endpoint this method uses is now deprecated
            and will be retired on October 29, 2022.: https://twittercommunity.com/t/deprecation-announcement-removing-compliance-messages-from-statuses-filter-and-retiring-statuses-sample-from-the-twitter-api-v1-1/170500
        """
        if self.task is not None and not self.task.done():
            raise TweepyException("Stream is already connected")

        endpoint = "statuses/sample"

        params = {}
        if languages is not None:
            params["language"] = ','.join(map(str, languages))
        if stall_warnings:
            params["stall_warnings"] = "true"

        self.task = asyncio.create_task(
            self._connect("GET", endpoint, params=params)
        )
        # Use name parameter when support for Python 3.7 is dropped
        return self.task
示例#9
0
 def get_username(self):
     if self.username is None:
         api = API(self)
         user = api.verify_credentials()
         if user:
             self.username = user.screen_name
         else:
             raise TweepyException('Unable to get username,'
                                   ' invalid oauth token!')
     return self.username
    def sample(self, *, languages=None, stall_warnings=False):
        """Sample realtime Tweets

        Parameters
        ----------
        languages : Optional[List[str]]
            Setting this parameter to a comma-separated list of `BCP 47`_
            language identifiers corresponding to any of the languages listed
            on Twitter’s `advanced search`_ page will only return Tweets that
            have been detected as being written in the specified languages. For
            example, connecting with language=en will only stream Tweets
            detected to be in the English language.
        stall_warnings: Optional[bool]
            Specifies whether stall warnings should be delivered. See
            https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/basic-stream-parameters
            for more information.

        Raises
        ------
        TweepyException
            When the stream is already connected

        Returns
        -------
        asyncio.Task
            The task running the stream

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/v1/tweets/sample-realtime/api-reference/get-statuses-sample

        .. _BCP 47: https://tools.ietf.org/html/bcp47
        .. _advanced search: https://twitter.com/search-advanced
        """
        if self.task is not None and not self.task.done():
            raise TweepyException("Stream is already connected")

        endpoint = "statuses/sample"

        params = {}
        if languages is not None:
            params["language"] = ','.join(map(str, languages))
        if stall_warnings:
            params["stall_warnings"] = "true"

        self.task = asyncio.ensure_future(
            self._connect("GET", endpoint, params=params)
        )
        # Use create_task when support for Python 3.6 is dropped
        return self.task
示例#11
0
    def __init__(self, consumer_key, consumer_secret):
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self._bearer_token = ''

        resp = requests.post(self._get_oauth_url('token'),
                             auth=(self.consumer_key, self.consumer_secret),
                             data={'grant_type': 'client_credentials'})
        data = resp.json()
        if data.get('token_type') != 'bearer':
            raise TweepyException('Expected token_type to equal "bearer", '
                                  f'but got {data.get("token_type")} instead')

        self._bearer_token = data['access_token']
示例#12
0
文件: auth.py 项目: wangkegame/tweepy
 def get_authorization_url(self,
                           signin_with_twitter=False,
                           access_type=None):
     """Get the authorization URL to redirect the user"""
     try:
         if signin_with_twitter:
             url = self._get_oauth_url('authenticate')
             if access_type:
                 log.warning(WARNING_MESSAGE)
         else:
             url = self._get_oauth_url('authorize')
         self.request_token = self._get_request_token(access_type=access_type)
         return self.oauth.authorization_url(url)
     except Exception as e:
         raise TweepyException(e)
示例#13
0
    def parse(self, payload, *, return_cursors=False, **kwargs):
        try:
            json = json_lib.loads(payload)
        except Exception as e:
            raise TweepyException(f'Failed to parse JSON payload: {e}')

        if return_cursors and isinstance(json, dict):
            if 'next' in json:
                return json, json['next']
            elif 'next_cursor' in json:
                if 'previous_cursor' in json:
                    cursors = json['previous_cursor'], json['next_cursor']
                    return json, cursors
                else:
                    return json, json['next_cursor']
        return json
示例#14
0
    def sample(self, *, languages=None, stall_warnings=False, threaded=False):
        if self.running:
            raise TweepyException("Stream is already connected")

        method = "GET"
        endpoint = "statuses/sample"

        params = {}
        if languages:
            params["language"] = ','.join(map(str, languages))
        if stall_warnings:
            params["stall_warnings"] = "true"

        if threaded:
            return self._threaded_connect(method, endpoint, params=params)
        else:
            self._connect(method, endpoint, params=params)
示例#15
0
    def sample(self, *, languages=None, stall_warnings=False, threaded=False):
        """Sample realtime Tweets

        Parameters
        ----------
        languages : list[str] | None
            Setting this parameter to a comma-separated list of `BCP 47`_
            language identifiers corresponding to any of the languages listed
            on Twitter’s `advanced search`_ page will only return Tweets that
            have been detected as being written in the specified languages. For
            example, connecting with language=en will only stream Tweets
            detected to be in the English language.
        stall_warnings : bool
            Specifies whether stall warnings should be delivered
        threaded : bool
            Whether or not to use a thread to run the stream

        Returns
        -------
        threading.Thread | None
            The thread if ``threaded`` is set to ``True``, else ``None``

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/v1/tweets/sample-realtime/api-reference/get-statuses-sample

        .. _BCP 47: https://tools.ietf.org/html/bcp47
        .. _advanced search: https://twitter.com/search-advanced
        """
        if self.running:
            raise TweepyException("Stream is already connected")

        method = "GET"
        endpoint = "statuses/sample"

        params = {}
        if languages:
            params["language"] = ','.join(map(str, languages))
        if stall_warnings:
            params["stall_warnings"] = "true"

        if threaded:
            return self._threaded_connect(method, endpoint, params=params)
        else:
            self._connect(method, endpoint, params=params)
示例#16
0
文件: auth.py 项目: wangkegame/tweepy
 def get_access_token(self, verifier=None):
     """
     After user has authorized the request token, get access token
     with user supplied verifier.
     """
     try:
         url = self._get_oauth_url('access_token')
         self.oauth = OAuth1Session(self.consumer_key,
                                    client_secret=self.consumer_secret,
                                    resource_owner_key=self.request_token['oauth_token'],
                                    resource_owner_secret=self.request_token['oauth_token_secret'],
                                    verifier=verifier, callback_uri=self.callback)
         resp = self.oauth.fetch_access_token(url)
         self.access_token = resp['oauth_token']
         self.access_token_secret = resp['oauth_token_secret']
         return self.access_token, self.access_token_secret
     except Exception as e:
         raise TweepyException(e)
示例#17
0
文件: auth.py 项目: wangkegame/tweepy
    def get_xauth_access_token(self, username, password):
        """
        Get an access token from an username and password combination.
        In order to get this working you need to create an app at
        http://twitter.com/apps, after that send a mail to [email protected]
        and request activation of xAuth for it.
        """
        try:
            url = self._get_oauth_url('access_token')
            oauth = OAuth1(self.consumer_key,
                           client_secret=self.consumer_secret)
            r = requests.post(url=url,
                              auth=oauth,
                              headers={'x_auth_mode': 'client_auth',
                                       'x_auth_username': username,
                                       'x_auth_password': password})

            credentials = parse_qs(r.content)
            return credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0]
        except Exception as e:
            raise TweepyException(e)
示例#18
0
    def sample(self, *, threaded=False, **params):
        """sample( \
            *, backfill_minutes=None, expansions=None, media_fields=None, \
            place_fields=None, poll_fields=None, tweet_fields=None, \
            user_fields=None, threaded=False \
        )

        Streams about 1% of all Tweets in real-time.

        If you are using the academic research product track, you can connect
        up to two `redundant connections <sample redundant connections_>`_ to
        maximize your streaming up-time.

        Parameters
        ----------
        backfill_minutes : int | None
            By passing this parameter, you can request up to five (5) minutes
            worth of streaming data that you might have missed during a
            disconnection to be delivered to you upon reconnection. The
            backfilled Tweets will automatically flow through the reconnected
            stream, with older Tweets generally being delivered before any
            newly matching Tweets. You must include a whole number between 1
            and 5 as the value to this parameter.

            This feature will deliver duplicate Tweets, meaning that if you
            were disconnected for 90 seconds, and you requested two minutes of
            backfill, you will receive 30 seconds worth of duplicate Tweets.
            Due to this, you should make sure your system is tolerant of
            duplicate data.

            This feature is currently only available to the Academic Research
            product track.
        expansions : list[str] | str
            :ref:`expansions_parameter`
        media_fields : list[str] | str
            :ref:`media_fields_parameter`
        place_fields : list[str] | str
            :ref:`place_fields_parameter`
        poll_fields : list[str] | str
            :ref:`poll_fields_parameter`
        tweet_fields : list[str] | str
            :ref:`tweet_fields_parameter`
        user_fields : list[str] | str
            :ref:`user_fields_parameter`
        threaded : bool
            Whether or not to use a thread to run the stream

        Raises
        ------
        TweepyException
            When the stream is already connected

        Returns
        -------
        threading.Thread | None
            The thread if ``threaded`` is set to ``True``, else ``None``

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/tweets/volume-streams/api-reference/get-tweets-sample-stream

        .. _sample redundant connections: https://developer.twitter.com/en/docs/twitter-api/tweets/volume-streams/integrate/recovery-and-redundancy-features
        """
        if self.running:
            raise TweepyException("Stream is already connected")

        method = "GET"
        endpoint = "sample"

        params = self._process_params(
            params, endpoint_parameters=(
                "backfill_minutes", "expansions", "media.fields",
                "place.fields", "poll.fields", "tweet.fields", "user.fields"
            )
        )

        if threaded:
            return self._threaded_connect(method, endpoint, params=params)
        else:
            self._connect(method, endpoint, params=params)
示例#19
0
    def filter(self, *, follow=None, track=None, locations=None,
               filter_level=None, languages=None, stall_warnings=False,
               threaded=False):
        """Filter realtime Tweets

        .. deprecated:: 4.9
            `The delivery of compliance messages through the Twitter API v1.1
            endpoint this method uses has been deprecated, and they will stop
            being delivered beginning October 29, 2022.`_ Twitter API v2 can be
            used instead with :meth:`StreamingClient.filter` and/or
            :class:`Client` :ref:`batch compliance <Batch compliance>` methods.

        Parameters
        ----------
        follow : list[int | str] | None
            User IDs, indicating the users to return statuses for in the stream
        track : list[str] | None
            Keywords to track
        locations : list[float] | None
            Specifies a set of bounding boxes to track
        filter_level : str | None
            Setting this parameter to one of none, low, or medium will set the
            minimum value of the filter_level Tweet attribute required to be
            included in the stream. The default value is none, which includes
            all available Tweets.

            When displaying a stream of Tweets to end users (dashboards or live
            feeds at a presentation or conference, for example) it is suggested
            that you set this value to medium.
        languages : list[str] | None
            Setting this parameter to a comma-separated list of `BCP 47`_
            language identifiers corresponding to any of the languages listed
            on Twitter’s `advanced search`_ page will only return Tweets that
            have been detected as being written in the specified languages. For
            example, connecting with language=en will only stream Tweets
            detected to be in the English language.
        stall_warnings : bool
            Specifies whether stall warnings should be delivered
        threaded : bool
            Whether or not to use a thread to run the stream

        Raises
        ------
        TweepyException
            When the stream is already connected or when the number of location
            coordinates is not a multiple of 4

        Returns
        -------
        threading.Thread | None
            The thread if ``threaded`` is set to ``True``, else ``None``

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/v1/tweets/filter-realtime/api-reference/post-statuses-filter

        .. _BCP 47: https://tools.ietf.org/html/bcp47
        .. _advanced search: https://twitter.com/search-advanced
        .. _The delivery of compliance messages through the Twitter API v1.1
            endpoint this method uses has been deprecated, and they will stop
            being delivered beginning October 29, 2022.: https://twittercommunity.com/t/deprecation-announcement-removing-compliance-messages-from-statuses-filter-and-retiring-statuses-sample-from-the-twitter-api-v1-1/170500
        """
        if self.running:
            raise TweepyException("Stream is already connected")

        method = "POST"
        endpoint = "statuses/filter"
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        body = {}
        if follow:
            body["follow"] = ','.join(map(str, follow))
        if track:
            body["track"] = ','.join(map(str, track))
        if locations and len(locations) > 0:
            if len(locations) % 4:
                raise TweepyException(
                    "Number of location coordinates should be a multiple of 4"
                )
            body["locations"] = ','.join(f"{l:.4f}" for l in locations)
        if filter_level:
            body["filter_level"] = filter_level
        if languages:
            body["language"] = ','.join(map(str, languages))
        if stall_warnings:
            body["stall_warnings"] = stall_warnings

        if threaded:
            return self._threaded_connect(method, endpoint, headers=headers,
                                          body=body)
        else:
            self._connect(method, endpoint, headers=headers, body=body)
示例#20
0
# Tweepy
# Copyright 2009-2022 Joshua Roesslein
# See LICENSE for details.

"""
Tweepy.asynchronoous

Asynchronous interfaces with the Twitter API
"""

try:
    import aiohttp
    import oauthlib
except ModuleNotFoundError:
    from tweepy.errors import TweepyException
    raise TweepyException(
        "tweepy.asynchronous requires aiohttp and oauthlib to be installed"
    )

from tweepy.asynchronous.streaming import AsyncStream
示例#21
0
文件: cursor.py 项目: thumpri/tweepy
 def prev(self):
     raise TweepyException(
         'This method does not allow backwards pagination')
示例#22
0
文件: cursor.py 项目: thumpri/tweepy
 def prev(self):
     if self.current_page == 1:
         raise TweepyException('Can not page back more, at first page')
     self.current_page -= 1
     return self.method(page=self.current_page, *self.args, **self.kwargs)
示例#23
0
    def filter(self, *, follow=None, track=None, locations=None,
               filter_level=None, languages=None, stall_warnings=False,
               threaded=False):
        """Filter realtime Tweets

        Parameters
        ----------
        follow : Optional[List[Union[int, str]]]
            User IDs, indicating the users to return statuses for in the stream
        track : Optional[List[str]]
            Keywords to track
        locations : Optional[List[float]]
            Specifies a set of bounding boxes to track
        filter_level : Optional[str]
            Setting this parameter to one of none, low, or medium will set the
            minimum value of the filter_level Tweet attribute required to be
            included in the stream. The default value is none, which includes
            all available Tweets.

            When displaying a stream of Tweets to end users (dashboards or live
            feeds at a presentation or conference, for example) it is suggested
            that you set this value to medium.
        languages : Optional[List[str]]
            Setting this parameter to a comma-separated list of `BCP 47`_
            language identifiers corresponding to any of the languages listed
            on Twitter’s `advanced search`_ page will only return Tweets that
            have been detected as being written in the specified languages. For
            example, connecting with language=en will only stream Tweets
            detected to be in the English language.
        stall_warnings : bool
            Specifies whether stall warnings should be delivered
        threaded : bool
            Whether or not to use a thread to run the stream

        Raises
        ------
        TweepyException
            When number of location coordinates is not a multiple of 4

        Returns
        -------
        Optional[threading.Thread]
            The thread if ``threaded`` is set to ``True``, else ``None``

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/v1/tweets/filter-realtime/api-reference/post-statuses-filter

        .. _BCP 47: https://tools.ietf.org/html/bcp47
        .. _advanced search: https://twitter.com/search-advanced
        """
        if self.running:
            raise TweepyException("Stream is already connected")

        method = "POST"
        endpoint = "statuses/filter"
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        body = {}
        if follow:
            body["follow"] = ','.join(map(str, follow))
        if track:
            body["track"] = ','.join(map(str, track))
        if locations and len(locations) > 0:
            if len(locations) % 4:
                raise TweepyException(
                    "Number of location coordinates should be a multiple of 4"
                )
            body["locations"] = ','.join(f"{l:.4f}" for l in locations)
        if filter_level:
            body["filter_level"] = filter_level
        if languages:
            body["language"] = ','.join(map(str, languages))
        if stall_warnings:
            body["stall_warnings"] = stall_warnings

        if threaded:
            return self._threaded_connect(method, endpoint, headers=headers,
                                          body=body)
        else:
            self._connect(method, endpoint, headers=headers, body=body)
示例#24
0
    def filter(self,
               *,
               follow=None,
               track=None,
               locations=None,
               filter_level=None,
               languages=None,
               stall_warnings=False):
        """Filter realtime Tweets

        Parameters
        ----------
        follow: list[int | str] | None
            A list of user IDs, indicating the users to return statuses for in
            the stream. See https://developer.twitter.com/en/docs/twitter-api/v1/tweets/filter-realtime/guides/basic-stream-parameters
            for more information.
        track: list[str] | None
            Keywords to track. Phrases of keywords are specified by a list. See
            https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/basic-stream-parameters
            for more information.
        locations: list[float] | None
            Specifies a set of bounding boxes to track. See
            https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/basic-stream-parameters
            for more information.
        filter_level : str | None
            Setting this parameter to one of none, low, or medium will set the
            minimum value of the filter_level Tweet attribute required to be
            included in the stream. The default value is none, which includes
            all available Tweets.

            When displaying a stream of Tweets to end users (dashboards or live
            feeds at a presentation or conference, for example) it is suggested
            that you set this value to medium.
        languages : list[str] | None
            Setting this parameter to a comma-separated list of `BCP 47`_
            language identifiers corresponding to any of the languages listed
            on Twitter’s `advanced search`_ page will only return Tweets that
            have been detected as being written in the specified languages. For
            example, connecting with language=en will only stream Tweets
            detected to be in the English language.
        stall_warnings: bool | None
            Specifies whether stall warnings should be delivered. See
            https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/basic-stream-parameters
            for more information.

        Raises
        ------
        TweepyException
            When the stream is already connected or when the number of location
            coordinates is not a multiple of 4

        Returns
        -------
        asyncio.Task
            The task running the stream

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/v1/tweets/filter-realtime/api-reference/post-statuses-filter

        .. _BCP 47: https://tools.ietf.org/html/bcp47
        .. _advanced search: https://twitter.com/search-advanced
        """
        if self.task is not None and not self.task.done():
            raise TweepyException("Stream is already connected")

        endpoint = "statuses/filter"
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        body = {}
        if follow is not None:
            body["follow"] = ','.join(map(str, follow))
        if track is not None:
            body["track"] = ','.join(map(str, track))
        if locations is not None:
            if len(locations) % 4:
                raise TweepyException(
                    "Number of location coordinates should be a multiple of 4")
            body["locations"] = ','.join(f"{location:.4f}"
                                         for location in locations)
        if filter_level is not None:
            body["filter_level"] = filter_level
        if languages is not None:
            body["language"] = ','.join(map(str, languages))
        if stall_warnings:
            body["stall_warnings"] = "true"

        self.task = asyncio.create_task(
            self._connect("POST", endpoint, headers=headers, body=body
                          or None))
        # Use name parameter when support for Python 3.7 is dropped
        return self.task
示例#25
0
    def filter(self, **params):
        """filter( \
            *, backfill_minutes=None, expansions=None, media_fields=None, \
            place_fields=None, poll_fields=None, tweet_fields=None, \
            user_fields=None \
        )

        Streams Tweets in real-time based on a specific set of filter rules.

        If you are using the academic research product track, you can connect
        up to two `redundant connections <filter redundant connections_>`_ to
        maximize your streaming up-time.

        The Tweets returned by this endpoint count towards the Project-level
        `Tweet cap`_.

        Parameters
        ----------
        backfill_minutes : int | None
            By passing this parameter, you can request up to five (5) minutes
            worth of streaming data that you might have missed during a
            disconnection to be delivered to you upon reconnection. The
            backfilled Tweets will automatically flow through the reconnected
            stream, with older Tweets generally being delivered before any
            newly matching Tweets. You must include a whole number between 1
            and 5 as the value to this parameter.

            This feature will deliver duplicate Tweets, meaning that if you
            were disconnected for 90 seconds, and you requested two minutes of
            backfill, you will receive 30 seconds worth of duplicate Tweets.
            Due to this, you should make sure your system is tolerant of
            duplicate data.

            This feature is currently only available to the Academic Research
            product track.
        expansions : list[str] | str
            :ref:`expansions_parameter`
        media_fields : list[str] | str
            :ref:`media_fields_parameter`
        place_fields : list[str] | str
            :ref:`place_fields_parameter`
        poll_fields : list[str] | str
            :ref:`poll_fields_parameter`
        tweet_fields : list[str] | str
            :ref:`tweet_fields_parameter`
        user_fields : list[str] | str
            :ref:`user_fields_parameter`

        Raises
        ------
        TweepyException
            When the stream is already connected

        Returns
        -------
        asyncio.Task
            The task running the stream

        References
        ----------
        https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/api-reference/get-tweets-search-stream

        .. _filter redundant connections: https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/integrate/recovery-and-redundancy-features
        .. _Tweet cap: https://developer.twitter.com/en/docs/twitter-api/tweet-caps
        """
        if self.task is not None and not self.task.done():
            raise TweepyException("Stream is already connected")

        endpoint = "search"

        params = self._process_params(
            params, endpoint_parameters=(
                "backfill_minutes", "expansions", "media.fields",
                "place.fields", "poll.fields", "tweet.fields", "user.fields"
            )
        )

        self.task = asyncio.create_task(
            self._connect("GET", endpoint, params=params)
        )
        # Use name parameter when support for Python 3.7 is dropped
        return self.task