Search twitter API
558930
def search_for_tweets_about(user_id, params):
    
    url = "https://api.twitter.com/1.1/search/tweets.json"
    response = make_twitter_request(url, user_id, params)
    return process_tweets(response.json()["statuses"])
142524
def search(query, results=10, suggestion=False):
  '''
  
  '''

  search_params = {
    'list': 'search',
    'srprop': '',
    'srlimit': results,
    'limit': results,
    'srsearch': query
  }
  if suggestion:
    search_params['srinfo'] = 'suggestion'

  raw_results = _wiki_request(search_params)

  if 'error' in raw_results:
    if raw_results['error']['info'] in ('HTTP request timed out.', 'Pool queue is full'):
      raise HTTPTimeoutError(query)
    else:
      raise WikipediaException(raw_results['error']['info'])

  search_results = (d['title'] for d in raw_results['query']['search'])

  if suggestion:
    if raw_results['query'].get('searchinfo'):
      return list(search_results), raw_results['query']['searchinfo']['suggestion']
    else:
      return list(search_results), None

  return list(search_results)
41595
def cat_tweets(filename='all_tweets.json.gz', path=DATA_PATH, ext='.json', save_tmp=False, verbosity=1, numtweets=10000000, ignore_suspicious=True):
    """"""
    log.info('Finding {} files in {}...'.format(ext, path))
    meta_files = find_files(path=path, ext=ext)
    meta_files = [meta for meta in meta_files
                  if re.match(r'^[-#@a-z ]*201[5-6]-[0-9]{2}-[0-9]{2}.*', meta['name'])]
    #  '\s[0-9]{2}[:][0-9]{2}[:][0-9]{2}[.][0-9]+[.]json(.gz)?$', meta['name'])]
    log.info('Found {} files that look like tweetget dumps.'.format(len(meta_files)))
    print([mf['name'] for mf in meta_files])
    total_size = sum([meta['size'] for meta in meta_files])
    if verbosity > 0:
        pbar = progressbar.ProgressBar(maxval=(total_size + 1.) / 1e6)
        pbar.start()
    else:
        pbar = None

    loaded_size = 0
    df_all = pd.DataFrame()
    for meta in meta_files:
        with (gzip.open(meta['path']) if ext.endswith('.gz') else open(meta['path'])) as fin:
            js = pd.json.load(fin)
        if not len(js):
            continue
        df = pd.io.json.json_normalize(js)
        # json entries were dumped in reverse time order (most recent first)
        df.drop_duplicates(['id'], keep='first', inplace=True)
        df.set_index('id', drop=True, inplace=True)
        if 'geo.coordinates' in df.columns:
            latlon = np.array([(ll[0], ll[1]) if isinstance(ll, list) else (np.nan, np.nan) for ll in df['geo.coordinates']])
            for i, ll in enumerate(latlon):
                try:
                    latlon[i] = float(ll[0]), float(ll[1])
                except ValueError:
                    latlon[i] = np.nan, np.nan
            ll = list(zip(*latlon))
            df['lat'] = ll[0]
            df['lon'] = ll[1]
            df_all = df_all.append(df)
        else:
            df['lat'] = np.nan * np.ones(len(df))
            df['lon'] = np.nan * np.ones(len(df))
            if ignore_suspicious:
                log.info('\nOddly the DataFrame in {} didnt have a geo.coordinates column.'.format(meta['path']))
                log.warn('\nSkipping {} suspicious tweets.'.format(len(df)))
            else:
                df_all = df_all.append(df)
        # this would be a good time to incrementally save these rows to disc
        del df
        loaded_size += meta['size']
        if len(df_all) >= numtweets:
            # FIXME use average rate of 400 tweets/MB to calculate better progressbar size at start
            break
        if save_tmp:
            save_tweets(df_all, path=path, filename='tmp.csv')
        if pbar:
            pbar.update(loaded_size / 1e6)
    print(len(df_all))
    bigger_better_cols = [c for c in df_all.columns if c.endswith('_at') or '_count' in c]
    print(bigger_better_cols)
    print(all(c in df_all.columns for c in bigger_better_cols))
    df_all = df_all.sort_values(by=bigger_better_cols, inplace=False)
    hashable_cols = [c for c in df_all.columns if df_all[c].dtype not in (list,)]
    df_all = df_all.drop_duplicates(subset=hashable_cols, inplace=False)
    if pbar:
        pbar.finish()
    log.info('Loaded {} unique tweets.'.format(len(df_all)))
    return df_all
327003
public static function TweetHandler($arguments)
    {
        if (!isset($arguments['id'])) {
            return null;
        }
        if (substr($arguments['id'], 0, 4) === 'http') {
            list($unneeded, $id) = explode('/status/', $arguments['id']);
        } else {
            $id = $arguments['id'];
        }
        $data = json_decode(file_get_contents('https://api.twitter.com/1/statuses/oembed.json?id=' . $id . '&omit_script=true&lang=en'), 1);

        return $data['html'];
    }
762046
def create_search_index():
    

    # create people name cache
    counter = 0

    people_names = []
    twitter_handles = []
    usernames = []

    log.debug("-" * 5)
    log.debug("Creating search index")

    for user in namespace.find():
        # the profile/info to be inserted
        search_profile = {}

        counter += 1

        if(counter % 1000 == 0):
            log.debug("Processed entries: %s" % counter)

        if validUsername(user['username']):
            pass
        else:
            continue

        profile = get_json(user['profile'])


        hasBazaarId=False
        # search for openbazaar id in the profile
        if 'account' in profile:
            for accounts in profile['account']:
                if  accounts['service'] == 'openbazaar':
                   hasBazaarId = True
                   search_profile['openbazaar']=accounts['identifier']

        if (hasBazaarId == False):
            search_profile['openbazaar'] = None

        if 'name' in profile:
            try:
                name = profile['name']
            except:
                continue

            try:
                name = name['formatted'].lower()
            except:
                name = name.lower()
            people_names.append(name)
            search_profile['name'] = name

        else:
            search_profile['name'] = None

        if 'twitter' in profile:
            twitter_handle = profile['twitter']

            try:
                twitter_handle = twitter_handle['username'].lower()
            except:
                try:
                    twitter_handle = profile['twitter'].lower()
                except:
                    continue

            twitter_handles.append(twitter_handle)
            search_profile['twitter_handle'] = twitter_handle

        else:
            search_profile['twitter_handle'] = None

        search_profile['fullyQualifiedName'] = user['fqu']
        search_profile['username'] = user['username']
        usernames.append(user['fqu'])

        search_profile['profile'] = profile
        search_profiles.save(search_profile)


    # dedup names
    people_names = list(set(people_names))
    people_names = {'name': people_names}

    twitter_handles = list(set(twitter_handles))
    twitter_handles = {'twitter_handle': twitter_handles}

    usernames = list(set(usernames))
    usernames = {'username': usernames}

    # save final dedup results to mongodb (using it as a cache)
    people_cache.save(people_names)
    twitter_cache.save(twitter_handles)
    username_cache.save(usernames)

    optimize_db()

    log.debug('Created name/twitter/username search index')
421725
public function getTwitterHashtag()
    {
        $access_token = $this->getTwitterAccessToken();

        if (isset($access_token->errors[0])) {
            return $access_token->errors[0];
        }

        $endpoint = 'https://api.twitter.com/1.1/search/tweets.json';
        $data = array(
            'access_token'     => $access_token,
            'q'                => urlencode('#' . $this->args['query']),
            'count'            => $this->args['length'],
            'exclude_replies'  => true,
            'include_rts '     => false,
            'result_type'      => 'recent',
            'lang'             => 'sv'
        );

        // Request headers
        $headers = array(
            "GET /1.1/search/tweets.json" . http_build_query($data) . " HTTP/1.1",
            "Host: api.twitter.com",
            "User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
            "Authorization: Bearer " . $access_token
        );

        // Curl
        $curl = new \Modularity\Helper\Curl();
        $tweets = $curl->request('GET', $endpoint, $data, 'JSON', $headers);

        return json_decode($tweets)->statuses;
    }
97490
def search_messages(self, *, query: str, **kwargs) -> SlackResponse:
        
        self._validate_xoxp_token()
        kwargs.update({"query": query})
        return self.api_call("search.messages", http_verb="GET", params=kwargs)
139211
function(req, res, next) {
    var requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
    var accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
    var authenticateUrl = 'https://api.twitter.com/oauth/authenticate';

    // Step 2. Redirect to the authorization screen.
    if (!req.query.oauth_token || !req.query.oauth_verifier) {
      var requestTokenOauth = {
        consumer_key: config.TWITTER_KEY,
        consumer_secret: config.TWITTER_SECRET,
        callback: config.TWITTER_CALLBACK
      };

      request.post({ url: requestTokenUrl, oauth: requestTokenOauth }, function(err, response, body) {
        var oauthToken = qs.parse(body);
        var params = qs.stringify({ oauth_token: oauthToken.oauth_token });

        res.redirect(authenticateUrl + '?' + params);
      });
      return;
    } 

    // Step 3. Exchange oauth token and oauth verifier for access token.
    var accessTokenOauth = {
      consumer_key: config.TWITTER_KEY,
      consumer_secret: config.TWITTER_SECRET,
      token: req.query.oauth_token,
      verifier: req.query.oauth_verifier
    };

    request.post({ url: accessTokenUrl, oauth: accessTokenOauth }, function(err, response, profile) {
      if (err) {
        res.status(500).send(err);
        return;
      } 
      req.profile = qs.parse(profile);
      next();
    });
  }
623841
def trends_available(self):
        
        url = 'https://api.twitter.com/1.1/trends/available.json'
        try:
            resp = self.get(url)
        except requests.exceptions.HTTPError as e:
            raise e
        return resp.json()
618232
public function getSearchTweets(array $parameters = array(), $multipart = false, $appOnlyAuth = false)
    {
        return $this->get('search/tweets', $parameters, $multipart, $appOnlyAuth);
    }
1304510
function search(term = _noSearchTermError()) {
	const url = `${API}/devrant/search`;
	const params = {
		app: 3,
		term
	};

	return http
		.GET(url, params)
		.then(data => data.results);
}
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: ""
    }
  }
}
1350322
function getFieldsFromTweetLike(tweetLike) {
  var fields = fieldsToCheck.map(function(fieldName) {
    return _.get(tweetLike, fieldName);
  });

  arrayFieldsToCheck.forEach(function(fieldDescription) {
    var arr = _.get(tweetLike, fieldDescription.arrayAt);
    if (_.isArray(arr)) {
      arr.forEach(function(element) {
        fields.push(_.get(element, fieldDescription.inEach));
      });
    }
  });

  return fields.filter(function(field) {
    return typeof field === 'string' && field.trim().length !== 0;
  }).map(function(field) {
    return field.toLowerCase();
  });
}
1074776
def on_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id):
    
    ####################################################################################################################
    # Log into my application
    ####################################################################################################################
    twitter = login(twitter_app_key, twitter_app_secret)

    twitter_lists_list = twitter.get_list_memberships(user_id=user_twitter_id, count=1000)

    for twitter_list in twitter_lists_list:
        print(twitter_list)

    return twitter_lists_list
973253
def search(self, query=None, **kwargs):
        ""
        api_path = "/api/v2/search.json"
        api_query = {}
        if "query" in kwargs.keys():
            api_query.update(kwargs["query"])
            del kwargs["query"]
        if query:
            api_query.update({
                "query": query,
            })
        return self.call(api_path, query=api_query, **kwargs)
473899
def filter(self, track=None, follow=None, locations=None, event=None,
               record_keepalive=False):
        
        if locations is not None:
            if type(locations) == list:
                locations = ','.join(locations)
            locations = locations.replace('\\', '')

        url = 'https://stream.twitter.com/1.1/statuses/filter.json'
        params = {
            "stall_warning": True,
            "include_ext_alt_text": True
        }
        if track:
            params["track"] = track
        if follow:
            params["follow"] = follow
        if locations:
            params["locations"] = locations
        headers = {'accept-encoding': 'deflate, gzip'}
        errors = 0
        while True:
            try:
                log.info("connecting to filter stream for %s", params)
                resp = self.post(url, params, headers=headers, stream=True)
                errors = 0
                for line in resp.iter_lines(chunk_size=1024):
                    if event and event.is_set():
                        log.info("stopping filter")
                        # Explicitly close response
                        resp.close()
                        return
                    if not line:
                        log.info("keep-alive")
                        if record_keepalive:
                            yield "keep-alive"
                        continue
                    try:
                        yield json.loads(line.decode())
                    except Exception as e:
                        log.error("json parse error: %s - %s", e, line)
            except requests.exceptions.HTTPError as e:
                errors += 1
                log.error("caught http error %s on %s try", e, errors)
                if self.http_errors and errors == self.http_errors:
                    log.warning("too many errors")
                    raise e
                if e.response.status_code == 420:
                    if interruptible_sleep(errors * 60, event):
                        log.info("stopping filter")
                        return
                else:
                    if interruptible_sleep(errors * 5, event):
                        log.info("stopping filter")
                        return
            except Exception as e:
                errors += 1
                log.error("caught exception %s on %s try", e, errors)
                if self.http_errors and errors == self.http_errors:
                    log.warning("too many exceptions")
                    raise e
                log.error(e)
                if interruptible_sleep(errors, event):
                    log.info("stopping filter")
                    return
755039
public Iterable<DContact> queryByTwitter(Object parent, java.lang.String twitter) {
    return queryByField(parent, DContactMapper.Field.TWITTER.getFieldName(), twitter);
  }