From 382c42262954767acc3f5ee3e008e03acbfc4f26 Mon Sep 17 00:00:00 2001 From: Parker Date: Thu, 28 Nov 2024 00:04:48 -0600 Subject: Overhaul \`play\` command - Split custom sources into helper functions - Add proper logging and handling - Fix LoadError embed messsage --- code/utils/source_helpers/apple/song.py | 74 +++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 code/utils/source_helpers/apple/song.py (limited to 'code/utils/source_helpers/apple/song.py') diff --git a/code/utils/source_helpers/apple/song.py b/code/utils/source_helpers/apple/song.py new file mode 100644 index 0000000..55db003 --- /dev/null +++ b/code/utils/source_helpers/apple/song.py @@ -0,0 +1,74 @@ +import datetime +import discord +import requests +from typing import Tuple, Optional +from requests.exceptions import JSONDecodeError + +from utils.config import BOT_COLOR, LOG + + +async def load( + headers: dict, + query: str, + user: discord.User, +) -> Tuple[Optional[dict], Optional[discord.Embed]]: + """ + Get the song info from the Apple Music API + """ + song_id = query.split("/album/")[1].split("?i=")[1] + + try: + # Get the song info + response = requests.get( + f"https://api.music.apple.com/v1/catalog/us/songs/{song_id}", + headers=headers, + ) + + if response.status_code == 404: + embed = discord.Embed( + title="Song Not Found", + description=( + "The song could not be found as the provided link is" + " invalid. Please try again." + ), + color=BOT_COLOR, + ) + return None, embed + + if response.status_code == 401: + LOG.error( + "Could not authorize with Apple Music API. Likely need to" + " restart the bot." + ) + return None, None + + response.raise_for_status() + # Unpack the song info + song = response.json() + name = song["data"][0]["attributes"]["name"] + artist = song["data"][0]["attributes"]["artistName"] + except IndexError: + LOG.error("Failed unpacking Apple Music song info") + return None, None + except (JSONDecodeError, requests.HTTPError): + LOG.error("Failed making request to Apple Music API") + return None, None + + # Extract artwork URL, if available + artwork_url = ( + song["data"][0]["attributes"].get("artwork", {}).get("url", None) + ) + if artwork_url: + artwork_url = artwork_url.replace("{w}x{h}", "300x300") + + embed = discord.Embed( + title="Song Queued", + description=f"**{name}** by **{artist}**\n\nQueued by: {user.mention}", + color=BOT_COLOR, + ) + embed.set_thumbnail(url=artwork_url) + embed.set_footer( + text=datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") + " UTC" + ) + + return song, embed -- cgit v1.2.3-70-g09d2