How to Search Tweets by username using Twitter API

In this article, I show you how to use Twitter’s Search API to get tweets from a particular user. You may want to integrate this search API for various reasons. For example, you wish to like and retweet each tweet of a user.

Before proceeding to this article, you must go through our previous article on integrating Twitter OAuth 2.0 in PHP. Following the linked article, you’ll store your access token in the database. In order to incorporate a search API you must need this access token.

Search Tweets by username

As an example, let’s say you want to fetch tweets from Google. Its username is set to Google itself. Just in case, if you don’t know how to get the username, it’s present in the URL. For Google, the URL is https://twitter.com/Google where the last string is the username.

Use the below code that’ll fetch recent tweets from this company.

<?php
require_once 'config.php';

$username = "Google"; // pass username here
search_tweet_by_username($username);

function search_tweet_by_username($username) {
    $db = new DB();
    $arr_token = (array) $db->get_access_token();
    $access_token = $arr_token['access_token'];

    $search_string = "(from:$username)";

    try {
        // get user details
        $client = new GuzzleHttp\Client([
            'base_uri' => 'https://api.twitter.com',
        ]);

        $response = $client->request("GET", "/2/tweets/search/recent", [
            "headers" => [
                "Authorization" => "Bearer ". $access_token
            ],
            'query' => [
                'query' => $search_string, // search keyword
                'sort_order' => 'relevancy',
                'max_results' => 10, // can be between 10 - 100
            ]
        ]);

        $res = json_decode($response->getBody());
        print_r($res);

    } catch(Exception $e) {
        if (401 == $e->getCode()) {
            $refresh_token = $db->get_refersh_token();

            $response = $client->request('POST', '/2/oauth2/token', [
                'form_params' => [
                    "grant_type" => "refresh_token",
                    "refresh_token" => $refresh_token,
                    "client_id" => CLIENT_ID,
                ],
            ]);

            $db->update_access_token($response->getBody());
            
            search_tweet_by_username($username);
        }
    }
}

In the above code, I also handled the condition for an expired access token. Upon expiry, it regenerates the access token and calls the search API again. All this process happens in the background.

Using Twitter API v2’s search API you can broaden your search more specifically. You’re able to build your query as per your requirement and receive the related response.

For instance, our code will print all tweets including retweets. If you want only original tweets(without retweets), modify the search string as follows.

$search_string = "(from:$username) -is:retweet";

Check again and this time you will get only tweets(excluding retweets) that are posted officially.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *