Yves/commands/top.py
2025-10-09 03:54:33 -03:00

93 lines
3.4 KiB
Python

import nerimity
import pylast
import bot
import utils as u
def setup(bot: bot.Bot):
async def send_top(ctx: nerimity.Context, entity: str, timeframe: str, username: str, countstr: str):
try: count = int(countstr)
except ValueError:
await ctx.send(u.error_msg("Please input a valid number for `count`."))
return
except Exception as e:
print(e)
await ctx.send(u.error_msg(f"Unknown error:\n`{e}`"))
return
if count > 10 or count < 1:
await ctx.send(u.error_msg("Please enter a count number between 1 and 10."))
return
requested = True if username else False
username = await bot.find_lastfm_username(ctx, username)
if not username: return
match timeframe:
case "a" | "all" | "alltime" | "o":
timeframe = "overall"
period = timeframe
case "y" | "year" | "yearly":
timeframe = "12month"
period = "in the past year"
case "m" | "month" | "monthly":
timeframe = "1month"
period = "in the past month"
case "w" | "week" | "weekly":
timeframe = "7day"
period = "in the past week"
case "d" | "day" | "daily":
timeframe = "1day"
period = "in the past day"
case _:
timeframe = "7day"
period = "in the past week (default)"
try:
user = bot.lastfm.get_user(username)
msg_content = ""
match entity:
case "artist":
top_list = user.get_top_artists(period=timeframe, limit=count, cacheable=False)
for index, i in enumerate(top_list):
msg_content += f"\n{index+1}. [{i.item.get_name(properly_capitalized=True)}]({i.item.get_url()}) | {i.weight} plays"
case "album" | "track":
top_list = user.get_top_albums(period=timeframe, limit=count)
for index, i in top_list:
msg_content += f"\n{index+1}. [{i.item.get_title(properly_capitalized=True)}]({i.item.get_url()}) by [{i.item.get_artist().get_name(properly_capitalized=True)}]({i.item.get_artist().get_url()}) | {i.weight} plays"
msg_head = f"Top {len(top_list)} {entity}s {period} for [{username}]({user.get_url()}):\n"
msg = msg_head + msg_content
if requested is True:
msg += f"\n### Requested by [@:{ctx.author.id}]"
await ctx.send(msg)
except pylast.WSError as e:
print(e)
await ctx.send(u.error_msg(f"Last.fm error:\n`{e}`"))
return
except Exception as e:
print(e)
await ctx.send(u.error_msg(f"Unknown error:\n`{e}`"))
return
@bot.command(name="topartists", aliases=["ta","topartist"])
@bot.slash_command(name="topartists", description="Generate a list of your top artists.")
async def topartists(ctx: nerimity.Context, timeframe: str = "7day", username: str = None, countstr: str = "10"):
await send_top(
ctx = ctx,
entity = "artist",
timeframe = timeframe,
username = username,
countstr = countstr
)