Compare commits

..

No commits in common. "f28026436a259bb67fc5993d5f80b73d5d14c672" and "37e4dcb5c8e5acfb984ca04b987a5c00f13cc288" have entirely different histories.

3 changed files with 55 additions and 110 deletions

1
.gitignore vendored
View File

@ -76,4 +76,3 @@ run.sh
impact.ttf impact.ttf
.env .env
rathaus_discord.sh rathaus_discord.sh
emojy

View File

@ -7,7 +7,6 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"regexp"
"strings" "strings"
"text/template" "text/template"
"time" "time"
@ -27,10 +26,9 @@ const (
) )
type TwitchPlugin struct { type TwitchPlugin struct {
b bot.Bot bot bot.Bot
c *config.Config config *config.Config
twitchList map[string]*Twitcher twitchList map[string]*Twitcher
tbl bot.HandlerTable
} }
type Twitcher struct { type Twitcher struct {
@ -64,14 +62,13 @@ type stream struct {
func New(b bot.Bot) *TwitchPlugin { func New(b bot.Bot) *TwitchPlugin {
p := &TwitchPlugin{ p := &TwitchPlugin{
b: b, bot: b,
c: b.Config(), config: b.Config(),
twitchList: map[string]*Twitcher{}, twitchList: map[string]*Twitcher{},
} }
for _, ch := range p.c.GetArray("Twitch.Channels", []string{}) { for _, ch := range p.config.GetArray("Twitch.Channels", []string{}) {
for _, twitcherName := range p.c.GetArray("Twitch."+ch+".Users", []string{}) { for _, twitcherName := range p.config.GetArray("Twitch."+ch+".Users", []string{}) {
twitcherName = strings.ToLower(twitcherName)
if _, ok := p.twitchList[twitcherName]; !ok { if _, ok := p.twitchList[twitcherName]; !ok {
p.twitchList[twitcherName] = &Twitcher{ p.twitchList[twitcherName] = &Twitcher{
name: twitcherName, name: twitcherName,
@ -84,7 +81,8 @@ func New(b bot.Bot) *TwitchPlugin {
go p.twitchAuthLoop(b.DefaultConnector()) go p.twitchAuthLoop(b.DefaultConnector())
p.register() b.Register(p, bot.Message, p.message)
b.Register(p, bot.Help, p.help)
p.registerWeb() p.registerWeb()
return p return p
@ -93,11 +91,11 @@ func New(b bot.Bot) *TwitchPlugin {
func (p *TwitchPlugin) registerWeb() { func (p *TwitchPlugin) registerWeb() {
r := chi.NewRouter() r := chi.NewRouter()
r.HandleFunc("/{user}", p.serveStreaming) r.HandleFunc("/{user}", p.serveStreaming)
p.b.RegisterWeb(r, "/isstreaming") p.bot.RegisterWeb(r, "/isstreaming")
} }
func (p *TwitchPlugin) serveStreaming(w http.ResponseWriter, r *http.Request) { func (p *TwitchPlugin) serveStreaming(w http.ResponseWriter, r *http.Request) {
userName := strings.ToLower(chi.URLParam(r, "user")) userName := chi.URLParam(r, "user")
if userName == "" { if userName == "" {
fmt.Fprint(w, "User not found.") fmt.Fprint(w, "User not found.")
return return
@ -126,39 +124,14 @@ func (p *TwitchPlugin) serveStreaming(w http.ResponseWriter, r *http.Request) {
} }
} }
func (p *TwitchPlugin) register() { func (p *TwitchPlugin) message(c bot.Connector, kind bot.Kind, message msg.Message, args ...any) bool {
p.tbl = bot.HandlerTable{ body := strings.ToLower(message.Body)
{ if body == "twitch status" {
Kind: bot.Message, IsCmd: true, channel := message.Channel
Regex: regexp.MustCompile(`(?i)^twitch status$`), if users := p.config.GetArray("Twitch."+channel+".Users", []string{}); len(users) > 0 {
HelpText: "Get status of all twitchers",
Handler: p.twitchStatus,
},
{
Kind: bot.Message, IsCmd: false,
Regex: regexp.MustCompile(`(?i)^is (?P<who>.+) streaming\??$`),
HelpText: "Check if a specific twitcher is streaming",
Handler: p.twitchUserStatus,
},
{
Kind: bot.Message, IsCmd: true,
Regex: regexp.MustCompile(`(?i)^reset twitch$`),
HelpText: "Reset the twitch templates",
Handler: p.resetTwitch,
},
}
p.b.Register(p, bot.Help, p.help)
p.b.RegisterTable(p, p.tbl)
}
func (p *TwitchPlugin) twitchStatus(r bot.Request) bool {
channel := r.Msg.Channel
if users := p.c.GetArray("Twitch."+channel+".Users", []string{}); len(users) > 0 {
for _, twitcherName := range users { for _, twitcherName := range users {
twitcherName = strings.ToLower(twitcherName) if _, ok := p.twitchList[twitcherName]; ok {
// we could re-add them here instead of needing to restart the bot. err := p.checkTwitch(c, channel, p.twitchList[twitcherName], true)
if t, ok := p.twitchList[twitcherName]; ok {
err := p.checkTwitch(r.Conn, channel, t, true)
if err != nil { if err != nil {
log.Error().Err(err).Msgf("error in checking twitch") log.Error().Err(err).Msgf("error in checking twitch")
} }
@ -166,28 +139,13 @@ func (p *TwitchPlugin) twitchStatus(r bot.Request) bool {
} }
} }
return true return true
} } else if body == "reset twitch" {
p.config.Set("twitch.istpl", isStreamingTplFallback)
func (p *TwitchPlugin) twitchUserStatus(r bot.Request) bool { p.config.Set("twitch.nottpl", notStreamingTplFallback)
who := strings.ToLower(r.Values["who"]) p.config.Set("twitch.stoppedtpl", stoppedStreamingTplFallback)
if t, ok := p.twitchList[who]; ok {
err := p.checkTwitch(r.Conn, r.Msg.Channel, t, true)
if err != nil {
log.Error().Err(err).Msgf("error in checking twitch")
p.b.Send(r.Conn, bot.Message, r.Msg.Channel, "I had trouble with that.")
} }
} else {
p.b.Send(r.Conn, bot.Message, r.Msg.Channel, "I don't know who that is.")
}
return true
}
func (p *TwitchPlugin) resetTwitch(r bot.Request) bool { return false
p.c.Set("twitch.istpl", isStreamingTplFallback)
p.c.Set("twitch.nottpl", notStreamingTplFallback)
p.c.Set("twitch.stoppedtpl", stoppedStreamingTplFallback)
p.b.Send(r.Conn, bot.Message, r.Msg.Channel, "The Twitch templates have been reset.")
return true
} }
func (p *TwitchPlugin) help(c bot.Connector, kind bot.Kind, message msg.Message, args ...any) bool { func (p *TwitchPlugin) help(c bot.Connector, kind bot.Kind, message msg.Message, args ...any) bool {
@ -197,14 +155,14 @@ func (p *TwitchPlugin) help(c bot.Connector, kind bot.Kind, message msg.Message,
msg += fmt.Sprintf("twitch.stoppedtpl (default: %s)\n", stoppedStreamingTplFallback) msg += fmt.Sprintf("twitch.stoppedtpl (default: %s)\n", stoppedStreamingTplFallback)
msg += "You can reset all messages with `!reset twitch`" msg += "You can reset all messages with `!reset twitch`"
msg += "And you can ask who is streaming with `!twitch status`" msg += "And you can ask who is streaming with `!twitch status`"
p.b.Send(c, bot.Message, message.Channel, msg) p.bot.Send(c, bot.Message, message.Channel, msg)
return true return true
} }
func (p *TwitchPlugin) twitchAuthLoop(c bot.Connector) { func (p *TwitchPlugin) twitchAuthLoop(c bot.Connector) {
frequency := p.c.GetInt("Twitch.AuthFreq", 60*60) frequency := p.config.GetInt("Twitch.AuthFreq", 60*60)
cid := p.c.Get("twitch.clientid", "") cid := p.config.Get("twitch.clientid", "")
secret := p.c.Get("twitch.secret", "") secret := p.config.Get("twitch.secret", "")
if cid == "" || secret == "" { if cid == "" || secret == "" {
log.Info().Msgf("Disabling twitch autoauth.") log.Info().Msgf("Disabling twitch autoauth.")
return return
@ -227,8 +185,8 @@ func (p *TwitchPlugin) twitchAuthLoop(c bot.Connector) {
} }
func (p *TwitchPlugin) twitchChannelLoop(c bot.Connector, channel string) { func (p *TwitchPlugin) twitchChannelLoop(c bot.Connector, channel string) {
frequency := p.c.GetInt("Twitch.Freq", 60) frequency := p.config.GetInt("Twitch.Freq", 60)
if p.c.Get("twitch.clientid", "") == "" || p.c.Get("twitch.secret", "") == "" { if p.config.Get("twitch.clientid", "") == "" || p.config.Get("twitch.secret", "") == "" {
log.Info().Msgf("Disabling twitch autochecking.") log.Info().Msgf("Disabling twitch autochecking.")
return return
} }
@ -238,8 +196,7 @@ func (p *TwitchPlugin) twitchChannelLoop(c bot.Connector, channel string) {
for { for {
time.Sleep(time.Duration(frequency) * time.Second) time.Sleep(time.Duration(frequency) * time.Second)
for _, twitcherName := range p.c.GetArray("Twitch."+channel+".Users", []string{}) { for _, twitcherName := range p.config.GetArray("Twitch."+channel+".Users", []string{}) {
twitcherName = strings.ToLower(twitcherName)
if err := p.checkTwitch(c, channel, p.twitchList[twitcherName], false); err != nil { if err := p.checkTwitch(c, channel, p.twitchList[twitcherName], false); err != nil {
log.Error().Err(err).Msgf("error in twitch loop") log.Error().Err(err).Msgf("error in twitch loop")
} }
@ -289,8 +246,8 @@ func (p *TwitchPlugin) checkTwitch(c bot.Connector, channel string, twitcher *Tw
baseURL.RawQuery = query.Encode() baseURL.RawQuery = query.Encode()
cid := p.c.Get("twitch.clientid", "") cid := p.config.Get("twitch.clientid", "")
token := p.c.Get("twitch.token", "") token := p.config.Get("twitch.token", "")
if cid == token && cid == "" { if cid == token && cid == "" {
log.Info().Msgf("Twitch plugin not enabled.") log.Info().Msgf("Twitch plugin not enabled.")
return nil return nil
@ -318,9 +275,9 @@ func (p *TwitchPlugin) checkTwitch(c bot.Connector, channel string, twitcher *Tw
title = games[0].Title title = games[0].Title
} }
notStreamingTpl := p.c.Get("Twitch.NotTpl", notStreamingTplFallback) notStreamingTpl := p.config.Get("Twitch.NotTpl", notStreamingTplFallback)
isStreamingTpl := p.c.Get("Twitch.IsTpl", isStreamingTplFallback) isStreamingTpl := p.config.Get("Twitch.IsTpl", isStreamingTplFallback)
stoppedStreamingTpl := p.c.Get("Twitch.StoppedTpl", stoppedStreamingTplFallback) stoppedStreamingTpl := p.config.Get("Twitch.StoppedTpl", stoppedStreamingTplFallback)
buf := bytes.Buffer{} buf := bytes.Buffer{}
info := struct { info := struct {
@ -338,31 +295,31 @@ func (p *TwitchPlugin) checkTwitch(c bot.Connector, channel string, twitcher *Tw
t, err := template.New("notStreaming").Parse(notStreamingTpl) t, err := template.New("notStreaming").Parse(notStreamingTpl)
if err != nil { if err != nil {
log.Error().Err(err) log.Error().Err(err)
p.b.Send(c, bot.Message, channel, err) p.bot.Send(c, bot.Message, channel, err)
t = template.Must(template.New("notStreaming").Parse(notStreamingTplFallback)) t = template.Must(template.New("notStreaming").Parse(notStreamingTplFallback))
} }
t.Execute(&buf, info) t.Execute(&buf, info)
p.b.Send(c, bot.Message, channel, buf.String()) p.bot.Send(c, bot.Message, channel, buf.String())
} else { } else {
t, err := template.New("isStreaming").Parse(isStreamingTpl) t, err := template.New("isStreaming").Parse(isStreamingTpl)
if err != nil { if err != nil {
log.Error().Err(err) log.Error().Err(err)
p.b.Send(c, bot.Message, channel, err) p.bot.Send(c, bot.Message, channel, err)
t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback)) t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback))
} }
t.Execute(&buf, info) t.Execute(&buf, info)
p.b.Send(c, bot.Message, channel, buf.String()) p.bot.Send(c, bot.Message, channel, buf.String())
} }
} else if gameID == "" { } else if gameID == "" {
if twitcher.gameID != "" { if twitcher.gameID != "" {
t, err := template.New("stoppedStreaming").Parse(stoppedStreamingTpl) t, err := template.New("stoppedStreaming").Parse(stoppedStreamingTpl)
if err != nil { if err != nil {
log.Error().Err(err) log.Error().Err(err)
p.b.Send(c, bot.Message, channel, err) p.bot.Send(c, bot.Message, channel, err)
t = template.Must(template.New("stoppedStreaming").Parse(stoppedStreamingTplFallback)) t = template.Must(template.New("stoppedStreaming").Parse(stoppedStreamingTplFallback))
} }
t.Execute(&buf, info) t.Execute(&buf, info)
p.b.Send(c, bot.Message, channel, buf.String()) p.bot.Send(c, bot.Message, channel, buf.String())
} }
twitcher.gameID = "" twitcher.gameID = ""
} else { } else {
@ -370,11 +327,11 @@ func (p *TwitchPlugin) checkTwitch(c bot.Connector, channel string, twitcher *Tw
t, err := template.New("isStreaming").Parse(isStreamingTpl) t, err := template.New("isStreaming").Parse(isStreamingTpl)
if err != nil { if err != nil {
log.Error().Err(err) log.Error().Err(err)
p.b.Send(c, bot.Message, channel, err) p.bot.Send(c, bot.Message, channel, err)
t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback)) t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback))
} }
t.Execute(&buf, info) t.Execute(&buf, info)
p.b.Send(c, bot.Message, channel, buf.String()) p.bot.Send(c, bot.Message, channel, buf.String())
} }
twitcher.gameID = gameID twitcher.gameID = gameID
} }
@ -382,8 +339,8 @@ func (p *TwitchPlugin) checkTwitch(c bot.Connector, channel string, twitcher *Tw
} }
func (p *TwitchPlugin) validateCredentials() error { func (p *TwitchPlugin) validateCredentials() error {
cid := p.c.Get("twitch.clientid", "") cid := p.config.Get("twitch.clientid", "")
token := p.c.Get("twitch.token", "") token := p.config.Get("twitch.token", "")
if token == "" { if token == "" {
return p.reAuthenticate() return p.reAuthenticate()
} }
@ -396,8 +353,8 @@ func (p *TwitchPlugin) validateCredentials() error {
} }
func (p *TwitchPlugin) reAuthenticate() error { func (p *TwitchPlugin) reAuthenticate() error {
cid := p.c.Get("twitch.clientid", "") cid := p.config.Get("twitch.clientid", "")
secret := p.c.Get("twitch.secret", "") secret := p.config.Get("twitch.secret", "")
if cid == "" || secret == "" { if cid == "" || secret == "" {
return fmt.Errorf("could not request a new token without config values set") return fmt.Errorf("could not request a new token without config values set")
} }
@ -420,5 +377,5 @@ func (p *TwitchPlugin) reAuthenticate() error {
}{} }{}
err = json.Unmarshal(body, &credentials) err = json.Unmarshal(body, &credentials)
log.Debug().Int("expires", credentials.ExpiresIn).Msgf("setting new twitch token") log.Debug().Int("expires", credentials.ExpiresIn).Msgf("setting new twitch token")
return p.c.RegisterSecret("twitch.token", credentials.AccessToken) return p.config.RegisterSecret("twitch.token", credentials.AccessToken)
} }

View File

@ -13,17 +13,6 @@ import (
"github.com/velour/catbase/bot/user" "github.com/velour/catbase/bot/user"
) )
func makeRequest(payload string) bot.Request {
c, k, m := makeMessage(payload)
return bot.Request{
Conn: c,
Kind: k,
Msg: m,
Values: nil,
Args: nil,
}
}
func makeMessage(payload string) (bot.Connector, bot.Kind, msg.Message) { func makeMessage(payload string) (bot.Connector, bot.Kind, msg.Message) {
isCmd := strings.HasPrefix(payload, "!") isCmd := strings.HasPrefix(payload, "!")
if isCmd { if isCmd {
@ -42,8 +31,8 @@ func makeTwitchPlugin(t *testing.T) (*TwitchPlugin, *bot.MockBot) {
c := New(mb) c := New(mb)
mb.Config().Set("twitch.clientid", "fake") mb.Config().Set("twitch.clientid", "fake")
mb.Config().Set("twitch.authorization", "fake") mb.Config().Set("twitch.authorization", "fake")
c.c.SetArray("Twitch.Channels", []string{"test"}) c.config.SetArray("Twitch.Channels", []string{"test"})
c.c.SetArray("Twitch.test.Users", []string{"drseabass"}) c.config.SetArray("Twitch.test.Users", []string{"drseabass"})
assert.NotNil(t, c) assert.NotNil(t, c)
c.twitchList["drseabass"] = &Twitcher{ c.twitchList["drseabass"] = &Twitcher{
@ -56,6 +45,6 @@ func makeTwitchPlugin(t *testing.T) (*TwitchPlugin, *bot.MockBot) {
func TestTwitch(t *testing.T) { func TestTwitch(t *testing.T) {
b, mb := makeTwitchPlugin(t) b, mb := makeTwitchPlugin(t)
b.twitchStatus(makeRequest("!twitch status")) b.message(makeMessage("!twitch status"))
assert.NotEmpty(t, mb.Messages) assert.NotEmpty(t, mb.Messages)
} }