rename widget script to getsc2clan
[sc2-widget] / getsc2clan
diff --git a/getsc2clan b/getsc2clan
new file mode 100755 (executable)
index 0000000..6c02c0b
--- /dev/null
@@ -0,0 +1,50 @@
+#!/usr/bin/env perl
+use 5.024;
+use warnings;
+use utf8;
+
+use Data::Dump qw( pp );
+use LWP::Authen::OAuth2;
+use JSON qw( decode_json );
+use List::Util qw( all );
+
+my ($profileid, $clanmatch) = @ARGV;  # clan host and name
+$profileid and $profileid =~ /\A\d+\z/
+       or die "Usage: $0 <profile id> [<clan name>]\n";
+
+my $bliz = LWP::Authen::OAuth2->new(
+       client_id               => '7f0f95ac9529474f854ee8d68a12c3e0',
+       client_secret           => 'Kfa8n98UAaDo4brOeqxe9C2kJE9pqpSd',
+       token_endpoint          => 'https://us.battle.net/oauth/token',
+       request_required_params => [qw( client_id client_secret grant_type )],
+);
+$bliz->request_tokens(grant_type => 'client_credentials');
+
+sub blizget {
+       my $args = join('/', @_);
+       my $res = $bliz->get("https://us.api.blizzard.com/sc2/$args");
+       $res->is_success or die $res->status_line;
+       my $json = $res->decoded_content;
+       return decode_json($json);
+}
+
+# find largest group consisting entirely of clan members
+# prefer deprecated interface to prevent costly ladder search
+my $ladders = blizget(legacy => profile => 2 => 1 => $profileid => 'ladders');
+my ($ladder) = (
+       sort { $b->{characters}->@* <=> $a->{characters}->@* } # population desc
+       grep {
+               !$clanmatch or
+               all { fc $_->{clanName} eq fc $clanmatch } $_->{characters}->@*
+       } # members
+       $ladders->{currentSeason}->@*
+) or die "No matching groups found\n";
+
+say JSON->new->canonical->pretty->encode({
+       league   => ucfirst lc $ladder->{ladder}->[0]->{league},
+       division => $ladder->{ladder}->[0]->{ladderName},
+       rank     => $ladder->{ladder}->[0]->{rank},
+       tag      => $ladder->{characters}->[0]->{clanTag},
+       members  => [map { blizget(metadata => profile => 2 => 1 => $_->{id}) } $ladder->{characters}->@*],
+       # lacks mmr, fav race (available in new api)
+});