simpbot/vtuber.go
Steve 4938f28ace
All checks were successful
continuous-integration/drone/push Build is passing
add api key
2023-04-24 18:01:40 -04:00

96 lines
2.1 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/spf13/viper"
"maunium.net/go/mautrix/id"
)
type VtuberConfig struct {
Name string `mapstructure:"name"`
ChannelID string `mapstructure:"channelid"`
LiveMsg string `mapstructure:"msg"`
Announce bool `mapstructure:"Announce"`
}
type Vtuber struct {
Name string
ChannelID string
CurrentStream string
CurrentStreamTitle string
LiveMsg string
AnnounceLive bool
TotalStreams int
Subs map[id.UserID]bool
}
func NewVtuber(name, channelID, liveMsg string, announce bool) *Vtuber {
return &Vtuber{
Name: name,
ChannelID: channelID,
CurrentStream: "",
CurrentStreamTitle: "",
LiveMsg: liveMsg,
AnnounceLive: announce,
TotalStreams: 0,
Subs: make(map[id.UserID]bool),
}
}
func LoadVtubers() []*Vtuber {
var vtubersRaw []VtuberConfig
var vtubers []*Vtuber
err := viper.UnmarshalKey("vtubers", &vtubersRaw)
if err != nil {
panic(err)
}
for _, vt := range vtubersRaw {
log.Printf("adding vtuber %v", vt)
vtubers = append(vtubers, NewVtuber(vt.Name, vt.ChannelID, vt.LiveMsg, vt.Announce))
}
return vtubers
}
func (v *Vtuber) IsLive() bool {
return v.CurrentStream != ""
}
func (v *Vtuber) Update(api_key string) error {
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)
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("X-APIKEY", api_key)
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 {
log.Printf("error parsing json for vtuber %v:%v", v.Name, err)
return err
}
found := false
for _, s := range sl.Streams {
if s.Status == "live" {
v.CurrentStream = s.ID
v.CurrentStreamTitle = s.Title
found = true
}
}
if !found {
v.CurrentStream = ""
v.CurrentStreamTitle = ""
}
return nil
}