DEV Community

manuel
manuel

Posted on • Edited on

How to find talkaktive friends on Twitter with Twitter's REST Api

I wrote about How to find out who don't follow back with Twitter's REST Api and How I track unfollower with Twitter's REST Api.

Now, here is my example how to find the 10 most talkative friends on Twitter using Laravel's collections and abraham/twitteroauth for Twitter's REST Api.

<?php
require "vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;
use Tightenco\Collect\Support\Collection;

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

$now     = new \DateTime();
$content = $api->get("friends/ids", [
    'screen_name' => 'mnlwldr',
    'count'       => 5000,
]);


collect($content->ids)
    ->chunk(100)
    ->flatMap(function (Collection $ids) use ($api) {
        return $api->get('users/lookup', [
            'user_id' => $ids->implode(','),
        ]);
    })
    ->mapWithKeys(function (stdClass $profile) use ($now) {
        /* The date when the profile was created */
        $profile_created_at = new DateTime(date('Y-m-d', strtotime($profile->created_at)));

        /* creation date till today in days */
        $days_since_profile_created = $profile_created_at->diff($now)->days;

        /* return the screen name as key and the statuses divided by the days */
        return [$profile->screen_name => $profile->statuses_count / $days_since_profile_created];
    })
    /* Sort it descending by ratio */
    ->sort(function ($a, $b) {
        return $b <=> $a;
    })
    /* We only need the 10 most active users */
    ->take(10)
    /* print out the ratio per day with the link to the profile */
    ->each(function ($ratio, $user) {
        print '[' . number_format($ratio, 2) . ' tweets / day] ' . 'https://twitter.com/' . $user . PHP_EOL;
    });
Enter fullscreen mode Exit fullscreen mode

Example output:

[92.10 tweets / day] https://twitter.com/User_1
[50.00 tweets / day] https://twitter.com/User_2
[49.32 tweets / day] https://twitter.com/User_3
[44.42 tweets / day] https://twitter.com/User_4
[40.39 tweets / day] https://twitter.com/User_5
[39.68 tweets / day] https://twitter.com/User_6
[38.08 tweets / day] https://twitter.com/User_7
[35.54 tweets / day] https://twitter.com/User_8
[32.92 tweets / day] https://twitter.com/User_9
[32.43 tweets / day] https://twitter.com/User_10

Enter fullscreen mode Exit fullscreen mode

Top comments (0)