func getVideoInfo(id string) (*ytVideoResponse, bool) { key, avail := config.Get("GOOGLE_API") if !avail { return nil, false } videoURL := fmt.Sprintf("%svideos/?id=%s&key=%s&part=%s&fields=%s", baseURL, id, key, videoParts, videoFields) vData, err := util.Fetch(videoURL) if err != nil { return nil, false } var videoData tyVideo err = json.Unmarshal(vData, &videoData) if err != nil || len(videoData.Videos) < 1 { return nil, false } chanID := videoData.Videos[0].Snippet.ChannelID chanURL := fmt.Sprintf("%schannels/?id=%s&key=%s&part=%s&fields=%s", baseURL, chanID, key, chanParts, chanFields) cData, err := util.Fetch(chanURL) if err != nil { return nil, false } var chanData ytChannel err = json.Unmarshal(cData, &chanData) if err != nil || len(chanData.Channels) < 1 { return nil, false } title := videoData.Videos[0].Snippet.Title views, _ := strconv.ParseInt(videoData.Videos[0].Statistics.Views, 10, 64) uploadTime, _ := time.Parse(timeForm, videoData.Videos[0].Snippet.Published) dur, _ := duration.ParseString(videoData.Videos[0].ContentDetails.Duration) durTime := dur.ToDuration() channel := chanData.Channels[0].Snippet.Title response := &ytVideoResponse{ Title: title, Views: views, Duration: durTime, Channel: channel, UploadTime: uploadTime, } return response, true }
func subredditLookup(msg commands.Message, ret commands.MessageFunc) string { if len(msg.Params) < 2 { return "Give me a subreddit!" } sub := msg.Params[1] url := fmt.Sprintf(subredditURL, sub) data, err := util.Fetch(url) if err != nil { return "Error getting reddit data!" } var rp redditPage json.Unmarshal(data, &rp) postcount := len(rp.Data.Children) if postcount == 0 { return "This subreddit looks empty!" } rand.Seed(time.Now().UTC().UnixNano()) randIndex := rand.Intn(postcount) redditdata := rp.Data.Children[randIndex].ChildData redditdata.URL = fixImgurLink(redditdata.URL) if redditdata.Nsfw { return fmt.Sprintf("(NSFW) %s: %s", redditdata.Title, redditdata.URL) } return fmt.Sprintf("%s: %s", redditdata.Title, redditdata.URL) }
func redditLookup(msg commands.Message, ret commands.MessageFunc) string { if len(msg.Params) < 2 { return "Usage: .ru [username]" } user := msg.Params[1] url := fmt.Sprintf("http://www.reddit.com/user/%s/about.json", user) data, err := util.Fetch(url) if err != nil { return "Unable to fetch the users' information from reddit" } var response redditUser if err := json.Unmarshal(data, &response); err != nil { return "Reddit gave me a bad response" } if len(response.Data.Name) < 1 { return "Couldn't find that person!" } //name := response.Data.Name created := response.Data.CreatedUtc createdInt := int64(created) ParsedTime := time.Unix(createdInt, 0) createdString := ParsedTime.Format(redditLayout) return fmt.Sprintf("%s with %v comment and %v link karma, created on %s", response.Data.Name, humanize.Comma(int64(response.Data.CommentKarma)), humanize.Comma(int64(response.Data.LinkKarma)), createdString) }
func wikiLookup(msg commands.Message, ret commands.MessageFunc) string { if len(msg.Params) < 2 { return "" } query := url.QueryEscape(strings.Join(msg.Params[1:], " ")) url := fmt.Sprintf("%s&action=query&prop=extracts|info&exintro=&explaintext=&inprop=url&indexpageids=&redirects=&titles=%s", wikiurl, query) data, err := util.Fetch(url) if err != nil { return "Error contacting Wikipedia API!" } var resp wikiResponse if err := json.Unmarshal(data, &resp); err != nil { return "Wikipedia gave me a bad answer!" } if len(resp.Query.PageIDs) < 1 { return "Wikipedia page not found!" } id := resp.Query.PageIDs[0] page := resp.Query.Pages[id] content := page.Extract if len(content) > 350 { content = fmt.Sprintf("%s...", content[:350]) } return fmt.Sprintf("%s %s", page.URL, content) }
func weatherLookup(msg commands.Message, ret commands.MessageFunc) string { geoAddr, err := util.GetCoordinates(msg.Params[1:]) if err != nil { return "I couldn't track down that location!" } apiKey, avail := config.Get("WUNDERGROUND_API") if avail != true { return "" } url := fmt.Sprintf("http://api.wunderground.com/api/%s/conditions/q/%v,%v.json", apiKey, geoAddr.Lat, geoAddr.Long) data, err := util.Fetch(url) if err != nil { return "Unable to lookup weather" } var conditions weatherConditions if err := json.Unmarshal(data, &conditions); err != nil { return "Weather Underground gave me a bad response" } response := conditions.Current if response.Weather == "" { return "I couldn't find that location -- try again!" } location := fmt.Sprintf("%s (%s)", response.Location.Full, response.StationID) return fmt.Sprintf("%s is: %s - %s with %s humidity | Wind: %s | %s precip. today", location, response.Weather, response.TempString, response.RelHumidity, response.WindString, response.PrecipString) }
func tumblrLookup(msg commands.Message, ret commands.MessageFunc) string { if len(msg.Params) < 2 { return "I need .tumblr [blog-url]" } blog := msg.Params[1] key, ok := config.Get("TUMBLR_API") if !ok { return "" } req := fmt.Sprintf("http://api.tumblr.com/v2/blog/%s/posts/text?api_key=%s", blog, key) data, err := util.Fetch(req) if err != nil { return "Unable to get data from tumblr" } var resp tumblrData if err := json.Unmarshal(data, &resp); err != nil { return "Tumblr gave me a bad response!" } if resp.Meta.Status != 200 { return "Tumblr returned an Error" } if len(resp.Response.Posts) < 1 { return "I didn't find any posts!" } post := resp.Response.Posts[0] return fmt.Sprintf("%s: %v @ %s", post.BlogName, post.Title, post.ShortURL) }
func walkscoreLookup(msg commands.Message, ret commands.MessageFunc) string { walkscore, avail := config.Get("WALKSCORE_API") if avail != true { return "" } geoAddr, err := util.GetCoordinates(msg.Params[1:]) if err != nil { return "Not found!" } lat := geoAddr.Lat long := geoAddr.Long addr := url.QueryEscape(geoAddr.FormattedAddress) walkscoreURL := fmt.Sprintf("http://api.walkscore.com/score?format=json&address=%v&lat=%v&lon=%v&wsapikey=%v", addr, lat, long, walkscore) wdata, err := util.Fetch(walkscoreURL) if err != nil { return "Error fetching walkscore data" } var ws walkScoreData if err := json.Unmarshal(wdata, &ws); err != nil { return "Walkscore gave me a bad response!" } if ws.Status != 1 { return "I couldn't find that in Walkscore's database" } return fmt.Sprintf("%s is a %s with a walkscore of %v", geoAddr.FormattedAddress, ws.Description, ws.Walkscore) }
func updateRates(apikey string) error { url := fmt.Sprintf("http://openexchangerates.org/api/latest.json?app_id=%s", apikey) ret, err := util.Fetch(url) if err != nil { return err } err = json.Unmarshal(ret, &data.r) if err != nil { return err } return nil }
func artistLookup(key string) string { fullURL := fmt.Sprintf("%s/%s/%s", lookupURL, "artists", key) data, err := util.Fetch(fullURL) if err != nil { return "" } var ret spotifyArtist if err := json.Unmarshal(data, &ret); err != nil { return "" } return fmt.Sprintf("[Artist]: %s with %d followers and %d popularity", ret.Name, ret.Followers.Total, ret.Popularity) }
func getLtc(_ commands.Message, ret commands.MessageFunc) string { btce, err := util.Fetch("https://btc-e.com/api/2/ltc_usd/ticker") if err != nil { return fmt.Sprintf("[%s]: BTC-E Error!", util.Bold("BTC-E")) } var response btceResponse if err := json.Unmarshal(btce, &response); err != nil { return fmt.Sprintf("[%s]: BTC-E Error!", util.Bold("BTC-E")) } return fmt.Sprintf("LTC->USD: Last: $%v, High: $%v, Low: $%v, Avg: $%v", response.Ticker.Last, response.Ticker.High, response.Ticker.Low, response.Ticker.Avg) }
func getBTCE(ch chan string) { btce, err := util.Fetch("https://btc-e.com/api/2/btc_usd/ticker") if err != nil { ch <- fmt.Sprintf("[%s]: BTC-E Error!", util.Bold("BTC-E")) } var response btceResponse if err := json.Unmarshal(btce, &response); err != nil { ch <- fmt.Sprintf("[%s]: BTC-E Error!", util.Bold("BTC-E")) return } out := fmt.Sprintf("[%s]: Last: $%v, High: $%v, Low: $%v, Avg: $%v", util.Bold("BTC-E"), response.Ticker.Last, response.Ticker.High, response.Ticker.Low, response.Ticker.Avg) ch <- out }
func getBitstamp(ch chan string) { bitstamp, err := util.Fetch("https://www.bitstamp.net/api/ticker/") if err != nil { ch <- fmt.Sprintf("[%s]: BitStamp Error!", util.Bold("BITSTAMP")) return } var btresponse bitstampResponse if err := json.Unmarshal(bitstamp, &btresponse); err != nil { ch <- fmt.Sprintf("[%s]: BitStamp Error!", util.Bold("BITSTAMP")) return } out := fmt.Sprintf("[%s]: Last: $%s, High: $%s, Low: $%s", util.Bold("BITSTAMP"), btresponse.Last, btresponse.High, btresponse.Low) ch <- out }
func ipAddressLookup(msg commands.Message, ret commands.MessageFunc) string { ip := strings.Join(msg.Params[1:], " ") url := fmt.Sprintf("http://ip-api.com/json/%s", ip) data, err := util.Fetch(url) if err != nil { return "sorry, there was a geolookup error.." } var response map[string]interface{} if err := json.Unmarshal(data, &response); err != nil { return "Sorry, ip-api.com gave me a bad response" } return fmt.Sprintf("%s: %s, %s, %s, %s, %s with %s", response["query"], response["city"], response["regionName"], response["country"], response["org"], response["as"], response["isp"]) }
func urbanLookup(msg commands.Message, ret commands.MessageFunc) string { search := strings.Join(msg.Params[1:], " ") url := fmt.Sprintf("%s%s", urbanapi, util.URLEncode(search)) data, err := util.Fetch(url) if err != nil { return "Error trying to find that!" } var ud urbanInfo if err := json.Unmarshal(data, &ud); err != nil { return "Urban Dictionary gave me a bad response!" } if len(ud.List) == 0 { return "I didn't get anything for that!" } return fmt.Sprintf("%s: %s", util.Bold(search), ud.List[0].Definition) }
func albumLookup(key string) string { fullURL := fmt.Sprintf("%s/%s/%s", lookupURL, "albums", key) data, err := util.Fetch(fullURL) if err != nil { return "" } var ret spotifyAlbum if err := json.Unmarshal(data, &ret); err != nil { return "" } var artist string if len(ret.Artists) > 1 { artist = "Multiple Artists" } else { artist = ret.Artists[0].Name } return fmt.Sprintf("[Album]: %s by %s released in %s", ret.Name, artist, ret.ReleaseDate) }
func defineWord(msg commands.Message, ret commands.MessageFunc) string { word := url.QueryEscape(strings.Join(msg.Params[1:], " ")) apiKey, avail := config.Get("WORDNIK_API") if avail != true { return "" } url := fmt.Sprintf("http://api.wordnik.com/v4/word.json/%s/definitions?includeRelated=false&api_key=%s&includeTags=false&limit=1&useCanonical=true", word, apiKey) data, err := util.Fetch(url) if err != nil { return "Unable to look up the definition of that word" } var response []defineReturn if err := json.Unmarshal(data, &response); err != nil { return "Wordnik gave me a bad answer for that word" } if len(response) > 0 { return fmt.Sprintf("%s (%s): %s", response[0].Word, response[0].PartOfSpeech, response[0].Text) } return "I couldn't find that word, sorry!" }
func trackLookup(key string) string { fullURL := fmt.Sprintf("%s/%s/%s", lookupURL, "tracks", key) data, err := util.Fetch(fullURL) if err != nil { return "" } var ret spotifyTrack if err := json.Unmarshal(data, &ret); err != nil { return "" } duration := time.Duration(ret.DurationMs) * time.Millisecond var artist string if len(ret.Artists) > 1 { artist = "Multiple Artists" } else { artist = ret.Artists[0].Name } return fmt.Sprintf("[Song]: %s - %s (%s) on the album %s", ret.Name, artist, duration.String(), ret.Album.Name) }
func stockLookup(msg commands.Message, ret commands.MessageFunc) string { stock := strings.Join(msg.Params[1:], "%20") url := fmt.Sprintf("http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=snl1abcghm6m8", stock) webdata, err := util.Fetch(url) if err != nil { return "Error fetching that stock!" } reader := strings.NewReader(string(webdata)) csvReader := csv.NewReader(reader) csvData, err := csvReader.ReadAll() if err != nil || len(csvData) < 1 { return "Error fetching that stock!" } data := csvData[0] if string(data[3]) == "N/A" && string(data[4]) == "N/A" && string(data[6]) == "N/A" { return "Invalid Stock!" } return fmt.Sprintf("%s (%s): Last: $%s | Ask: $%s | Bid: $%s | Change: %s | Day Low: %s | Day High: %s | %s Last 200 days | %s Last 50 days", data[1], data[0], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9]) }
func wolframLookup(msg commands.Message, ret commands.MessageFunc) string { appid, avail := config.Get("WOLFRAM_API") if avail != true { return "" } query := util.URLEncode(strings.Join(msg.Params[1:], " ")) getURL := fmt.Sprintf("%s?input=%s&appid=%s", geturl, query, appid) resp, err := util.Fetch(getURL) if err != nil { return "Wolfram returned an error!" } var d result if err := xml.Unmarshal(resp, &d); err != nil { fmt.Println(err) return "Wolfram did not return valid data!" } if len(d.Pods) < 2 && len(d.Pods[0].Subpods) > 0 && len(d.Pods[1].Subpods) > 0 { return "Wolfram did not return valid data!" } return fmt.Sprintf("wa: q: %s, a: %s", d.Pods[0].Subpods[0].Plaintext, removeNewLineUntil(d.Pods[1].Subpods[0].Plaintext, 200)) }