Twitter API – Like And Retweet A Tweet Using PHP

Recently while working on a client’s project, we came across a situation where the client wants to like and retweet all tweets from a specific user. We needed to make this process automatic so that all tasks should be performed automatically in the background.

To handle this operation, Twitter provides an Account Activity API which is a premium service. But, we wanted to go with the free resources and we chose to incorporate the Like and Retweet APIs of Twitter. We have achieved our goal by

  • Adding a cron on the server which runs periodically.
  • Fetch the recent tweets of a user.
  • Like and Retweet the tweets received in a response.

Before writing a code for it, you should go through our previous article given below. Twitter API requires passing an access token in each request. And it requires integrating Twitter OAuth 2.0 flow into your application. I already wrote about this so don’t want to occupy extra space in this tutorial.

When you follow the above article, you will noticed I have passed a few scope parameters to the OAuth. These scopes are tweet.read users.read like.write tweet.write offline.access. It gets the required permissions from the user to perform desired tasks on their account. Using the offline.access scope, we receive the refresh token from Twitter which is then used to regenerate the expired access token.

Like and Retweet using PHP

At this stage, I assume you have integrated the Twitter OAuth and you have the access token stored in the database table.

Now, I am taking an example of Google’s Twitter profile. Let’s say we have to like and retweet Google’s tweets from our account. For that, I have to pick up their Twitter username which is Google itself. If you are not aware of how to find a username, then it can be retrieved from the URL. In the case of Google, it’s https://twitter.com/Google.

Finally, the below code would perform our task. This code will take only original tweets from the user(not tweets they retweeted) and perform the like, retweet operations on your account.

like-retweet.php

<?php
require_once 'config.php';

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

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

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

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

    	// Get Twitter's id of yours
    	$response = $client->request('GET', '/2/users/me', [
        	"headers" => [
            	"Authorization" => "Bearer ". $access_token
        	]
    	]);

    	$res = json_decode($response->getBody());
    	$twitter_user_id = $res->data->id;

    	$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());

    	if ( $res && !empty($res->data) ) {
        	foreach ( $res->data as $r ) {
            	// like a tweet
            	$response1 = $client->request("POST", "/2/users/$twitter_user_id/likes", [
                	"headers" => [
                    	"Authorization" => "Bearer ". $access_token
                	],
                	"json" => [
                    	"tweet_id" => $r->id
                	],
            	]);

            	// retweet a tweet
            	$response2 = $client->request("POST", "/2/users/$twitter_user_id/retweets", [
                	"headers" => [
                    	"Authorization" => "Bearer ". $access_token
                	],
                	"json" => [
                    	"tweet_id" => $r->id
                	],
            	]);
        	}
        	echo "Tweets liked and retweeted successfully.";
    	}
	} 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_like_retweet($username);
    	} else {
        	echo $e->getMessage();
    	}
	}
}

This PHP file you should set in the Cron as per your schedule. It will run as commands, fetch recent tweets from Google and like, retweet them on your account. Even if your access token expires, it’ll regenerate the token in the background without failing the operations.

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

2 thoughts on “Twitter API – Like And Retweet A Tweet Using PHP

Leave a Reply

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