Worth Retweeting

by @edent

Recently, I've seen a lot of people retweeting content that I've already seen.
"How very annoying," I thought to myself, "I wish someone would do something about that."

So, like any self-respecting geek, I rolled up my sleeves and got on with it 🙂

My PHP is a little rusty, but luckily the twitter API is fairly easy.

My first pass was an abject lesson of inefficiency and illiteracy. Here was my thought process...

  1. Get the ID of the person I want to retweet
  2. Get all of My Followers
  3. Get the people that my followers follow
  4. See how many of them follow the person I want to retweet.

This did work but it was horribly slow. Also, the twitter API is limited to 100 requests per hour. If you have over 100 followers, you won't get anywhere.

However, on closer reading of the API - and a little tiramisu - I had the answer.

  1. Get my followers
  2. Get the retweetee's followers
  3. See how many from (1) occur in (2)

This can be accomplished in a few lines of PHP.

To get the first 5,000 followers for any user - use this URL

$myfollowers_url = "http://twitter.com/followers/ids.json?screen_name=" . $my_name . "&page;=1";

Then use curl to grab the data -

$curl_handle=curl_init();curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle,CURLOPT_URL,$myfollowers_url);
$myfollowers_json = curl_exec($curl_handle);
curl_close($curl_handle);

You can turn the resulting JSON into an array thus:

$myfollowers_array = explode("," , $myfollowers_string);

You do the same for the person you wish to retweet.
PHP provides the method array_intersect() to see how many elements from array1 occur in array2.

$samefollowers_count = count(array_intersect($myfollowers_array,$theirfollowers_array));

From there, the maths is trivial.

$myfollowers_count = count($myfollowers_array);
$theirfollowers_count = count($theirfollowers_array);
$ratio = $samefollowers_count / $myfollowers_count;

Hey presto! Done. You can view the beta at https://shkspr.mobi/twitter/retweet.php

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.