counter: fix api and add a message when one exists

This commit is contained in:
Chris Sexton 2021-11-28 14:12:38 -05:00 committed by Chris Sexton
parent 2a9ae13560
commit 6d004d8d1f
3 changed files with 25 additions and 9 deletions

View File

@ -4,6 +4,7 @@ import (
"embed"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
@ -69,12 +70,24 @@ func (p *CounterPlugin) mkIncrementAPI(delta int) func(w http.ResponseWriter, r
fmt.Fprint(w, string(j))
return
}
body, _ := ioutil.ReadAll(r.Body)
postData := map[string]string{}
err = json.Unmarshal(body, &postData)
personalMsg := ""
if inputMsg, ok := postData["message"]; ok {
personalMsg = fmt.Sprintf("\nMessage: %s", inputMsg)
}
chs := p.cfg.GetArray("channels", []string{p.cfg.Get("channels", "none")})
req := &bot.Request{
Conn: p.b.DefaultConnector(),
Kind: bot.Message,
Msg: msg.Message{
User: &u,
ChannelName: "#API",
// Noting here that we're only going to do goals in a "default"
// channel even if it should send updates to others.
Channel: chs[0],
Body: fmt.Sprintf("%s += %d", itemName, delta),
Time: time.Now(),
},
@ -82,12 +95,11 @@ func (p *CounterPlugin) mkIncrementAPI(delta int) func(w http.ResponseWriter, r
Args: nil,
}
item.UpdateDelta(req, delta)
msg := fmt.Sprintf("%s changed their %s counter by %d for a total of %d via the amazing %s API",
userName, itemName, delta, item.Count, p.cfg.Get("nick", "catbase"))
for _, ch := range p.cfg.GetArray("channels", []string{}) {
msg := fmt.Sprintf("%s changed their %s counter by %d for a total of %d via the amazing %s API. %s",
userName, itemName, delta, item.Count, p.cfg.Get("nick", "catbase"), personalMsg)
for _, ch := range chs {
p.b.Send(p.b.DefaultConnector(), bot.Message, ch, msg)
req.Msg.Channel = ch
sendUpdate(req, userName, itemName, item.Count)
}
j, _ := json.Marshal(struct{ Status bool }{true})
fmt.Fprint(w, string(j))

View File

@ -733,6 +733,8 @@ func RegisterUpdate(f updateFunc) {
}
func sendUpdate(r *bot.Request, who, what string, amount int) {
log.Debug().
Msgf("Updating %s for %s with %d", who, what, amount)
if r == nil {
return
}

View File

@ -213,6 +213,8 @@ func (p *GoalsPlugin) checkGoal(c bot.Connector, ch, what, who string) {
perc := float64(item.Count) / float64(g.Amount) * 100.0
remaining := p.remainingText(item, g)
log.Debug().Msgf("ch: %v, perc: %.2f, remaining: %s", ch, perc, remaining)
if perc >= 100 {
p.deregister(c, ch, g.Kind, g.What, g.Who)
m := fmt.Sprintf("You made it! You have %.2f%% of %s and now it's done.", perc, what)
@ -316,7 +318,7 @@ func (g goal) Delete() error {
}
func (p *GoalsPlugin) update(r bot.Request, u counter.Update) {
log.Debug().Msgf("entered update for %#v", u)
log.Debug().Msgf("entered update for %#v in ch: %v", u, r.Msg.Channel)
gs, err := p.getGoal(u.Who, u.What)
if err != nil {
log.Error().Err(err).Msgf("could not get goal for %#v", u)