Skip to content

Instantly share code, notes, and snippets.

@eliocapelati
Last active June 13, 2022 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eliocapelati/30a41f6ea51b637a391fed7c0e71dfc8 to your computer and use it in GitHub Desktop.
Save eliocapelati/30a41f6ea51b637a391fed7c0e71dfc8 to your computer and use it in GitHub Desktop.
Usage: $ python3 lastfm_cli.py username
import requests
from requests import Session
import json
from pprint import pprint
import os
import sys
class Lastfm:
url = 'http://ws.audioscrobbler.com/2.0/'
s = Session()
def __init__(self, token=None):
self.token = token
def recent_tracks(self, user_name=None):
recent = self.s.get(self.url
+ "?method=user.getrecenttracks&user={USER_NAME}&api_key={API_KEY}&format=json&limit=1"
.format(USER_NAME=user_name, API_KEY=self.token))
if recent.status_code == 200:
recent_json = recent.json()
if 'error' in recent.json():
raise LastfmError(
code=recent_json['error'], message=recent_json['message'])
else:
return recent.json()
else:
raise LastfmError(message=recent.text)
class LastfmError(Exception):
"""Exception raised for errors in the request.
Lastfm erros code according https://www.last.fm/api/errorcodes:
1 : This error does not exist
2 : Invalid service -This service does not exist
3 : Invalid Method - No method with that name in this package
4 : Authentication Failed - You do not have permissions to access the service
5 : Invalid format - This service doesn't exist in that format
6 : Invalid parameters - Your request is missing a required parameter
7 : Invalid resource specified
8 : Operation failed - Most likely the backend service failed. Please try again.
9 : Invalid session key - Please re-authenticate
10 : Invalid API key - You must be granted a valid key by last.fm
11 : Service Offline - This service is temporarily offline. Try again later.
12 : Subscribers Only - This station is only available to paid last.fm subscribers
13 : Invalid method signature supplied
14 : Unauthorized Token - This token has not been authorized
15 : This item is not available for streaming.
16 : The service is temporarily unavailable, please try again.
17 : Login: User requires to be logged in
18 : Trial Expired - This user has no free radio plays left. Subscription required.
19 : This error does not exist
20 : Not Enough Content - There is not enough content to play this station
21 : Not Enough Members - This group does not have enough members for radio
22 : Not Enough Fans - This artist does not have enough fans for for radio
23 : Not Enough Neighbours - There are not enough neighbours for radio
24 : No Peak Radio - This user is not allowed to listen to radio during peak usage
25 : Radio Not Found - Radio station not found
26 : API Key Suspended - This application is not allowed to make requests to the web services
27 : Deprecated - This type of request is no longer supported
29 : Rate Limit Exceded - Your IP has made too many requests in a short period, exceeding our API guidelines
"""
def __init__(self, message, code=-1):
self.code = code
self.message = message
#!/usr/bin/env python3
from lastfm import Lastfm, LastfmError
import os
import sys
def main(user_name):
template = """
Last played
Name : {NAME}
Artist : {ARTIST}
Album : {ALBUM}
Now playing? {NOW_PLAYING}"""
l = Lastfm(token=os.getenv('LASTFM_TOKEN'))
try:
recent = l.recent_tracks(user_name)
except LastfmError as e:
print(e.message)
raise
last_track = recent['recenttracks']['track'][0]
#print(recent['recenttracks']['@attr']['total'])
print(template.format(
NAME=last_track['name'],
ARTIST=last_track['artist']['#text'],
ALBUM=last_track['album']['#text'],
NOW_PLAYING= 'YEEEEEEES!!!!' if '@attr' in last_track else "NOP, played at {DATE}".format(DATE=last_track['date']['#text'])
))
if __name__ == '__main__':
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment