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:
- twitteroauth library by Abraham Williams: https://github.com/abraham/twitteroauth
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:
- @trendwordus https://twitter.com/trendwordus (for US)
- @web_trendjp https://twitter.com/web_trendjp (for JP)
- Source: source-1.1.zip (33KB) (requires PHP 5.3 or later)
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:
- Get your follower IDs
- Get your following IDs
- 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.
Nice share :)
may i ask how to use that autofollow function on complete php code ?
Thank you :)
Thank you :)
I put a complete code at the beginning of this post.
Note that you need put the library code “twitteroauth.php” (available at https://github.com/abraham/twitteroauth) on ./lib directory.
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
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.Did you solve the problem? If not, would you check your file structure as well? Here is my file structure:
“OAuth.php” and “twitteroauth.php” are from twitteroauth library at https://github.com/abraham/twitteroauth
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?
You need the user’s ID to combine the user into the
autoFollow()
function. You can use theusers/show
Twitter API to get a user’s ID by the user name.The following is a simple example:
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!
You need to introduce an argument
$from_user
for theautoFollow
function as follows: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:
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?
How did you check the following numbers?
If you did with a Web browser, please try page refreshes by “Ctrl + F5” reload.
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.
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:
Uh…
statuses/friends
is the deprecated API. I’ll revise my code.https://dev.twitter.com/docs/api/1/get/statuses/friends
I’ve revised my code. Please see: http://techiella.x0.com/practice-of-programming/how-to-auto-follow-on-twitter-by-twitter-api-php/
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();
?>
I mean Following
Does this only work for the first like 20 recent followers?
It is working for recent followers so i guess so
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.
I’ve revised my code and posted here: http://techiella.x0.com/practice-of-programming/how-to-auto-follow-on-twitter-by-twitter-api-php/
I’ve revised my code; the following code is without deprecated Twitter API calls:
This code works fine for one of my twitter bots (@trendwordus): http://twitter.com/#!/trendwordus
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.
@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.
I keep getting this error
Warning: Invalid argument supplied for foreach() (line 15 and 22)
Or is this just an outdated code? and wouldnt work anyways
How about check the variable
$followers
is null or not?If
$followers
is null, please check the code (at line 13) works properly: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.
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
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:I get a long list of numbers, and commas. (guessing IDs)
Thank you. That means
$followers
is O.K, not null. How about$friends
?Got the same, a list of ID’s so Im guessing that works also
> 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?I get NULL NULL
Your result of
var_dump($followers)
contains["ids"]=>
like the following?OK Ima noob! I have no idea what your last comment is talking about :(
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″}”
And when I do var_dump($followers->ids);
I get NULL
not sure I even did this one right though
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);
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?
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
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?
If your result by this code is not NULL, we could solve the problem.
Ok, this is what i got
string(1) “{“
> 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()”
Warning: Invalid argument supplied for foreach()
:(
> 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”.
Went to the file viz web browser
Would you try SSH? Your dump result is something strange (because of viz web browser(?))
FYI: “How do I get and use SSH access?”
http://support.hostgator.com/articles/getting-started/how-do-i-get-and-use-ssh-access
I meant “via web browser”
And I have no idea about SSH access. I got other Twitter Oauth scripts to work, but this is just not working
You can follow the instruction.
“How do I get and use SSH access?”
http://support.hostgator.com/articles/getting-started/how-do-i-get-and-use-ssh-access
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?
O.K. The code can be run on Windows or Linux PC. You could check HostGator specific problem or not.
if executed via browser riding a apache hosting server has to work but fails foreach () in you not work?
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
If anybody can get this working, I will Paypal $5 :(
I would eventually like to follow from keywords also
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
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
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()
Yea good luck on that lol I been trying to get this script to work for about a month
you worked??
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?
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?
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.
Thank you so much!
Warning: Invalid argument supplied for foreach()
This script works with api 1.1?
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.
php give me an example pleas
What do you mean?
Heyy i have got error Cannot use object of type stdClass as array on line 15 when i’m use your revision code.
Error on this line, you mean?
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();
Error on this line foreach ($followers[“ids”] as $i => $id) {
Please try the code (titled “Whole Code for Twitter Auto-Follow Function”) at the top of this article, which is the latest version.
I’ve tried the code (titled “Whole Code for Twitter Auto-Follow Function”). there is no error code but only displays a blank page
This is an auto-follow script, prints nothing.
does this script only increase following it instead of followers?
This script just does follow back, not increase your followers.
ok thanks :)