Skip to content

Instantly share code, notes, and snippets.

@snarkyboojum
Created April 16, 2011 06:51
Show Gist options
  • Save snarkyboojum/922935 to your computer and use it in GitHub Desktop.
Save snarkyboojum/922935 to your computer and use it in GitHub Desktop.
DailyMile comment(ers) script
use Modern::Perl;
use LWP::Simple;
use Data::Dumper;
use JSON;
my $USERNAME = 'snarkyboojum';
$USERNAME = $ARGV[0] if (defined $ARGV[0]);
my $DEBUG = 0;
my $WAIT_INTERVAL_SECS = 3;
# dodgey way to track pagination globally
my $pagination = 1;
# commentors hash, keyed by username, value is the count
my %commentors = ();
getCommentors(\%commentors);
showTopCommentors(\%commentors);
# e.g. http://api.dailymile.com/people/snarkyboojum/entries.json
sub getCommentors {
my $c = shift;
# template for getting entries RESTfully
my $getEntriesUrl = qq{http://api.dailymile.com/people/$USERNAME/entries.json};
my $pages_left = 1;
my $action;
# get an entry e.g. http://api.dailymile.com/entries/6531042.json
while ( $pages_left ) {
$action = $getEntriesUrl . qq{?page=$pagination};
my $data = getEntries($action);
$pages_left = pagesLeft($data);
$pagination++;
# process JSON data
if ($pages_left && defined $data) {
foreach my $entry (@{ $data->{'entries'} }) {
foreach my $comments (@{ $entry->{'comments'} }) {
my $display_name = $comments->{'user'}{'display_name'};
my $name = $comments->{'user'}{'username'};
say Dumper($comments) if $DEBUG;
# ignore ourselves :)
next if (lc $name eq lc $USERNAME);
# populate our comment hash
if (! exists $c->{$display_name} ) {
$c->{$display_name} = 1;
}
else {
$c->{$display_name}++;
}
}
}
}
# let's not be naughty - play by DM API rules
sleep $WAIT_INTERVAL_SECS;
}
}
sub showTopCommentors {
my $c = shift;
say Dumper($c) if $DEBUG;
my @top = reverse sort { $c->{$a} <=> $c->{$b} } keys %$c;
my $place = 1;
foreach my $id (@top) {
print "$place\. $id (" , $c->{$id}, ")\n";
$place++;
}
}
sub getEntries {
my $url = shift;
say "Getting entries with: [$url]";
# use LWP::Simple::get() to get JSON data
my $json_data = get($url);
die "Couldn't get data using action: [$url]\n" unless defined $json_data;
my $data = decode_json($json_data);
return $data;
}
sub pagesLeft {
my $response = shift;
return 0 if (! defined $response);
say Dumper($response) if $DEBUG;
if (scalar @{ $response->{'entries'} } == 0) {
return 0;
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment