simpbot/vtuber.go

97 lines
2.2 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-05-14 18:45:55 -04:00
"github.com/charmbracelet/log"
2021-08-07 13:02:50 -04:00
"github.com/spf13/viper"
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 {
2021-05-21 13:39:54 -04:00
Name string `mapstructure:"name"`
ChannelID string `mapstructure:"channelid"`
LiveMsg string `mapstructure:"msg"`
2021-08-23 19:49:20 -04:00
Announce bool `mapstructure:"Announce"`
2021-05-21 13:39:54 -04:00
}
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 18:45:55 -04:00
func loadVtubers() []*Vtuber {
var vtubersRaw []vtuberConfig
2021-08-07 13:02:50 -04:00
var vtubers []*Vtuber
err := viper.UnmarshalKey("vtubers", &vtubersRaw)
if err != nil {
panic(err)
}
for _, vt := range vtubersRaw {
2023-05-14 18:45:55 -04:00
log.Infof("adding vtuber %v", vt)
vtubers = append(vtubers, newVtuber(vt.Name, vt.ChannelID, vt.LiveMsg, vt.Announce))
2021-08-07 13:02:50 -04:00
}
return vtubers
}
2023-05-14 18:45:55 -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 18:45:55 -04:00
//Update takes an apiKey and updates the vtuber struct
func (v *Vtuber) Update(apiKey string) error {
2021-08-04 18:06:06 -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 {
return err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
jsonBody, _ := ioutil.ReadAll(res.Body)
var sl StreamList
err = json.Unmarshal(jsonBody, &sl)
if err != nil {
return err
}
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
}