Last active
February 17, 2020 03:44
-
-
Save stephanebruckert/d0cc70508e72273995d297f6af6fad13 to your computer and use it in GitHub Desktop.
Reverse a Spotify playlist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import spotipy | |
import spotipy.util as util | |
''' | |
python3 script to reverse a Spotify playlist, i.e.: | |
A B C D E (before) | |
E D C B A (after) | |
Create a new Spotify app on https://developer.spotify.com/. | |
Set `http://localhost/` as the callback URL. | |
Then replace the ENV variables accordingly and run the following 2 commands: | |
pip3 install spotipy | |
CLIENT_ID='<replace>' \ | |
CLIENT_SECRET='<replace>' \ | |
USER_ID='<replace>' \ | |
PLAYLIST_ID='<replace>' \ | |
python3 reverse-playlist.py | |
''' | |
CLIENT_ID = os.environ['CLIENT_ID'] | |
CLIENT_SECRET = os.environ['CLIENT_SECRET'] | |
USER_ID = os.environ['USER_ID'] | |
REDIRECT_URI = 'http://localhost/' | |
PLAYLIST_ID = os.environ['PLAYLIST_ID'] | |
SCOPE = 'playlist-read-private playlist-modify-private playlist-modify-public' | |
def get_spotify_instance(): | |
token = util.prompt_for_user_token( | |
username=USER_ID, | |
scope=SCOPE, | |
client_id=CLIENT_ID, | |
client_secret=CLIENT_SECRET, | |
redirect_uri=REDIRECT_URI) | |
return spotipy.Spotify(auth=token) | |
def reverse(): | |
sp = get_spotify_instance() | |
playlist = sp.user_playlist(USER_ID, PLAYLIST_ID) | |
total = playlist['tracks']['total'] | |
snapshot_id = playlist['snapshot_id'] | |
i = 0 | |
while i < total: | |
try: | |
res = sp.user_playlist_reorder_tracks(USER_ID, PLAYLIST_ID, 0, total - i, snapshot_id=snapshot_id) | |
print(playlist['name'], res, str(i + 1) + "/" + str(total)) | |
snapshot_id = res['snapshot_id'] | |
i += 1 | |
except Exception as e: | |
print("Spotify API rate limit exceeded or token expired, please wait...:", e) | |
sp = get_spotify_instance() | |
if __name__ == "__main__": | |
reverse() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment