Twitter Auto-Follow PHP Script


/ Published in: PHP
Save to your folder(s)

Simple PHP script which allows you to specify your twitter log in details and a search term, then automatically follow users who have tweeted that term. Code is released as Open Source, use it as you wish - please leave my URL in the commented section though.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. // Twitter Auto-follow Script by Dave Stevens - http://davestevens.co.uk
  4.  
  5. // Set the twitter user
  6. $user = "";
  7. $pass = "";
  8.  
  9. // Set the term you want to follow (e.g. "soccer")
  10. $term = "";
  11.  
  12. // Get already followed
  13. $userApiUrl = "http://twitter.com/statuses/friends.json";
  14.  
  15. $ch = curl_init($userApiUrl);
  16. curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
  17. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  18.  
  19. $apiresponse = curl_exec($ch);
  20.  
  21.  
  22. $followed = array();
  23.  
  24. if ($apiresponse) {
  25. $json = json_decode($apiresponse);
  26. if ($json != null) {
  27. foreach ($json as $u) {
  28. $followed[] = $u->name;
  29. }
  30. }
  31. }
  32.  
  33. $userApiUrl = "http://search.twitter.com/search.json?q=" . $term . "&rpp=100";
  34.  
  35. $ch = curl_init($userApiUrl);
  36. curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
  37. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  38.  
  39. $apiresponse = curl_exec($ch);
  40.  
  41.  
  42. if ($apiresponse) {
  43. $results = json_decode($apiresponse);
  44. $count = 20;
  45.  
  46. if ($results != null) {
  47.  
  48. $resultsArr = $results->results;
  49.  
  50. if (is_array($resultsArr)) {
  51.  
  52. foreach ($resultsArr as $result) {
  53.  
  54. $from_user = $result->from_user;
  55.  
  56. if (!in_array($from_user,$followed)) {
  57.  
  58. $ch = curl_init("http://twitter.com/friendships/create/" . $from_user . ".json");
  59. curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
  60. curl_setopt($ch, CURLOPT_POST, 1);
  61. curl_setopt($ch, CURLOPT_POSTFIELDS,"follow=true");
  62. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  63.  
  64. $apiresponse = curl_exec($ch);
  65.  
  66. if ($apiresponse) {
  67. $response = json_decode($apiresponse);
  68.  
  69. if ($response != null) {
  70. if (property_exists($response,"following")) {
  71. if ($response->following === true) {
  72. echo "Now following " . $response->screen_name . "\n";
  73. } else {
  74. echo "Couldn't follow " . $response->screen_name . "\n";
  75. }
  76. } else {
  77. echo "Follow limit exceeded, skipped " . $from_user . "\n";
  78. }
  79. }
  80.  
  81. }
  82.  
  83. curl_close($ch);
  84.  
  85. } else {
  86. echo "Already following " . $from_user . "\n";
  87. }
  88.  
  89. }
  90.  
  91. }
  92.  
  93. }
  94.  
  95.  
  96. }
  97.  
  98. ?>

URL: http://davestevens.co.uk

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.