Skip to content

Instantly share code, notes, and snippets.

@kenmickles
Created April 29, 2016 02:56
Show Gist options
  • Save kenmickles/b257a2ffb6d268c54795d2f21ba8752c to your computer and use it in GitHub Desktop.
Save kenmickles/b257a2ffb6d268c54795d2f21ba8752c to your computer and use it in GitHub Desktop.
Quick and dirty script to import a CSV of songs into a Spotify playlist
require 'httparty'
require 'awesome_print'
require 'enumerator'
USER_ID = "kenmickles"
ACCESS_TOKEN = ""
PLAYLIST_ID = ""
def search_for_track(query)
response = HTTParty.get("https://api.spotify.com/v1/search",
query: {
q: query,
type: "track"
},
headers: {
"Authorization" => "Bearer #{ACCESS_TOKEN}"
}
)
if response['tracks'].nil?
ap response
raise "Something went wrong!"
end
track = response['tracks']['items'][0]
sleep 2.0
track
end
tracks = []
missing = []
CSV.foreach("playlist.csv", headers: true) do |row|
query = "#{row['Name']} #{row['Artist']} #{row['Album']}"
puts "Searching for `#{query}`..."
track = search_for_track(query)
if track.nil?
query = "#{row['Name']} #{row['Artist']}"
track = search_for_track(query)
end
if track
puts " found `#{track['artists'][0]['name']} - #{track['name']}`\n\n"
tracks << track
else
puts " couldn't find anything :(\n\n"
missing << row
end
end
File.open("tracks.json", 'w') { |f| f.write JSON.pretty_generate(tracks) }
File.open("missing.json", 'w') { |f| f.write JSON.pretty_generate(missing) }
# tracks = JSON.parse File.read("tracks.json")
tracks.each_slice(100) do |slice|
uris = slice.collect { |t| t['uri'] }
puts HTTParty.post("https://api.spotify.com/v1/users/#{USER_ID}/playlists/#{PLAYLIST_ID}/tracks",
body: { uris: uris }.to_json,
headers: {
"Authorization" => "Bearer #{ACCESS_TOKEN}",
'Content-Type' => 'application/json'
}
)
end
if missing.length > 0
puts "\nCouldn't find these:"
ap missing
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment