Skip to content

Commit

Permalink
feat: add helper functions to handle track, playlist and album
Browse files Browse the repository at this point in the history
  • Loading branch information
thenishantsapkota committed Mar 27, 2022
1 parent cdd54d0 commit 00b13e3
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions spotbee/spotify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials


class SpotifyHandler:
def __init__(self, client_id: str, client_secret: str) -> None:
self.credentials = SpotifyClientCredentials(
client_id,
client_secret,
)
self.spotify = spotipy.Spotify(client_credentials_manager=self.credentials)

async def get_tracks_from_playlist(self, playlist_url: str) -> list:
results = self.spotify.playlist_tracks(playlist_url, additional_types=["track"])

tracklist = []
for item in results["items"]:
tracklist.append(
item["track"]["name"] + " - " + item["track"]["artists"][0]["name"]
)

return tracklist

async def get_tracks_from_album(self, playlist_url: str) -> list:
results = self.spotify.album_tracks(playlist_url)
tracklist = []
for item in results["items"]:
tracklist.append(item["name"] + " - " + item["artists"][0]["name"])

return list(set(tracklist))

async def get_track_from_url(self, track_url: str) -> list:
result = self.spotify.track(track_url)
return ["{} - {}".format(result["name"], result["artists"][0]["name"])]

async def handle_spotify_url(self, url: str) -> list | None:
if url.__contains__("playlist"):
return await self.get_tracks_from_playlist(url)
elif url.__contains__("album"):
return await self.get_tracks_from_album(url)
elif url.__contains__("track"):
return await self.get_track_from_url(url)
else:
return None

0 comments on commit 00b13e3

Please sign in to comment.