How to Auto Follow on Twitter by Twitter API v1.1 & PHP

If you want to follow all of your Twitter Followers, you can automate it with Twitter API & PHP. I’ll introduce a simple implementation with the twitteroauth library by Abraham Williams:

The code in this post works with the version 1.1 of Twitter API.

The followings are sample applications, which tweet top 10 hourly Google trends, with the auto-follow function that I’ll describe in this post:

Whole Code for Twitter Auto-Follow Function

An auto-follow function can be written in simple form with the twitteroauth library as follows:

<?php
require_once 'lib/twitteroauth.php';

define('CONSUMER_KEY', 'your_consumer_key');
define('CONSUMER_SECRET', 'your_consumer_secret');
define('ACCESS_TOKEN', 'your_access_token');
define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');

function auto_follow()
{
    $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

    $followers = $toa->get('followers/ids', array('cursor' => -1));
    $friends = $toa->get('friends/ids', array('cursor' => -1));

    foreach ($followers->ids as $i => $id) {
        if (empty($friends->ids) or !in_array($id, $friends->ids)) {
            $ret = $toa->post('friendships/create', array('user_id' => $id));
        }
    }
}

auto_follow();

How to Execute

Copy & paste the code above to a file and save it as auto_follow.php. Note that you need to put two twitteroauth library scripts (OAuth.php and twitteroauth.php) in ./lib directory:

$ ls -R ./
lib/                            auto_follow.php

./lib:
OAuth.php               twitteroauth.php

Then, replace the keys with your own ones in the following code:

define('CONSUMER_KEY', 'your_consumer_key');
define('CONSUMER_SECRET', 'your_consumer_secret');
define('ACCESS_TOKEN', 'your_access_token');
define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');

Twitter API key & tokens can be obtained from https://dev.twitter.com/apps/new.

*Important*: In order to execute the auto-follow code, “Read and Write” setting for “Application type” is required, which can be confiugred at your application setting page on dev.twitter.com.

After the setteing above is done, you can execute the code like this:

$ php auto_follow.php

Based on this execution, you can build an automation system that performs auto-follow periodically with “cron” command (e.g. every 1 hours).

The remaining of this post is short descriptions of the code, which consists of three parts:

  1. Get your follower IDs
  2. Get your following IDs
  3. Follow a user

So, let’s look into each one.

How to Get Your Follower IDs

Your follower IDs can be taken by the following code at the line 13:

    $followers = $toa->get('followers/ids', array('cursor' => -1));

How to Get Your Following IDs

Get method with the arg friends/ids returns your following user IDs:

    $friends = $toa->get('friends/ids', array('cursor' => -1));

How to Code an Auto Follow Function

    foreach ($followers->ids as $i => $id) {
        if (empty($friends->ids) or !in_array($id, $friends->ids)) {
            $ret = $toa->post('friendships/create', array('user_id' => $id));
        }
    }

The code above traverses your follower IDs, and then follows a user if the user ID is not contained in your following IDs. “Do follow” can be performed by a post method with the arg friendships/create and specifying the target ID, which you want to follow, as array('user_id' => $id).

Summary

The last code line is the call statement for auto_follow() function:

auto_follow();

I hope this how-to is helpful for you.

81 thoughts on “How to Auto Follow on Twitter by Twitter API v1.1 & PHP

  1. Ecletticamente

    Hi Techiella,
    Thanks for sharing your post is great only have a little problem.

    I did everything you sayd but my profile has not been updated creating new connection to other users.

    – I have included the library and I have echo some part so I know it get the user ID (it should work)
    – I have also set my application with write permission (You didnt mentioned about application setting and how to get consumer key)

    Could you give me some hint?
    Cheers
    Ecletticamente

    1. techiella Post author

      Thank you for your comment with a note about application permission.

      Did you check the $ret value in the following code? It might be helpful.

      $ret = $toa->post('friendships/create', array('user_id' => $id));
      
    2. techiella Post author

      Did you solve the problem? If not, would you check your file structure as well? Here is my file structure:

      %ls -R ./
      lib/                            autoFollow.php
      
      ./lib:
      OAuth.php               twitteroauth.php
      

      “OAuth.php” and “twitteroauth.php” are from twitteroauth library at https://github.com/abraham/twitteroauth

  2. Ron

    I got a code that looks up certain words in the tweets, and these people I want to follow. If I got a match I got the poster’s user name. How can I combine this user name into above script?

    1. techiella Post author

      You need the user’s ID to combine the user into the autoFollow() function. You can use the users/show Twitter API to get a user’s ID by the user name.

      The following is a simple example:

      function autoFollow() {
      
         ...
      
          foreach ($followers->users as $follower) {
              $followerIds[] = $follower->id;
          }
      
         // Append an additional user to follow.
         $userToFollow = $toa->get('users/show', array('screen_name' => 'USER_NAME_TO_FOLLOW'));
         $followerIds[] = $userToFollow->id;
      
         ...
      
      
  3. Ron

    I still cannot make it ;-(
    Here is the entire code I tried:

    host = “http://search.twitter.com/”;

    // Prepare content – looking for tweets which include the word NLP

    $search = $twitter->get(‘search’, array(‘q’ => ‘NLP’, ‘rpp’ => 2));
    $twitter->host = “https://api.twitter.com/1/”;

    foreach($search->results as $tweet) {
    $haystack=$tweet->text;

    $from_user = $tweet->from_user;

    echo “$from_usern”;

    autoFollow();

    }

    function autoFollow() {
    $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

    $followers = $toa->get(‘statuses/followers’, array(‘cursor’ => -1));
    $followerIds = array();
    foreach ($followers->users as $follower) {
    $followerIds[] = $follower->id;
    }

    // Append an additional user to follow.
    // tried a fixed user: $userToFollow = $toa->get(‘users/show’, array(‘screen_name’ => ‘rsswebde’));
    $userToFollow = $toa->get(‘users/show’, array(‘screen_name’ => $from_user));
    $followerIds[] = $userToFollow->id;
    $friends = $toa->get(‘statuses/friends’);
    $friendIds = array();
    foreach ($friends as $friend) {
    $friendIds[] = $friend->id;
    }

    foreach ($followerIds as $id) {
    if (empty($friendIds) or !in_array($id, $friendIds)) {
    $toa->post(‘friendships/create’, array(‘user_id’ => $id));
    }
    }
    }

    ?>

    Thanks for you help!

    1. techiella Post author

      You need to introduce an argument $from_user for the autoFollow function as follows:

      function autoFollow($from_user)
      {
          $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
      
          $followers = $toa->get('statuses/followers', array('cursor' => -1));
          $followerIds = array();
          foreach ($followers->users as $follower) {
              $followerIds[] = $follower->id;
          }
      
          // Append an additional user to follow.
          // tried a fixed user: $userToFollow = $toa->get(‘users/show’, array(‘screen_name’ => ‘rsswebde’));
          $userToFollow = $toa->get('users/show', array('screen_name' => $from_user));
          $followerIds[] = $userToFollow->id;
      
          ...
      }
      

      For just in case, please check the file structure as well; note that you need to put twitteroauth library scripts (“OAuth.php” and “twitteroauth.php”) in the “./lib” directory:

      %ls -R ./
      lib/                            autoFollow.php
       
      ./lib:
      OAuth.php               twitteroauth.php
      
  4. Ron

    Still no luck!

    <?php
    require_once('twitteroauth.php');

    OAuth.php and twitteroauth.php are therefore in the same directory as the autoFollow.php

    I don't get any error, but also no increase of the Following numbers.

    Any idea what I am doing wrong?

    1. techiella Post author

      How did you check the following numbers?

      If you did with a Web browser, please try page refreshes by “Ctrl + F5” reload.

  5. Ron

    Good question! I used shift reload in firefox and it does not increase the numbers I am following.
    Your question inspires me, if there is a way to ask within the program for successful create that friendship.
    And if it is possible to get the number before and after.

    1. techiella Post author

      Please make sure that page refreshes should be done with “Ctrl+F5”, not “Shift+F5”.

      The number of users with friendship can be counted like the following:

      $friends = $toa->get(‘statuses/friends’);
      $friendIds = array();
      foreach ($friends as $friend) {
          $friendIds[] = $friend->id;
      }
      echo count($friendIds);
      
    2. techiella Post author

      Uh… statuses/friends is the deprecated API. I’ll revise my code.

      https://dev.twitter.com/docs/api/1/get/statuses/friends

      GET statuses/friends

      Updated on Mon, 2011-07-04 08:55

      This method is deprecated as it will only return information about users who have Tweeted recently. It is not a functional way to retrieve all of a users followers. Instead of using this method use a combination of GET friends/ids and GET users/lookup.

      Returns a user’s friends, each with current status inline. They are ordered by the order in which the user followed them, most recently followed first, 100 at a time. (Please note that the result set isn’t guaranteed to be 100 every time as suspended users will be filtered out.)

      Use the cursor option to access older friends.

      With no user specified, request defaults to the authenticated user’s friends.

      It is also possible to request another user’s friends list via the id, screen_name or user_id parameter.

  6. chris

    I can not get it to work either. I can find the ID and echo them and get no error. But my followers do not change? Here is my code :

    get(‘statuses/followers’, array(‘cursor’ => -1));
    $followerIds = array();
    foreach ($followers->users as $follower) {
    $followerIds[] = $follower->id;
    }

    $friends = $toa->get(‘statuses/friends’);
    $friendIds = array();
    foreach ($friends as $friend) {
    $friendIds[] = $friend->id;
    }

    foreach ($followerIds as $id) {
    if (empty($friendIds) or !in_array($id, $friendIds)) {
    $toa->post(‘friendships/create’, array(‘user_id’ => $id));
    echo “test”;
    }
    }
    }

    autoFollow();
    ?>

    1. techiella Post author

      Thank you for your comment.

      You’re probably right. I’ve checked the latest API documentaion on dev.twitter.com, which says
      “This method is deprecated as it will only return information about users who have Tweeted recently.” (https://dev.twitter.com/docs/api/1/get/statuses/followers)

      I’ve also just noticed that my code is based on deprecated APIs. I need to revise my code.

      GET statuses/followers

      Updated on Mon, 2011-07-04 08:55

      This method is deprecated as it will only return information about users who have Tweeted recently. It is not a functional way to retrieve all of a users followers. Instead of using this method use a combination of GET followers/ids and GET users/lookup.

      Returns the authenticating user’s followers, each with current status inline. They are ordered by the order in which they followed the user, 100 at a time. (Please note that the result set isn’t guaranteed to be 100 every time as suspended users will be filtered out.)

      Use the cursor parameter to access earlier followers.

      Instead of using this method to analyze a user’s followers, consider using a combination of followers/ids and users/lookup instead.

  7. techiella Post author

    I’ve revised my code; the following code is without deprecated Twitter API calls:

    function autoFollow()
    {
        $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    
        $followers = $toa->get('followers/ids', array('cursor' => -1));
        $followerIds = array();
        foreach ($followers->ids as $i => $id) { // Store the latest 100 followers.
            $followerIds[] = $id;
            if ($i == 99) break;
        }
    
        $friends = $toa->get('friends/ids', array('cursor' => -1));
        $friendIds = array();
        foreach ($friends->ids as $i => $id) { // Store the latest 100 friends.
            $friendIds[] = $id;
            if ($i == 99) break;
        }
    
        foreach ($followerIds as $id) {
            if (empty($friendIds) or !in_array($id, $friendIds)) {
                $ret = $toa->post('friendships/create', array('user_id' => $id));
            }
        }
    }
    

    This code works fine for one of my twitter bots (@trendwordus): http://twitter.com/#!/trendwordus

  8. Ron

    It still did not work for me, … till I found that oAuth access was read+write and the access token only read, … fixed that, and now it is posting too.

    Thanks for the help.

  9. Prad

    @Ron, how did you make it work? what was your final code? I have been working on this but can’t seem to make it work either. The settings on the app is correct.
    Hope you publish your code somewhere on the web.

    1. techiella Post author

      How about check the variable $followers is null or not?

      If $followers is null, please check the code (at line 13) works properly:

      $followers = $toa->get('followers/ids', array('cursor' => -1));
      
      1. DJ

        Ok Im a noob! lol I got a auto tweet script to work.. and an auto shoutout script to work. But Idk how to check if a variable is null or not.

  10. DJ

    I copied and pasted the code in the begining, only replaced my access codes, and I put ?> at the end…. it should work shouldn’t?? I dont get why its not working

    1. techiella Post author

      Yes, the code should works. I’m actually using the same code on the article, and it works fine.

      But if not works, there could be something wrong. So, let’s check the variable; var_dump() is useful. You can check the content of $followers like this:

      $followers = $toa->get('followers/ids', array('cursor' => -1));
      var_dump($followers);
      
        1. techiella Post author

          Thank you. That means $followers is O.K, not null. How about $friends?

          $friends = $toa->get('friends/ids', array('cursor' => -1));
          var_dump($friends);
          
        2. techiella Post author

          > Got the same, a list of ID’s so Im guessing that works also

          Thank you. Yes, it’s working…
          You still get “Warning: Invalid argument supplied for foreach()”?
          Would do you check ids like the following?

          var_dump($followers->ids);
          var_dump($friends->ids);
          
        3. techiella Post author

          Your result of var_dump($followers) contains ["ids"]=> like the following?

          object(stdClass)#1 (5) {
            ["previous_cursor_str"]=>
            string(1) "0"
            ["next_cursor"]=>
            int(0)
            ["ids"]=>
            array(640) {
              [0]=>
              int(286959365)
              [1]=>
              int(433241684)
          ...
          
  11. DJ

    When I do var_dump($followers);

    I get this

    string(1247) “{“previous_cursor_str”:”0″,”next_cursor”:0,”ids”:[BUNCH OF IDs],”previous_cursor”:0,”next_cursor_str”:”0″}”

  12. DJ

    Should I do it like This?

    function autoFollow()
    {
    $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

    $followers = $toa->get(‘followers/ids’, array(‘cursor’ => -1));
    $followerIds = array();
    }
    var_dump($followers);

    OR LIKE THIS?

    $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

    $followers = $toa->get(‘followers/ids’, array(‘cursor’ => -1));
    $followerIds = array();

    var_dump($followers);

    1. techiella Post author

      It should be second one.

      > string(1247) “{“previous_cursor_str”:”0″,”next_cursor”:0,”ids”:[BUNCH OF IDs],”previous_cursor”:0,”next_cursor_str”:”0″}”

      Thank you. I can see the result is different from I expect…

      By the way, I’m using PHP v5.2.17. How about you?

  13. DJ

    I have no idea… Im in my cpanel . I just create a new file with .php extension. Then put my code into file. Im with HostGator

    1. techiella Post author

      HostGator provides PHP 5.2.17 and 5.3.10, so it’s O.K.

      Would do you try a little bit different code for dump?

      $followers = $toa->get('followers/ids', array('cursor' => -1));
      var_dump($followers["ids"]);
      

      If your result by this code is not NULL, we could solve the problem.

    2. techiella Post author

      > string(1) “{“

      Thank you. This result is also something strange…

      Anyway, would do you try the code below?
      I hope you won’t get “Warning: Invalid argument supplied for foreach()”

      <?php
      require_once 'lib/twitteroauth.php';
       
      define('CONSUMER_KEY', 'your_consumer_key');
      define('CONSUMER_SECRET', 'your_consumer_secret');
      define('ACCESS_TOKEN', 'your_access_token');
      define('ACCESS_TOKEN_SECRET', 'your_access_token_secret');
       
      function autoFollow()
      {
          $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
       
          $followers = $toa->get('followers/ids', array('cursor' => -1));
          $followerIds = array();
          foreach ($followers["ids"] as $i => $id) {
              $followerIds[] = $id;
              if ($i == 99) break; // Deal with only the latest 100 followers.
          }
       
          $friends = $toa->get('friends/ids', array('cursor' => -1));
          $friendIds = array();
          foreach ($friends["ids"] as $i => $id) {
              $friendIds[] = $id;
              if ($i == 99) break; // Deal with only the latest 100 friends.
          }
       
          foreach ($followerIds as $id) {
              if (empty($friendIds) or !in_array($id, $friendIds)) {
                  $ret = $toa->post('friendships/create', array('user_id' => $id));
              }
          }
      }
       
      autoFollow();
      
    3. techiella Post author

      > string(1247) “{“previous_cursor_str”:”0″,”next_cursor”:0,”ids”:[BUNCH OF IDs],”previous_cursor”:0,”next_cursor_str”:”0″}”

      How did you exectute the code for the dump?

      In my case, I login with SSH on a host server, then exectute the command “php autoFollow.php”.

  14. DJ

    And I have no idea about SSH access. I got other Twitter Oauth scripts to work, but this is just not working

      1. DJ

        Im not even sure what SSH access is… and besides the other Twitter Oauth scripts work perfect! So this one should be the same way shouldn’t it?

    1. techiella Post author

      O.K. The code can be run on Windows or Linux PC. You could check HostGator specific problem or not.

      1. alex

        if executed via browser riding a apache hosting server has to work but fails foreach () in you not work?

  15. DJ

    I downloaded WinSCP and it doesnt even let me login. It says my login is wrong. But its not, I login everyday via FileZilla. There still should be a way to get this to work via web browser/cpanel like I do all of the other php scripts

  16. DJ

    If you can get this working I am willing to pay. would really like to get auto follow by keyword, and auto unfollow who dont follow me working

  17. DJ

    Somebody else told me to add

    if (is_array($followers))
    {

    or

    if (is_array($followers->ids))
    {

    before foreach…

    but nope still doesnt work… I get no error with that code.. but it doesnt work either

  18. maxbux

    Thanks for the script. I however get the following when running it;

    PHP Notice: Undefined property: stdClass::$ids
    PHP Warning: Invalid argument supplied for foreach()

  19. Ugur

    Thank you for this nice article.

    I am trying to send followers via Twitter API. I am developing an application which will send followers to the application’s other users. I can make this happen with friendships/create, but when I try to send 10 or more followers, the server gives 30 seconds connection timeout error. I can send 2 or 3 followers but I have to do it more quickly. Otherwise, server requirements will seriously increase.

    When someone authorizes my app, they will earn 50 followers. I mean 50 of other users who authorized APP will follow that one’s account. I mean, what I want is not follow multiple accounts with one account. I want multiple accounts to follow one account. Can you help me or give me an idea?

    1. techiella Post author

      Thank you for your comment.

      This is just an idea intended to avoid 30 seconds connection timeout error.
      How about trying to send only 1 follower in one execution, then repeat the execution 10 or more times?

  20. Bassam Jarad

    First of all, thank you very much for the code. It was very helpful to me.

    For the guys here having trouble with $followers->ids being NULL or being returned as string. I fixed that simply by adding this line:
    $toa->decode_json = true;

    below:
    $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

    I hope this helps.

    1. techiella Post author

      Yes, it works.

      If not, check the version number of Twitter API in twitteroauth.php (a code in twitteroauth library):
      public $host = "https://api.twitter.com/1.1/";
      The version 1.0 of Twitter API is now deprecated, so set the number to 1.1.

  21. Jack

    Heyy i have got error Cannot use object of type stdClass as array on line 15 when i’m use your revision code.

    1. techiella Post author

      Error on this line, you mean?

      $friends = $toa->get('friends/ids', array('cursor' => -1));
      
  22. Jack

    Error on this line

    get(‘followers/ids’, array(‘cursor’ => -1));
    $followerIds = array();
    foreach ($followers[“ids”] as $i => $id) {
    $followerIds[] = $id;
    if ($i == 99) break; // Deal with only the latest 100 followers.
    }

    $friends = $toa->get(‘friends/ids’, array(‘cursor’ => -1));
    $friendIds = array();
    foreach ($friends[“ids”] as $i => $id) {
    $friendIds[] = $id;
    if ($i == 99) break; // Deal with only the latest 100 friends.
    }

    foreach ($followerIds as $id) {
    if (empty($friendIds) or !in_array($id, $friendIds)) {
    $ret = $toa->post(‘friendships/create’, array(‘user_id’ => $id));
    }
    }
    }

    autoFollow();

      1. techiella Post author

        Please try the code (titled “Whole Code for Twitter Auto-Follow Function”) at the top of this article, which is the latest version.

        1. Jack

          I’ve tried the code (titled “Whole Code for Twitter Auto-Follow Function”). there is no error code but only displays a blank page

Comments are closed.