all repos — paprika @ 776fcd43ff010c8e1b0081ef9d7bcfc4d4073d2b

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	defer r.Body.Close()
39
40	return &li, err
41}
42
43func NowPlaying(user string) (string, error) {
44	url := fmt.Sprintf(
45		"https://api.listenbrainz.org/1/user/%s/playing-now",
46		user,
47	)
48	li, err := getListen(url)
49	if err != nil {
50		return "", err
51	}
52
53	if len(li.Payload.Listens) != 0 {
54		// Now playing a track
55		tm := li.Payload.Listens[0].TrackMetadata
56		return fmt.Sprintf(
57			"%s is currently listening to \"%s\" by \x02%s\x02, from the album \x02%s\x02",
58			user,
59			tm.TrackName,
60			tm.ArtistName,
61			tm.ReleaseName,
62		), nil
63	} else {
64		// Last listen
65		url = fmt.Sprintf(
66			"https://api.listenbrainz.org/1/user/%s/listens?count=1",
67			user,
68		)
69		li, err := getListen(url)
70		if err != nil {
71			return "", err
72		}
73
74		tm := li.Payload.Listens[0].TrackMetadata
75		listenedAt, _ := time.Parse(time.RFC1123, li.Payload.Listens[0].InsertedAt)
76		return fmt.Sprintf(
77			"%s listened to \"%s\" by \x02%s\x02, from the album \x02%s\x02, %s",
78			user,
79			tm.TrackName,
80			tm.ArtistName,
81			tm.ReleaseName,
82			humanize.Time(listenedAt),
83		), nil
84	}
85}