Common code for implementing Twitch bots.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
2.3 KiB

package bot
import (
"errors"
"fmt"
"raccatta.cc/bot/unstable/log"
)
func (b *Bot) AddTarget(id, login string, conf map[string]string) {
log.Debug().Str("user-id", id).Str("login", login).Interface("conf", conf).Msg("Add target")
if b.ChannelManager != nil {
defer b.ChannelManager.AddTarget(id, login, conf)
}
b.mu.Lock()
defer b.mu.Unlock()
if id == "" {
nu, ok := b.byname[login]
if !ok {
log.Debug().Str("login", login).Msg("Can't create new target without ID")
return
}
id = nu.id
}
u, ok := b.byid[id]
if !ok {
u = &user{id: id, login: login}
b.byid[id] = u
b.byname[login] = u // ! assert not set
} else if u.login != login {
// User renamed
delete(b.byname, u.login)
b.Commander.Remove(u.login)
b.jmgr.Part("#" + u.login)
u.login = login
b.byname[login] = u // ! assert not set
} else {
// Nothing to do
}
b.Commander.Configure(login, conf)
// TODO: maybe special-case renames so they always reuse the same
// connection; edge case
b.jmgr.Join("#" + login)
}
func (b *Bot) RemoveTargetLogin(login string) error {
log.Debug().Str("login", login).Msg("Remove target")
// Always send a part
defer b.jmgr.Part("#" + login)
var chid string
b.mu.Lock()
cs, ok := b.byname[login]
if ok {
chid = cs.id
}
b.mu.Unlock()
if chid == "" {
return fmt.Errorf("Unknown channel %q", login)
}
b.RemoveTarget(chid, login)
return nil
}
func (b *Bot) RemoveTarget(id, login string) {
log.Debug().Str("login", login).Msg("Remove target")
if b.ChannelManager != nil {
defer b.ChannelManager.RemoveTarget(id, login)
}
b.mu.Lock()
defer b.mu.Unlock()
cs, ok := b.byname[login]
if ok {
delete(b.byname, login)
delete(b.byid, cs.id)
b.Commander.Remove(login)
}
}
//
// Live state (-> commander)
//
func (b *Bot) SetLive(id string, live bool) {
login := b.LoginFromID(id) // TODO
b.Commander.SetLive(id, login, live)
}
//
// ID mapping
//
func (b *Bot) LoginFromID(id string) string {
b.mu.Lock()
defer b.mu.Unlock()
cs, ok := b.byid[id]
if ok {
return cs.login
}
return ""
}
//
// Config
//
func (b *Bot) SetTargetConfig(id, login string, conf map[string]string) (string, error) {
if b.ConfigPropagation == nil {
return "", errors.New("Config propagation not enabled")
}
return b.ConfigPropagation(id, login, conf)
}
func (b *Bot) TargetConfig(login string) map[string]string {
return nil
}