all repos — paprika @ 776fcd43ff010c8e1b0081ef9d7bcfc4d4073d2b

go rewrite of taigabot

plugins/lastfm/nowplaying.go (view raw)

 1package lastfm
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"net/http"
 7	"time"
 8
 9	"git.icyphox.sh/paprika/config"
10	"github.com/dustin/go-humanize"
11)
12
13type ListenInfo struct {
14	RecentTracks struct {
15		Track []struct {
16			Artist struct {
17				Text string `json:"#text"`
18			} `json:"artist"`
19			Album struct {
20				Text string `json:"#text"`
21			} `json:"album"`
22			Name string `json:"name"`
23			Date struct {
24				UnixTimestamp int `json:"uts"`
25			} `json:"date"`
26			Attr struct {
27				NowPlaying string `json:"nowplaying"`
28			} `json:"@attr"`
29		} `json:"track"`
30	} `json:"recenttracks"`
31}
32
33func getRecentTracks(url string) (*ListenInfo, error) {
34	li := ListenInfo{}
35	fmt.Println(url)
36	r, err := http.Get(url)
37	if err != nil {
38		return nil, err
39	} else if r.StatusCode != 200 {
40		return nil, fmt.Errorf("non-200 response from Last.fm")
41	}
42
43	json.NewDecoder(r.Body).Decode(&li)
44	defer r.Body.Close()
45
46	return &li, err
47}
48
49func NowPlaying(user string) (string, error) {
50	key := config.C.ApiKeys["lastfm-key"]
51	url := fmt.Sprintf(
52		"https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json",
53		user,
54		key,
55	)
56
57	rt, err := getRecentTracks(url)
58	if err != nil {
59		return "", err
60	}
61
62	track := rt.RecentTracks.Track[0]
63	if rt.RecentTracks.Track[0].Attr.NowPlaying == "true" {
64		return fmt.Sprintf(
65			"%s is currently listening to \"%s\" by \x02%s\x02, from the album \x02%s\x02",
66			user,
67			track.Name,
68			track.Artist.Text,
69			track.Album.Text,
70		), nil
71	} else {
72		return fmt.Sprintf(
73			"%s listened to \"%s\" by \x02%s\x02, from the album \x02%s\x02, %s",
74			user,
75			track.Name,
76			track.Artist.Text,
77			track.Album.Text,
78			humanize.Time(time.Unix(int64(track.Date.UnixTimestamp), 0)),
79		), nil
80	}
81}