Last active
August 29, 2015 14:21
-
-
Save mnd999/b71a1fb546f3cebe91eb to your computer and use it in GitHub Desktop.
Spotify game, West London Hack Night 19/5/15
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
package main | |
import ( | |
"net/http" | |
"net/url" | |
"io/ioutil" | |
"encoding/xml" | |
// "fmt" | |
"math/rand" | |
"strings" | |
"os" | |
) | |
func main() { | |
term := "badger" | |
if len(os.Args) > 1 { | |
term = os.Args[1] | |
} | |
println(term) | |
titles := make(map[string]bool) | |
for i := 0; i < 10; i++ { | |
// println(term) | |
result := searchSpotify(term) | |
title := "" | |
artist := "" | |
count := 0 | |
for (!strings.Contains(strings.ToUpper(title), strings.ToUpper(term)) || titles[strings.ToUpper(title)] == true) && count < 100 { | |
num := rand.Intn(len(result.Tracks)) | |
title = result.Tracks[num].Title | |
artist = result.Tracks[num].Artist | |
//println(title) | |
count++ | |
} | |
titles[strings.ToUpper(title)] = true | |
println(title + " - " + artist) | |
term = getWordFromTitle(title, term) | |
} | |
} | |
func getWordFromTitle(title string, lastTerm string) string { | |
words := strings.Split(title," ") | |
// fmt.Printf("%q",words) | |
// println(len(words)) | |
word := "" | |
for len(word) < 3 || isWordBoring(word) || (strings.ToUpper(lastTerm) == strings.ToUpper(word) && len(words) >1) { | |
word = words[rand.Intn(len(words))] | |
} | |
// println("word: " +word) | |
return word | |
} | |
func isWordBoring(word string) bool { | |
boringWords := []string {"and", "-", "the", "a", "i", "you", "he", "she", "it", "we", "like", "" } | |
for _,element := range boringWords { | |
if (strings.ToLower(word) == element) { | |
return true | |
} | |
} | |
return false | |
} | |
func searchSpotify(query string) Spotify { | |
resp, err := http.Get("http://ws.spotify.com/search/1/track?q=" + url.QueryEscape(query)) | |
if err != nil { | |
println("Error!") | |
return Spotify{} | |
} | |
defer resp.Body.Close() | |
body, _ := ioutil.ReadAll(resp.Body) | |
//println(string(body)) | |
spotify := Spotify{} | |
xml.Unmarshal(body, &spotify) | |
//println(fmt.Sprintf("%+v",spotify)) | |
return spotify | |
} | |
type Spotify struct { | |
Tracks []Track `xml:"track"` | |
} | |
type Track struct { | |
Title string `xml:"name"` | |
Artist string `xml:"artist>name"` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment