mirror of https://github.com/velour/catbase.git
pubsub: add counter pub
This commit is contained in:
parent
4f9b50f47a
commit
3343a98802
|
@ -3,10 +3,14 @@
|
|||
package bot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
@ -263,3 +267,25 @@ func (b *bot) selfSaid(conn Connector, channel, message string, action bool) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PubToASub sends updates to subscribed URLs
|
||||
func (b *bot) PubToASub(subject string, payload interface{}) {
|
||||
key := fmt.Sprintf("pubsub.%s.url", subject)
|
||||
subs := b.config.GetArray(key, []string{})
|
||||
if len(subs) == 0 {
|
||||
return
|
||||
}
|
||||
encodedBody, _ := json.Marshal(struct {
|
||||
Payload interface{} `json:"payload"`
|
||||
}{payload})
|
||||
body := bytes.NewBuffer(encodedBody)
|
||||
for _, url := range subs {
|
||||
r, err := http.Post(url, "text/json", body)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
} else {
|
||||
body, _ := ioutil.ReadAll(r.Body)
|
||||
log.Debug().Msgf("Response body: %s", string(body))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -172,6 +172,9 @@ type Bot interface {
|
|||
|
||||
// Check valid password
|
||||
CheckPassword(secret, password string) bool
|
||||
|
||||
// PubToASub publishes a message to any subscribers
|
||||
PubToASub(subject string, payload interface{})
|
||||
}
|
||||
|
||||
// Connector represents a server connection to a chat service
|
||||
|
|
|
@ -126,3 +126,4 @@ func (mb *MockBot) OnBlacklist(ch, p string) bool { return false }
|
|||
func (mb *MockBot) URLFormat(title, url string) string { return title + url }
|
||||
func (mb *MockBot) CheckPassword(secret, password string) bool { return true }
|
||||
func (mb *MockBot) ListenAndServe() {}
|
||||
func (mb *MockBot) PubToASub(subject string, payload interface{}) {}
|
||||
|
|
|
@ -160,7 +160,7 @@ func (p *CounterPlugin) handleCounterAPI(w http.ResponseWriter, r *http.Request)
|
|||
}
|
||||
|
||||
type Update struct {
|
||||
Who string
|
||||
What string
|
||||
Amount int
|
||||
Who string `json:"who"`
|
||||
What string `json:"what"`
|
||||
Amount int `json:"amount"`
|
||||
}
|
||||
|
|
|
@ -344,6 +344,11 @@ func New(b bot.Bot) *CounterPlugin {
|
|||
b.Register(cp, bot.Help, cp.help)
|
||||
cp.registerWeb()
|
||||
|
||||
RegisterUpdate(func(r bot.Request, u Update) {
|
||||
log.Debug().Msgf("Publishing update %v", u)
|
||||
b.PubToASub("counter", u)
|
||||
})
|
||||
|
||||
return cp
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue