mirror of
https://github.com/Luzifer/twitch-bot.git
synced 2024-11-08 16:20:02 +00:00
56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"regexp"
|
|
"text/template"
|
|
"time"
|
|
|
|
"github.com/go-irc/irc"
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/Luzifer/twitch-bot/plugins"
|
|
)
|
|
|
|
var (
|
|
// Compile-time assertion
|
|
_ plugins.MsgFormatter = formatMessage
|
|
|
|
stripNewline = regexp.MustCompile(`(?m)\s*\n\s*`)
|
|
)
|
|
|
|
func formatMessage(tplString string, m *irc.Message, r *plugins.Rule, fields *plugins.FieldCollection) (string, error) {
|
|
compiledFields := plugins.NewFieldCollection()
|
|
|
|
if config != nil {
|
|
configLock.RLock()
|
|
compiledFields.SetFromData(config.Variables)
|
|
compiledFields.Set("permitTimeout", int64(config.PermitTimeout/time.Second))
|
|
configLock.RUnlock()
|
|
}
|
|
|
|
compiledFields.SetFromData(fields.Data())
|
|
|
|
if m != nil {
|
|
compiledFields.Set("msg", m)
|
|
}
|
|
compiledFields.Set("username", plugins.DeriveUser(m, fields))
|
|
compiledFields.Set("channel", plugins.DeriveChannel(m, fields))
|
|
|
|
// Template in frontend supports newlines, messages do not
|
|
tplString = stripNewline.ReplaceAllString(tplString, " ")
|
|
|
|
// Parse and execute template
|
|
tpl, err := template.
|
|
New(tplString).
|
|
Funcs(tplFuncs.GetFuncMap(m, r, compiledFields)).
|
|
Parse(tplString)
|
|
if err != nil {
|
|
return "", errors.Wrap(err, "parse template")
|
|
}
|
|
|
|
buf := new(bytes.Buffer)
|
|
err = tpl.Execute(buf, compiledFields.Data())
|
|
|
|
return buf.String(), errors.Wrap(err, "execute template")
|
|
}
|