simpbot/vtuber.go

91 lines
2.1 KiB
Go
Raw Normal View History

2021-05-21 12:45:24 -04:00
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
2021-08-07 13:02:50 -04:00
2023-01-17 22:49:57 -05:00
"maunium.net/go/mautrix/id"
2021-05-21 12:45:24 -04:00
)
2023-05-14 18:45:55 -04:00
type vtuberConfig struct {
2023-05-30 20:12:38 -04:00
Name string `yaml:"name"`
ChannelID string `yaml:"channelid"`
LiveMsg string `yaml:"msg"`
Announce bool `yaml:"announce"`
2021-05-21 13:39:54 -04:00
}
2023-05-14 19:13:23 -04:00
// Vtuber represents a vtuber
2021-05-21 12:45:24 -04:00
type Vtuber struct {
Name string
ChannelID string
CurrentStream string
CurrentStreamTitle string
LiveMsg string
AnnounceLive bool
2021-10-26 14:01:58 -04:00
TotalStreams int
2023-01-17 22:49:57 -05:00
Subs map[id.UserID]bool
2021-05-21 12:45:24 -04:00
}
2023-05-14 18:45:55 -04:00
func newVtuber(name, channelID, liveMsg string, announce bool) *Vtuber {
2021-05-21 12:45:24 -04:00
return &Vtuber{
Name: name,
ChannelID: channelID,
CurrentStream: "",
CurrentStreamTitle: "",
LiveMsg: liveMsg,
AnnounceLive: announce,
2021-10-26 14:01:58 -04:00
TotalStreams: 0,
2023-01-17 22:49:57 -05:00
Subs: make(map[id.UserID]bool),
2021-05-21 12:45:24 -04:00
}
}
2023-05-14 19:13:23 -04:00
// IsLive returns whether the specified Vtuber is live
2021-05-21 12:45:24 -04:00
func (v *Vtuber) IsLive() bool {
return v.CurrentStream != ""
}
2023-05-14 19:13:23 -04:00
// Update takes an apiKey and updates the vtuber struct
2023-05-14 18:45:55 -04:00
func (v *Vtuber) Update(apiKey string) error {
2023-05-14 19:13:23 -04:00
url := fmt.Sprintf(
"https://holodex.net/api/v2/live?channel_id=%s&lang=all&sort=available_at&order=desc&limit=25&offset=0&paginated=%%3Cempty%%3E",
v.ChannelID,
)
2021-05-21 12:45:24 -04:00
req, err := http.NewRequest("GET", url, nil)
2023-05-14 18:45:55 -04:00
req.Header.Set("X-APIKEY", apiKey)
2021-05-21 12:45:24 -04:00
if err != nil {
2023-05-14 19:09:49 -04:00
return fmt.Errorf("error creating GET %w", err)
2021-05-21 12:45:24 -04:00
}
res, err := http.DefaultClient.Do(req)
if err != nil {
2023-05-14 19:09:49 -04:00
return fmt.Errorf("error sending request %w", err)
2021-05-21 12:45:24 -04:00
}
defer res.Body.Close()
2023-05-14 19:09:49 -04:00
if res.StatusCode != 200 {
return fmt.Errorf("bad status code %v", res.StatusCode)
}
jsonBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("error reading response: %w", err)
}
2021-05-21 12:45:24 -04:00
var sl StreamList
err = json.Unmarshal(jsonBody, &sl)
if err != nil {
2023-05-14 19:09:49 -04:00
return fmt.Errorf("error marshalling vtuber: %w %v", err, string(jsonBody))
2021-05-21 12:45:24 -04:00
}
found := false
for _, s := range sl.Streams {
if s.Status == "live" {
v.CurrentStream = s.ID
v.CurrentStreamTitle = s.Title
2021-05-21 12:45:24 -04:00
found = true
}
}
if !found {
v.CurrentStream = ""
v.CurrentStreamTitle = ""
2021-05-21 12:45:24 -04:00
}
return nil
}