all repos — paprika @ e568d23f7e187249da9d1f243b788c24c6afe0fa

go rewrite of taigabot

plugins/lastfm/nowplaying.go (view raw)

 1package lastfm
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"net/http"
 7	"strconv"
 8	"time"
 9
10	"git.icyphox.sh/paprika/config"
11	"github.com/dustin/go-humanize"
12)
13
14type ListenInfo struct {
15	RecentTracks struct {
16		Track []struct {
17			Artist struct {
18				Text string `json:"#text"`
19			} `json:"artist"`
20			Album struct {
21				Text string `json:"#text"`
22			} `json:"album"`
23			Name string `json:"name"`
24			Date struct {
25				UnixTimestamp string `json:"uts"`
26			} `json:"date"`
27			Attr struct {
28				NowPlaying string `json:"nowplaying"`
29			} `json:"@attr"`
30		} `json:"track"`
31	} `json:"recenttracks"`
32}
33
34func getRecentTracks(url string) (*ListenInfo, error) {
35	li := ListenInfo{}
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		strT := track.Date.UnixTimestamp
73		ts, _ := strconv.Atoi(strT)
74		t := time.Unix(int64(ts), 0)
75		return fmt.Sprintf(
76			"%s listened to \"%s\" by \x02%s\x02, from the album \x02%s\x02, %s",
77			user,
78			track.Name,
79			track.Artist.Text,
80			track.Album.Text,
81			humanize.Time(t),
82		), nil
83	}
84}