Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recommendation example #223

Merged
merged 3 commits into from
Sep 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions examples/recommendation/recommendation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package main

import (
"context"
"fmt"
"log"
"os"

spotifyauth "github.com/zmb3/spotify/v2/auth"

"golang.org/x/oauth2/clientcredentials"

"github.com/zmb3/spotify/v2"
)

func main() {
ctx := context.Background()
config := &clientcredentials.Config{
ClientID: os.Getenv("SPOTIFY_ID"),
ClientSecret: os.Getenv("SPOTIFY_SECRET"),
TokenURL: spotifyauth.TokenURL,
}
token, err := config.Token(ctx)
if err != nil {
log.Fatalf("couldn't get token: %v", err)
}

httpClient := spotifyauth.New().Client(ctx, token)
client := spotify.New(httpClient)

// store artist and genre info (upto 5 seed values allowed)
favorite_artists := []string{"Invent Animate", "Spiritbox", "Sleep Token"}
genres := []string{"metalcore"}
var artist_ids []spotify.ID

// find the ID for each artist and append it to list of artist ID's
for _, artist := range favorite_artists {
artists, err := client.Search(ctx, artist, spotify.SearchTypeArtist)

if err != nil {
log.Fatal(err)
}
artist_ids = append(artist_ids, artists.Artists.Artists[0].ID)
}

// store the values in seed
seeds := spotify.Seeds{
Artists: artist_ids,
Genres: genres,
}

// declare track attributes for a more refined search
track_attributes := spotify.NewTrackAttributes().
MaxValence(0.4).
TargetEnergy(0.6).
TargetDanceability(0.6)

// get recommendations based on seed values
res, err := client.GetRecommendations(ctx, seeds, track_attributes, spotify.Country("US"), spotify.Limit(10))
if err != nil {
log.Fatal(err)
}

// display the recommended tracks along with artists
fmt.Println("\t---- Recommended Tracks ----")
for _, track := range res.Tracks {
fmt.Println(track.Name + " by " + track.Artists[0].Name)
}
}