Skip to content

Instantly share code, notes, and snippets.

@rajat404
Last active September 8, 2022 16:05
Show Gist options
  • Save rajat404/9f303d5b4d7b220736d5c569c261279f to your computer and use it in GitHub Desktop.
Save rajat404/9f303d5b4d7b220736d5c569c261279f to your computer and use it in GitHub Desktop.
Script to download songs from Spotify
#!/usr/bin/env python
# Based on: https://github.com/SathyaBhat/spotify-dl
# Please install spotipy, youtube_dl before running this
import os
import json
import spotipy
import spotipy.util as util
youtube_options = "--extract-audio --audio-format mp3 --no-playlist --no-overwrites --no-part --title --audio-quality 0"
def authenticate():
"""
Authenticates you to Spotify
"""
scope = 'user-library-read'
username = ''
return util.prompt_for_user_token(username, scope)
def fetch_tracks(sp, playlist, user_id):
"""
Fetches tracks from Spotify user's saved
tracks or from playlist(if playlist parameter is passed
and saves song name and artist name to songs list
"""
offset = 0
songs_dict = {}
if user_id is None:
current_user_id = sp.current_user()['id']
else:
current_user_id = user_id
while True:
if playlist is None:
results = sp.current_user_saved_tracks(limit=50, offset=offset)
else:
results = sp.user_playlist_tracks(current_user_id, playlist, None,
limit=50, offset=offset)
for item in results['items']:
track = item['track']
track_name = str(track['name'])
track_artist = str(track['artists'][0]['name'])
songs_dict.update({track_name: track_artist})
offset += 1
if results.get('next') is None:
break
return songs_dict
def download_songs(songs=None):
"""
Download songs from youtube
"""
# import ipdb; ipdb.set_trace()
if songs is None:
try:
with open('data.json', 'r') as f:
songs = json.load(f)
except FileNotFoundError:
print('No songs found!')
return
for song in songs:
artist = json.dumps(songs[song])
song = json.dumps(song)
final_string = "youtube-dl {} ytsearch:{} - {}".format(youtube_options, song, artist)
# final_string = "youtube-dl {} ytsearch:gvsearch1 {} - {}".format(youtube_options, song, artist)
os.system(final_string)
def get_songs(username):
"""
Authenticates the user, get songs
"""
all_songs = {}
token = authenticate()
sp = spotipy.Spotify(auth=token)
songs = fetch_tracks(sp, None, username)
# Read existing data, if any
try:
with open('data.json', 'r') as f:
all_songs = json.load(f)
except FileNotFoundError:
pass
# Update `all_songs` with the new songs
all_songs.update(songs)
# Write the complete JSON to file
with open('data.json', 'w') as f:
# overwrite if exists
json.dump(all_songs, f, ensure_ascii=False)
return all_songs
if __name__ == '__main__':
choice = input('Do you want to:\n1. Compile Song List\n2. Download songs\nEnter your choice [1/2]\t')
if choice == '1':
username = input('Please enter your Spotify Username: ')
if username in [None, '']:
print('Username is mandatory!')
exit()
songs = get_songs(username)
elif choice == '2':
download_songs()
else:
print('Please enter meaningful input')
exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment