mirror of
https://git.sr.ht/~ashkeel/strimertul
synced 2024-09-30 02:40:33 +00:00
66 lines
1.8 KiB
Go
66 lines
1.8 KiB
Go
package client
|
|
|
|
import (
|
|
"math/rand"
|
|
"strconv"
|
|
"strings"
|
|
textTemplate "text/template"
|
|
|
|
"github.com/Masterminds/sprig/v3"
|
|
|
|
"git.sr.ht/~ashkeel/strimertul/twitch/template"
|
|
|
|
"github.com/nicklaw5/helix/v2"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
const ChatCounterPrefix = "twitch/chat/counters/"
|
|
|
|
type templateEngineImpl struct {
|
|
customFunctions textTemplate.FuncMap
|
|
}
|
|
|
|
func (b *templateEngineImpl) MakeTemplate(message string) (*textTemplate.Template, error) {
|
|
return textTemplate.New("").Funcs(sprig.TxtFuncMap()).Funcs(b.customFunctions).Parse(message)
|
|
}
|
|
|
|
func (c *Client) GetTemplateEngine() template.Engine {
|
|
return &templateEngineImpl{
|
|
customFunctions: textTemplate.FuncMap{
|
|
"user": func(message helix.EventSubChannelChatMessageEvent) string {
|
|
return message.ChatterUserLogin
|
|
},
|
|
"param": func(num int, message helix.EventSubChannelChatMessageEvent) string {
|
|
parts := strings.Split(message.Message.Text, " ")
|
|
if num >= len(parts) {
|
|
return parts[len(parts)-1]
|
|
}
|
|
return parts[num]
|
|
},
|
|
"randomInt": func(min int, max int) int {
|
|
return rand.Intn(max-min) + min
|
|
},
|
|
"game": func(channel string) string {
|
|
channel = strings.TrimLeft(channel, "@")
|
|
info, err := c.API.SearchChannels(&helix.SearchChannelsParams{Channel: channel, First: 1, LiveOnly: false})
|
|
if err != nil {
|
|
return "unknown"
|
|
}
|
|
return info.Data.Channels[0].GameName
|
|
},
|
|
"count": func(name string) int {
|
|
counterKey := ChatCounterPrefix + name
|
|
counter := 0
|
|
if byt, err := c.DB.GetKey(counterKey); err == nil {
|
|
counter, _ = strconv.Atoi(byt)
|
|
}
|
|
counter++
|
|
err := c.DB.PutKey(counterKey, strconv.Itoa(counter))
|
|
if err != nil {
|
|
c.Logger.Error("Error saving key", zap.Error(err), zap.String("key", counterKey))
|
|
}
|
|
return counter
|
|
},
|
|
},
|
|
}
|
|
}
|