catbase/plugins/tell/tell.go

116 lines
2.4 KiB
Go
Raw Normal View History

2017-11-16 22:05:22 +00:00
package tell
import (
"fmt"
"strings"
2019-10-08 20:50:29 +00:00
"github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx"
2017-11-16 22:05:22 +00:00
"github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg"
)
type delayedMsg string
type TellPlugin struct {
2019-10-08 20:50:29 +00:00
b bot.Bot
db *sqlx.DB
2017-11-16 22:05:22 +00:00
}
func New(b bot.Bot) *TellPlugin {
2019-10-08 20:50:29 +00:00
tp := &TellPlugin{b, b.DB()}
b.Register(tp, bot.Message, tp.message)
2019-10-08 20:50:29 +00:00
tp.createDB()
return tp
2017-11-16 22:05:22 +00:00
}
2019-10-08 20:50:29 +00:00
type tell struct {
ID int
Who string
What string
}
func (t *TellPlugin) createDB() {
q := `create table if not exists tell (
id integer primary key autoincrement,
who string,
what string
)`
t.db.MustExec(q)
}
func (t *TellPlugin) getTells() []tell {
result := []tell{}
q := `select * from tell`
t.db.Select(&result, q)
return result
}
func (t *TellPlugin) rmTell(entry tell) {
q := `delete from tell where id=?`
if _, err := t.db.Exec(q, entry.ID); err != nil {
log.Error().Err(err).Msg("could not remove tell")
}
}
func (t *TellPlugin) addTell(who, what string) error {
q := `insert into tell (who, what) values (?, ?)`
_, err := t.db.Exec(q, who, what)
if err != nil {
log.Error().Err(err).Msg("could not add tell")
}
return err
}
func (t *TellPlugin) check(who string) []tell {
result := []tell{}
tells := t.getTells()
for _, e := range tells {
if e.Who == who {
result = append(result, e)
t.rmTell(e)
}
}
return result
}
func (t *TellPlugin) checkValidTarget(ch, target string) bool {
users := t.b.Who(ch)
log.Debug().
Str("ch", ch).
Str("target", target).
Interface("users", users).
Msg("checking valid target")
for _, u := range users {
if u.Name == target {
return true
}
}
return false
}
2019-05-27 23:21:53 +00:00
func (t *TellPlugin) message(c bot.Connector, kind bot.Kind, message msg.Message, args ...interface{}) bool {
2019-10-08 20:50:29 +00:00
if strings.HasPrefix(strings.ToLower(message.Body), "tell ") {
2017-11-16 22:05:22 +00:00
parts := strings.Split(message.Body, " ")
2017-11-17 13:39:35 +00:00
target := strings.ToLower(parts[1])
2019-10-08 20:50:29 +00:00
if !t.checkValidTarget(message.Channel, target) {
return false
}
2017-11-16 22:05:22 +00:00
newMessage := strings.Join(parts[2:], " ")
newMessage = fmt.Sprintf("Hey, %s. %s said: %s", target, message.User.Name, newMessage)
2019-10-08 20:50:29 +00:00
t.addTell(target, newMessage)
2019-05-27 23:21:53 +00:00
t.b.Send(c, bot.Message, message.Channel, fmt.Sprintf("Okay. I'll tell %s.", target))
2017-11-16 22:05:22 +00:00
return true
}
2017-11-17 13:39:35 +00:00
uname := strings.ToLower(message.User.Name)
2019-10-08 20:50:29 +00:00
if tells := t.check(uname); len(tells) > 0 {
for _, m := range tells {
t.b.Send(c, bot.Message, message.Channel, m.What)
2017-11-16 22:05:22 +00:00
}
return true
}
return false
}