all repos — paprika @ 534766d447a1d7f759bce2dd4f6c9400117140a5

go rewrite of taigabot

plugins/listenbrainz/nowplaying.go (view raw)

 1package listenbrainz
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"net/http"
 7	"time"
 8
 9	"github.com/dustin/go-humanize"
10)
11
12type ListenInfo struct {
13	Payload struct {
14		Count   int `json:"count"`
15		Listens []struct {
16			InsertedAt    string `json:"inserted_at"`
17			ListenedAt    int    `json:"listened_at"`
18			TrackMetadata struct {
19				ArtistName  string `json:"artist_name"`
20				ReleaseName string `json:"release_name"`
21				TrackName   string `json:"track_name"`
22			} `json:"track_metadata"`
23			UserName string `json:"user_name"`
24		} `json:"listens"`
25	} `json:"payload"`
26}
27
28func getListen(url string) (*ListenInfo, error) {
29	li := ListenInfo{}
30	r, err := http.Get(url)
31	if err != nil {
32		return nil, err
33	} else if r.StatusCode != 200 {
34		return nil, fmt.Errorf("non-200 response from Listenbrainz")
35	}
36
37	json.NewDecoder(r.Body).Decode(&li)
38	return &li, err
39}
40
41func NowPlaying(user string) (string, error) {
42	url := fmt.Sprintf(
43		"https://api.listenbrainz.org/1/user/%s/playing-now",
44		user,
45	)
46	li, err := getListen(url)
47	if err != nil {
48		return "", err
49	}
50
51	if len(li.Payload.Listens) != 0 {
52		// Now playing a track
53		tm := li.Payload.Listens[0].TrackMetadata
54		return fmt.Sprintf(
55			"%s is currently listening to \"%s\" by \x02%s\x02, from the album \x02%s\x02",
56			user,
57			tm.TrackName,
58			tm.ArtistName,
59			tm.ReleaseName,
60		), nil
61	} else {
62		// Last listen
63		url = fmt.Sprintf(
64			"https://api.listenbrainz.org/1/user/%s/listens?count=1",
65			user,
66		)
67		li, err := getListen(url)
68		if err != nil {
69			return "", err
70		}
71
72		tm := li.Payload.Listens[0].TrackMetadata
73		listenedAt, _ := time.Parse(time.RFC1123, li.Payload.Listens[0].InsertedAt)
74		return fmt.Sprintf(
75			"%s listened to \"%s\" by \x02%s\x02, from the album \x02%s\x02, %s",
76			user,
77			tm.TrackName,
78			tm.ArtistName,
79			tm.ReleaseName,
80			humanize.Time(listenedAt),
81		), nil
82	}
83}