Edm0nd/edmond/plugins/music.py

67 lines
2.1 KiB
Python
Raw Normal View History

import random
try:
from scaruffi.api import ScaruffiApi
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
from edmond.plugin import Plugin
class MusicPlugin(Plugin):
"""Get some good music for your friends using the scaruffi library.
The first command returns a random good album. The second command allows you
to choose the decade: you can say 1960, 60, 60s or 60's, all of these will
return an album from the sixties.
"""
REQUIRED_CONFIGS = ["commands"]
DECADES = [60, 70, 80, 90, 00, 10]
def __init__(self, bot):
super().__init__(bot)
self.api = ScaruffiApi()
def on_pubmsg(self, event):
if not self.should_handle_command(event.arguments[0]):
return False
if self.command.ident == self.config["commands"][0]:
decade = random.choice(self.DECADES)
2020-11-06 15:17:29 +01:00
self.tell_album_from_decade(event.target, decade)
elif self.command.ident == self.config["commands"][1]:
decade = self.parse_decade(self.command.content)
if decade is None:
self.signal_failure(event.target)
2020-11-06 15:17:29 +01:00
else:
self.tell_album_from_decade(event.target, decade)
return True
def tell_album_from_decade(self, target, decade):
album = self.get_random_album(decade)
if not album:
self.signal_failure(target)
2020-11-06 15:17:29 +01:00
return
self.bot.say(target, album)
def get_random_album(self, decade):
"""Return an album as str from this decade from Scaruffi website."""
ratings = self.api.get_ratings(decade)
if not ratings:
return None
rating = random.choice(list(ratings.keys()))
album = random.choice(ratings[rating])
return f"{album.artist} - {album.title} ({album.year})"
def parse_decade(self, text):
"""Return decade text as an int if possible, else None. Strip "'s"."""
text = text.lower().rstrip("'s")
try:
return int(text)
except ValueError:
return None