How to create playlist in user's Spotify profile using Spotipy?

131 Views Asked by At

Issue: Unable to create Spotify playlist for some other user whose account is not in developer mode.

The following code takes two inputs: the user's username and a list of songs that need to be added to a playlist. I have set CLIENT_ID and CLIENT_SECRET as per my Spotify's developer account. Now the issue is that whenever a playlist is created it gets added to my Spotify instead of the user's Spotify. Hence, I want help in solving this issue.

class spotifyAuthoriser:

    def __init__(self, user) -> None:
        self.user_id = user
        self.sp = spotipy.Spotify(
            auth_manager=SpotifyOAuth(
                scope="playlist-modify-private playlist-modify-public",
                redirect_uri="http://example.com",
                client_id=CLIENT_ID,
                client_secret=CLIENT_SECRET,
                show_dialog=True,
                cache_path=r"project source codes\source code\token.txt",
                username=self.user_id,
            )
        )
        self.user_id = self.sp.current_user()["id"]
        print(self.user_id)

    def add_playlist_to_profile(self, song_list, mood):
        # Add songs to the playlist
        song_uris = []
        for song in song_list:
            result = self.sp.search(q=f"track:{song}", type="track")
            # print(result)
            try:
                uri = result["tracks"]["items"][0]["uri"]
                song_uris.append(uri)
            except IndexError:
                pass
                # print(f"{song} doesn't exist in Spotify. Skipped.")

        current_date = datetime.now()
        formatted_date = current_date.strftime("%d/%m/%y")

        # Creating a new private playlist in Spotify
        playlist = self.sp.user_playlist_create(
            user=self.user_id, name=f"Feeling {mood} {formatted_date}", public=False)
        pp.pprint(playlist)
        print(playlist['external_urls']['spotify'])

        # Adding songs found into the new playlist
        self.sp.user_playlist_add_tracks(
            user=self.user_id, playlist_id=playlist["id"], tracks=song_uris)

One possible solution can be that only the list of songs must be provided and while running this code the user is redirected to Spotify's login page. After logging in, the playlist gets created in the user's library. I would be really grateful if someone would help me out with this. I would really appreciate any help you can provide.

0

There are 0 best solutions below