Skip to content

Instantly share code, notes, and snippets.

@typhonius
Last active March 25, 2016 14:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save typhonius/6561610 to your computer and use it in GitHub Desktop.
Save typhonius/6561610 to your computer and use it in GitHub Desktop.
Real simple script to get my now playing from last.fm for chat
#!/usr/bin/env perl
use strict;
use warnings;
use HTTP::Request;
use LWP::UserAgent;
use JSON;
use utf8;
binmode(STDOUT, ":utf8");
my $last_fm = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks';
my $user = $ENV{'LAST_FM_USER'};
my $api = $ENV{'LAST_FM_KEY'};
# When you aren't currently listening a song and put the limit to 1, last.fm doesn't return it as a list.
# If you are listening to a song and you limit it to 1, it returns 2 tracks: currently playing and the previously listened one.
# Thus. For consistency, it's set to 2, so that it always returns a list.
my $limit = 2;
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => $last_fm . '&user=' . $user . '&api_key=' . $api . '&limit=' . $limit . '&format=json');
my $res = $ua->request($req);
if ($res->is_success) {
my $json = JSON->new->allow_nonref;
my $perl_scalar = $json->decode( $res->content );
foreach (@{ $perl_scalar->{recenttracks}->{track} }) {
my $name = $_->{name};
my $artist = $_->{artist}->{'#text'};
my $album = $_->{album}->{'#text'};
my $listening = "/me is listening to ${name} -by- ${artist}";
if ($album) {
$listening .= " -from- ${album}";
}
print $listening;
exit 0
}
}
else {
die ($res->content);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment