rename widget script to getsc2clan
[sc2-widget] / getsc2clan
1 #!/usr/bin/env perl
2 use 5.024;
3 use warnings;
4 use utf8;
5
6 use Data::Dump qw( pp );
7 use LWP::Authen::OAuth2;
8 use JSON qw( decode_json );
9 use List::Util qw( all );
10
11 my ($profileid, $clanmatch) = @ARGV;  # clan host and name
12 $profileid and $profileid =~ /\A\d+\z/
13         or die "Usage: $0 <profile id> [<clan name>]\n";
14
15 my $bliz = LWP::Authen::OAuth2->new(
16         client_id               => '7f0f95ac9529474f854ee8d68a12c3e0',
17         client_secret           => 'Kfa8n98UAaDo4brOeqxe9C2kJE9pqpSd',
18         token_endpoint          => 'https://us.battle.net/oauth/token',
19         request_required_params => [qw( client_id client_secret grant_type )],
20 );
21 $bliz->request_tokens(grant_type => 'client_credentials');
22
23 sub blizget {
24         my $args = join('/', @_);
25         my $res = $bliz->get("https://us.api.blizzard.com/sc2/$args");
26         $res->is_success or die $res->status_line;
27         my $json = $res->decoded_content;
28         return decode_json($json);
29 }
30
31 # find largest group consisting entirely of clan members
32 # prefer deprecated interface to prevent costly ladder search
33 my $ladders = blizget(legacy => profile => 2 => 1 => $profileid => 'ladders');
34 my ($ladder) = (
35         sort { $b->{characters}->@* <=> $a->{characters}->@* } # population desc
36         grep {
37                 !$clanmatch or
38                 all { fc $_->{clanName} eq fc $clanmatch } $_->{characters}->@*
39         } # members
40         $ladders->{currentSeason}->@*
41 ) or die "No matching groups found\n";
42
43 say JSON->new->canonical->pretty->encode({
44         league   => ucfirst lc $ladder->{ladder}->[0]->{league},
45         division => $ladder->{ladder}->[0]->{ladderName},
46         rank     => $ladder->{ladder}->[0]->{rank},
47         tag      => $ladder->{characters}->[0]->{clanTag},
48         members  => [map { blizget(metadata => profile => 2 => 1 => $_->{id}) } $ladder->{characters}->@*],
49         # lacks mmr, fav race (available in new api)
50 });