Skip to content

Instantly share code, notes, and snippets.

@TheMuellenator
Forked from angelabauer/main.py
Last active May 6, 2024 15:46
Show Gist options
  • Save TheMuellenator/c84616c21f0f9ce68c12c357d3e1c794 to your computer and use it in GitHub Desktop.
Save TheMuellenator/c84616c21f0f9ce68c12c357d3e1c794 to your computer and use it in GitHub Desktop.
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
scope="playlist-modify-private",
redirect_uri="http://example.com",
client_id=YOUR UNIQUE CLIENT ID,
client_secret= YOUR UNIQUE CLIENT SECRET,
show_dialog=True,
cache_path="token.txt"
)
)
user_id = sp.current_user()["id"]
date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")
song_uris = ["The list of", "song URIs", "you got by", "searching Spotify"]
playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False)
# print(playlist)
sp.playlist_add_items(playlist_id=playlist["id"], items=song_uris)
@bluebanana18
Copy link

bluebanana18 commented Feb 28, 2024

Hey guys, I keep getting an insufficient client scope error. What am I still missing in the code?

Also, when I run Angela's code it creates the playlist but can't add any songs. I am a bit lost there lol.

@drakewilcox
Copy link

Hey guys, I keep getting an insufficient client scope error. What am I still missing in the code?

Also, when I run Angela's code it creates the playlist but can't add any songs. I am a bit lost there lol.

@bluebanana18 I was having the exact same issue.

The solution for me was updating the scope in the Spotify Authentication section to include both private and public playlist-modify scopes. (update to line 3 of Angela's code)

Yes, this seems counter intuitive since on line 15 of the example, the created playlist is set as private and has the playlist-modify-private scope set, so you think it would work. But looks like the Spotify API wants both scopes set.

Also you may need to delete your token.txt file before running in order for the token to reset properly.

Example:

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="token.txt"
  )
)

Hope this helps

@bluebanana18
Copy link

@drakewilcox
Mind blown. It was really that simple, huh. Thanks a lot!

@grizzleswens
Copy link

Here is my code, it is working perfectly, I had to have a little bit of hand holding from chat gpt

import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth

Set your Spotify app credentials

You will need to make a spotify web app to get this data, go to spotify dev tools

SPOTIPY_CLIENT_ID = 'YOUR CLIENT ID'
SPOTIPY_CLIENT_SECRET = 'YOUR CLIENT SECRET'
SPOTIPY_REDIRECT_URI = 'YOUR REDIRECT URI'
SCOPE = 'playlist-modify-public user-read-private'

date = input("What date would you like to travel back in time to? YYYY-MM-DD")
endpoint = f"https://www.billboard.com/charts/hot-100/{date}/"

Scrape web for top 100 songs

response = requests.get(endpoint)
html_data = response.text

soup = BeautifulSoup(html_data, "html.parser")

songs = soup.select("li ul li h3")
songs_titles = [song.getText().strip() for song in songs]

track_uris = []

Authenticate with Spotify

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=SCOPE))

Find track URIs

for song in songs_titles:
try:
results = sp.search(q=f"track:{song}", type="track")
track_uri = results['tracks']['items'][0]['uri']
track_uris.append(track_uri)
except IndexError:
continue

# Authenticate with Spotify

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=SCOPE))

Get current user's profile data

user_id = sp.current_user()['id']

Create a new playlist for the current user

playlist_name = f"Billboard top songs on {date}"
playlist_description = "Created with Python"
playlist = sp.user_playlist_create(user=user_id, name=playlist_name, description=playlist_description)

Get the playlist ID

playlist_id = playlist['id']

Add tracks to the playlist

sp.playlist_add_items(playlist_id=playlist_id, items=track_uris)

print(f"Playlist created and tracks added. Playlist ID: {playlist_id}")

@rickycc
Copy link

rickycc commented Apr 18, 2024

# Use this return to check if our OAuth is successful.
# return 'OAuth Successful'
sp = spotipy.Spotify(auth=token_info['access_token'])
user_id = sp.current_user()['id']
current_playlists = sp.current_user_playlists()['items']

song_uris = []
# Song search to add in playlist
for song in song_names:
    result = sp.search(q=f"track:{song}", type="track", market="US")
    # print track: find the
    # print(result['tracks']['items'][0])
    try:
        uri = result["tracks"]["items"][0]["uri"]
        song_uris.append(uri)
    except IndexError:
        print(f"{song} doesn't exist in Spotify. Skipped.")
# print(song_uris)

# Check if the playlist already exist for given date:
billboard_100_playlist_id = None
for playlist in current_playlists:
    if playlist['name'] == f'{date} Billboard 100':
        billboard_100_playlist_id = playlist['id']

if not billboard_100_playlist_id:
    new_playlist = sp.user_playlist_create(user_id, f'{date} Billboard 100', True)
    billboard_100_playlist_id = new_playlist['id']
    # return f"Billboard top 100 playlist id for date {date} is not found."

Awesome work. However, I am having trouble carrying out the playlist check. I cannot retrieve any information running the line below immediately after the authentication steps. I can print out user_id = sp.current_user()["id"] without any problem.
Can you shed some light on what should i do?

current_playlists = sp.current_user_playlists()['items']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment