Skip to content

Commit

Permalink
Fix commands breaking when there are users without scrobbles
Browse files Browse the repository at this point in the history
  • Loading branch information
joinemm committed Nov 28, 2023
1 parent b531cef commit 204fd99
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
30 changes: 29 additions & 1 deletion cogs/lastfm.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ async def convert(self, ctx: MisoContext, argument: str):
username = ctxdata[2]

data = await ctx.cog.api.user_get_now_playing(username)
if data is None:
raise exceptions.CommandWarning("You have not listened to anything!")

return self.extract(data)
else:
return self.parse(stripped_argument)
Expand Down Expand Up @@ -451,6 +454,9 @@ async def milestone(self, ctx: MisoContext, n: int):
async def nowplaying(self, ctx: MisoContext):
"""See your currently playing song"""
track = await self.api.user_get_now_playing(ctx.lfm.username)
if track is None:
raise exceptions.CommandWarning("You have not listened to anything!")

artist_name = track["artist"]["#text"]
album_name = track["album"]["#text"]
track_name = track["name"]
Expand Down Expand Up @@ -630,6 +636,8 @@ async def recent(self, ctx: MisoContext):
async def youtube(self, ctx: MisoContext):
"""Find your currently playing track on youtube"""
track = await self.api.user_get_now_playing(ctx.lfm.username)
if track is None:
raise exceptions.CommandWarning("You have not listened to anything!")

artist_name = track["artist"]["#text"]
track_name = track["name"]
Expand Down Expand Up @@ -712,7 +720,7 @@ async def artist_overview(self, ctx: MisoContext, timeframe: Period, artist: str
# there are "ghost" chartlists that mess up web scraping
albumsdiv = chartlists[1]
tracksdiv = chartlists[3]
except ValueError:
except IndexError:
return raise_no_artist_plays(artist, timeframe)

albums = self.api.get_library_playcounts(albumsdiv)
Expand Down Expand Up @@ -951,6 +959,9 @@ async def album(self, ctx: MisoContext, *, album: Annotated[tuple, AlbumArgument
async def album_cover(self, ctx: MisoContext):
"""See the full album cover of your current song"""
track = await self.api.user_get_now_playing(ctx.lfm.username)
if track is None:
raise exceptions.CommandWarning("You have not listened to anything!")

image = LastFmImage.from_url(track["image"][-1]["#text"])
artist_name = track["artist"]["#text"]
album_name = track["album"]["#text"]
Expand Down Expand Up @@ -1409,6 +1420,9 @@ async def server_nowplaying(self, ctx: MisoContext):

rows = []
for member_data, member in data:
if member_data is None:
continue

if not member_data["nowplaying"]:
continue

Expand Down Expand Up @@ -1505,6 +1519,8 @@ async def server_topartists(
artist_map = {}
for member_data, member in data:
artists = member_data["artist"]
if len(artists) == 0:
continue
lowest_playcount = int(artists[-1]["playcount"])
highest_playcount = int(artists[0]["playcount"])
for artist in artists:
Expand Down Expand Up @@ -1562,6 +1578,8 @@ async def server_toptracks(
track_map = {}
for member_data, member in data:
tracks = member_data["track"]
if len(tracks) == 0:
continue
lowest_playcount = int(tracks[-1]["playcount"])
highest_playcount = int(tracks[0]["playcount"])
for track in tracks:
Expand Down Expand Up @@ -1625,6 +1643,8 @@ async def server_topalbums(
album_map = {}
for member_data, member in data:
albums = member_data["album"]
if len(albums) == 0:
continue
lowest_playcount = int(albums[-1]["playcount"])
highest_playcount = int(albums[0]["playcount"])
for album in albums:
Expand Down Expand Up @@ -1727,6 +1747,8 @@ async def server_chart(
artist_map = {}
for member_data, member in data:
artists = member_data["artist"]
if len(artists) == 0:
continue
lowest_playcount = int(artists[-1]["playcount"])
highest_playcount = int(artists[0]["playcount"])
for artist in artists:
Expand Down Expand Up @@ -1776,6 +1798,9 @@ async def server_chart(
track_list = []
for member_data, member in data:
tracks = member_data["track"]
if len(tracks) == 0:
continue

for track in tracks:
artist_name = track["artist"]["#text"]
track_name = track["name"]
Expand Down Expand Up @@ -1817,6 +1842,9 @@ async def server_chart(
album_map = {}
for member_data, member in data:
albums = member_data["album"]
if len(albums) == 0:
continue

lowest_playcount = int(albums[-1]["playcount"])
highest_playcount = int(albums[0]["playcount"])
for album in albums:
Expand Down
10 changes: 5 additions & 5 deletions modules/lastfm.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,15 +369,13 @@ async def track_get_info(
# HELPERS #
###########

async def user_get_now_playing(self, username: str) -> dict:
async def user_get_now_playing(self, username: str) -> dict | None:
"""Get the user's currently playing or most recent track with added nowplaying key."""
data = await self.user_get_recent_tracks(username, limit=1)
try:
track: dict = data["track"][0]
except KeyError:
raise exceptions.LastFMError(
error_code=0, message="Last.fm returned no data"
)
except (KeyError, IndexError):
return None

now_playing = bool(
track.get("@attr") and track["@attr"].get("nowplaying") == "true"
Expand All @@ -399,6 +397,8 @@ async def scrape_page(self, page_url: str, params: dict | None = None):
"User-Agent": self.USER_AGENT,
},
) as response:
if self.bot.debug:
logger.info(f"Scraping page {response.url}")
response.raise_for_status()
content = await response.text()
soup = BeautifulSoup(content, "lxml")
Expand Down

0 comments on commit 204fd99

Please sign in to comment.