Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use LWP::UserAgent;
use JSON;
use Getopt::Long qw(:config posix_default no_ignore_case gnu_compat);
use Pod::Usage qw(pod2usage);
sub ranking_json_url_for {
my $genre = shift;
return "https://itunes.apple.com/jp/rss/topfreeapplications/limit=100/genre=${genre}/json";
}
sub get_ranking_from_store {
my %args = @_;
my $genre = $args{genre};
my $url = ranking_json_url_for($genre);
my $res = LWP::UserAgent->new->get($url);
return unless $res->is_success;
my $json = JSON->new->utf8->decode($res->content);
my $rank = 0;
for (my $i = 0; $i < 100; $i++) {
my $entry = $json->{feed}->{entry}->[$i];
if ($entry->{id}->{attributes}->{"im:id"} eq $args{app_id}) {
$rank = $i + 1;
return +{
ranking => $rank,
title => $entry->{title}->{label},
link => $entry->{id}->{label},
genre => $entry->{category}->{attributes}->{label},
};
}
}
return; # nothing
}
sub current_time {
my @t = localtime;
sprintf '%02d:%02d', $t[2], $t[1];
}
sub generate_slack_text {
my %args = @_;
my $r = $args{ranking};
my $t = current_time();
sprintf "<%s|%s> は%s(無料)で %d 位でした (%s)",
$r->{link}, $r->{title}, $r->{genre}, $r->{ranking}, $t;
}
sub post_to_slack {
my %args = @_;
my $url = delete $args{slack}->{url};
my $payload = JSON->new->utf8->encode({
%{ $args{slack} },
text => generate_slack_text(ranking => $args{ranking}),
});
LWP::UserAgent->new->post($url => { payload => $payload });
}
MAIN: {
GetOptions(
'store_genre=s' => \my $genre,
'store_app_id=s' => \my $app_id,
'slack_url=s' => \my $slack_url,
'slack_channel=s' => \my $slack_channel,
'slack_username=s' => \my $slack_username,
'slack_icon_url=s' => \my $slack_icon_url,
'help|h' => \my $help,
);
pod2usage(1) if $help;
my $rank_info = get_ranking_from_store(genre => $genre, app_id => $app_id);
my $slack_info = {
url => $slack_url,
($slack_channel ? (channel => $slack_channel) : ()),
($slack_username ? (username => $slack_username) : ()),
($slack_icon_url ? (icon_url => $slack_icon_url) : ()),
};
post_to_slack(slack => $slack_info, ranking => $rank_info);
}
__END__
=head1 NAME
ios_ranking_to_slack.pl
=head1 SYNOPSIS
B<ios_ranking_to_slack.pl> [OPTIONS]
=head1 OPTIONS
=over 8
=item B<-h|--help>
print help.
=item B<--store_genre>
App Store genre id (e.g. 6023)
=item B<--store_app_id>
App Store application id (e.g. 1234567890)
=item B<--slack_url>
Slack Webhook URL
=item B<--slack_channel>
Optional: Slack channel or user if want to override webhook definition.
=item B<--slack_username>
Optional: Slack bot name if want to override webhook definition.
=item B<--slack_icon_url>
Optional: Slack bot icon if want to override webhook definition.
=back
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment