Yves/commands/now_playing.py
2025-10-07 04:57:25 -03:00

81 lines
3.4 KiB
Python

import requests
import nerimity
import pylast
import bot
import utils as u
def setup(bot: bot.Bot):
@bot.command(name="fm", aliases=["np"])
@bot.slash_command(name="fm", description="Shows what you're currently playing")
async def fm(ctx: nerimity.Context, lookup: str = None):
if lookup: username = lookup
else:
try: username = await bot.get_lastfm(ctx.author.id)
except Exception as e:
print(e)
await ctx.send(u.error_msg("Unknown database error."))
if not username:
await ctx.send(u.error_msg("Please provide a Last.fm username (or set yours with `/setfm`)"))
else:
try:
user = bot.lastfm.get_user(username)
track = user.get_now_playing()
if track == None:
now_playing = False
played_track = user.get_recent_tracks(limit=1)
track = played_track[0].track
else:
now_playing = True
track_url = track.get_url()
track_name = track.get_name()
track_artist = track.get_artist().get_name()
track_artist_url = track.get_artist().get_url()
if now_playing == True:
await ctx.send(f"Now playing for **{username}**: [{track_name}]({track_url}) by [{track_artist}]({track_artist_url})")
else:
await ctx.send(f"Last played for **{username}**: [{track_name}]({track_url}) by [{track_artist}]({track_artist_url})")
except IndexError:
await ctx.send(u.error_msg(f"User **{username}** has no recent tracks or they're set to private."))
except pylast.WSError:
await ctx.send(u.error_msg(f"User **{username}** not found."))
except Exception as e:
print(e)
await ctx.send(u.error_msg("Unknown error."))
@bot.command(name="cover", aliases=["coverart","art"])
@bot.slash_command(name="cover", description="Returns cover art of last played album or a custom query.")
async def cover(ctx: nerimity.Context, *album: str):
username = None
user = None
if not album:
try: username = await bot.get_lastfm(ctx.author.id)
except Exception as e:
print(e)
await ctx.send(u.error_msg("Unknown database error."))
if not username: await ctx.send(u.error_msg("Please provide an `artist - album` query or set your Last.fm username with `/setfm`."))
else:
try:
user = bot.lastfm.get_user(username)
if not user.get_now_playing:
last_played = user.get_recent_tracks(limit=1)
album = last_played[0].get_album()
else:
album = user.get_now_playing().get_album()
cover_art = album.get_cover_image()
if not cover_art: await ctx.send(u.error_msg(f"**{album.get_name()}** does not seem to have cover art."))
else: await ctx.send(f"Here's the cover art for **[{album.get_name()}]({album.get_url()})**:\n{cover_art}")
except Exception as e:
print(e)
await ctx.send(u.error_msg("Unknown error."))