Stream statuses/sample

        :param \*\*params: Parameters to send with your stream request

        Accepted params found at:
        https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample
516367
def sample(self, **params):
        
        url = 'https://stream.twitter.com/%s/statuses/sample.json' \
              % self.streamer.api_version
        self.streamer._request(url, params=params)
273951
def _print_stream_parameters(self, values):
        """"""
        cprint("{0}".format(*values), "magenta", attrs=["bold"])
        print("{4}".format(*values))
        cprint("  available formats:   {1}".format(*values), "blue")
        cprint("  mandatory selectors: {2}".format(*values), "red")
        cprint("  optional selectors:  {3}".format(*values), "green")
        print()
1332744
private Map<String, String> populateCommonAuthzHeaderParams() {
        Map<String, String> parameters = new HashMap<String, String>();

        parameters.put(TwitterConstants.PARAM_OAUTH_CONSUMER_KEY, consumerKey);
        parameters.put(TwitterConstants.PARAM_OAUTH_NONCE, Utils.generateNonce());
        parameters.put(TwitterConstants.PARAM_OAUTH_SIGNATURE_METHOD, DEFAULT_SIGNATURE_ALGORITHM);
        parameters.put(TwitterConstants.PARAM_OAUTH_TIMESTAMP, Utils.getCurrentTimestamp());
        parameters.put(TwitterConstants.PARAM_OAUTH_VERSION, DEFAULT_OAUTH_VERSION);

        return parameters;
    }
1162883
def handle(send, msg, args):
    
    worker = args["handler"].workers
    result = worker.run_pool(get_urls, [msg])
    try:
        urls = result.get(5)
    except multiprocessing.TimeoutError:
        worker.restart_pool()
        send("Url regex timed out.", target=args["config"]["core"]["ctrlchan"])
        return
    for url in urls:
        # Prevent botloops
        if (args["db"].query(Urls).filter(Urls.url == url, Urls.time > datetime.now() - timedelta(seconds=10)).count() > 1):
            return

        if url.startswith("https://twitter.com"):
            tid = url.split("/")[-1]
            twitter_api = get_api(args["config"])
            status = twitter_api.GetStatus(tid)
            text = status.text.replace("\n", " / ")
            send("** {} (@{}) on Twitter: {}".format(status.user.name, status.user.screen_name, text))
            return

        imgkey = args["config"]["api"]["googleapikey"]
        title = urlutils.get_title(url, imgkey)

        shortkey = args["config"]["api"]["bitlykey"]
        short = urlutils.get_short(url, shortkey)

        last = args["db"].query(Urls).filter(Urls.url == url).order_by(Urls.time.desc()).first()
        if args["config"]["feature"].getboolean("linkread"):
            if last is not None:
                lasttime = last.time.strftime("%H:%M:%S on %Y-%m-%d")
                send("Url %s previously posted at %s by %s -- %s" % (short, lasttime, last.nick, title))
            else:
                send("** %s - %s" % (title, short))
        args["db"].add(Urls(url=url, title=title, nick=args["nick"], time=datetime.now()))
952537
def __call_stream(self, uri, params=None, method="get"):
        
        try:
            resp = self.__get_response(uri, params, method, True)
            assert resp.ok
        except AssertionError:
            raise BadRequest(resp.status_code)
        except Exception as e:
            log.error("Bad response: {}".format(e), exc_info=True)
        else:
            return resp
1316904
def tweets_for(query_type, args, per_user=None):
    
    lookup = {"query_type": query_type, "value": args[0]}
    try:
        tweets = Tweet.objects.get_for(**lookup)
    except TwitterQueryException:
        return []
    if per_user is not None:
        _tweets = defaultdict(list)
        for tweet in tweets:
            if len(_tweets[tweet.user_name]) < per_user:
                _tweets[tweet.user_name].append(tweet)
        tweets = sum(_tweets.values(), [])
        tweets.sort(key=lambda t: t.created_at, reverse=True)
    if len(args) > 1 and str(args[-1]).isdigit():
        tweets = tweets[:int(args[-1])]
    return tweets
111110
def channels_twitter_ticket_statuses(self, id, **kwargs):
        ""
        api_path = "/api/v2/channels/twitter/tickets/{id}/statuses.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, **kwargs)
1369465
def _request(self, url, method='GET', params=None, api_call=None, json_encoded=False):
        """"""
        method = method.lower()
        params = params or {}

        func = getattr(self.client, method)
        if isinstance(params, dict) and json_encoded is False:
            params, files = _transparent_params(params)
        else:
            params = params
            files = list()

        requests_args = {}
        for k, v in self.client_args.items():
            # Maybe this should be set as a class variable and only done once?
            if k in ('timeout', 'allow_redirects', 'stream', 'verify'):
                requests_args[k] = v

        if method == 'get' or method == 'delete':
            requests_args['params'] = params
        else:
            # Check for json_encoded so we will sent params as "data" or "json"
            if json_encoded:
                data_key = 'json'
            else:
                data_key = 'data'
            requests_args.update({
                data_key: params,
                'files': files,
            })
        try:
            response = func(url, **requests_args)
        except requests.RequestException as e:
            raise TwythonError(str(e))

        # create stash for last function intel
        self._last_call = {
            'api_call': api_call,
            'api_error': None,
            'cookies': response.cookies,
            'headers': response.headers,
            'status_code': response.status_code,
            'url': response.url,
            'content': response.text,
        }

        # greater than 304 (not modified) is an error
        if response.status_code > 304:
            error_message = self._get_error_message(response)
            self._last_call['api_error'] = error_message

            ExceptionType = TwythonError
            if response.status_code == 429:
                # Twitter API 1.1, always return 429 when
                # rate limit is exceeded
                ExceptionType = TwythonRateLimitError
            elif response.status_code == 401 or 'Bad Authentication data' \
                    in error_message:
                # Twitter API 1.1, returns a 401 Unauthorized or
                # a 400 "Bad Authentication data" for invalid/expired
                # app keys/user tokens
                ExceptionType = TwythonAuthError

            raise ExceptionType(
                error_message,
                error_code=response.status_code,
                retry_after=response.headers.get('X-Rate-Limit-Reset'))
        content = ''
        try:
            if response.status_code == 204:
                content = response.content
            else:
                content = response.json()
        except ValueError:
            if response.content != '':
                raise TwythonError('Response was not valid JSON. \
                                   Unable to decode.')

        return content
556311
async function _process(
  args,
  { fetch },
  {
    _omitScript,
    maxWidth,
    hideMedia,
    hideThread,
    align,
    lang,
    theme,
    linkColor,
    widgetType
  }
) {
  const params = {
    url: args[0],
    omitScript: _omitScript,
    maxWidth,
    hideMedia,
    hideThread,
    align,
    lang,
    theme,
    linkColor,
    widgetType
  }
  try {
    const apiUrl = `https://api.twitter.com/1/statuses/oembed.json?${getQuery(
      params
    )}`
    const res = await (isBrowser ? jsonp : fetch)(apiUrl)
    return await res.json()
  } catch (e) {
    return {
      html: ""
    }
  }
}
506015
def post_data(self, url, params):
        
        url = urljoin(self.endpoint, url)
        headers = {'Authorization': self.token}
        req = requests.post(url, headers=headers, data=params, verify=False)

        if req.status_code == 204:
            return True

        if req.status_code == 404:
            raise NotFoundError()

        try:
            data = req.json()
        except ValueError as e:
            raise JSONReadError(
                'Read failed from API: %s' % str(e)
            )

        if not req.ok:
            msg = [data[m] for m in ("id", "message") if m in data][1]
            raise DataReadError(msg)

        return data
581391
def _xread(self, streams, timeout=0, count=None, latest_ids=None):
        
        if latest_ids is None:
            latest_ids = ['$'] * len(streams)
        if len(streams) != len(latest_ids):
            raise ValueError(
                'The streams and latest_ids parameters must be of the '
                'same length'
            )

        count_args = [b'COUNT', count] if count else []
        if timeout is None:
            block_args = []
        elif not isinstance(timeout, int):
            raise TypeError(
                "timeout argument must be int, not {!r}".format(timeout))
        else:
            block_args = [b'BLOCK', timeout]
        return block_args + count_args + [b'STREAMS'] + streams + latest_ids
1062118
def find_stream(self, **kwargs):
        
        found = list(self.find_streams(**kwargs).values())
        if not found:
            raise StreamNotFoundError(kwargs)
        if len(found) > 1:
            raise MultipleStreamsFoundError(kwargs)
        return found[0]
688705
def rest_get_stream(self, url, session=None, verify=True, cert=None):
        
        res = session.get(url, stream=True, verify=verify, cert=cert)
        return res.raw, res.status_code
98518
def get_params(self):
        
        params = super().get_params()
        params.update({'beta': self.beta,
                       'knn': self.knn,
                       'decay': self.decay,
                       'bandwidth': self.bandwidth,
                       'distance': self.distance,
                       'thresh': self.thresh,
                       'n_jobs': self.n_jobs})
        return params
904341
def start_stream(self):
        """"""

        tracking_terms = self.term_checker.tracking_terms()

        if len(tracking_terms) > 0 or self.unfiltered:
            # we have terms to track, so build a new stream
            self.stream = tweepy.Stream(self.auth, self.listener,
                                        stall_warnings=True,
                                        timeout=90,
                                        retry_count=self.retry_count)

            if len(tracking_terms) > 0:
                logger.info("Starting new twitter stream with %s terms:", len(tracking_terms))
                logger.info("  %s", repr(tracking_terms))
                
                # Launch it in a new thread
                self.stream.filter(track=tracking_terms, async=True, languages=self.languages)
            else:
                logger.info("Starting new unfiltered stream")
                self.stream.sample(async=True, languages=self.languages)
260299
def stream_list(self, id, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
        
        id =  self.__unpack_id(id)
        return self.__stream("/api/v1/streaming/list?list={}".format(id), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec)
67209
def stream(stream_id, update_max_id = true)
      raise ArgumentError, "stream_id can't be 0" if stream_id == 0

      stream = @streams[stream_id]
      if stream
        if stream.state == :idle && stream_id < @max_stream_ids[stream_id % 2]
          stream.set_state(:closed_implicitly)
        end
      elsif stream_id > @max_stream_ids[stream_id % 2]
        @max_stream_ids[stream_id % 2] = stream_id if update_max_id
        stream = Stream.new(self, stream_id, state: :idle)
        callback(:stream, stream)
        @streams[stream_id] = stream
      else
        stream = Stream.new(self, stream_id, state: :closed_implicitly)
        callback(:stream, stream)
      end

      stream
    end