flokati/modules/webhook.go

60 lines
1.2 KiB
Go

// vi:ts=4:sts=4:sw=4:noet:tw=72
package modules
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"strings"
"git.dnix.de/an/xlog"
)
var (
webhookPort = flag.String("webhook_port", "8080", "Webhook listener port")
webhookChan = flag.String("webhook_chan", "", "Channel to post into")
)
func init() {
MsgFuncs["webhook"] = webhookHandleMessage
RunFuncs["webhook"] = webhookRun
}
func webhookRun() {
xlog.Info("webhook listener started")
http.HandleFunc("/webhook", webhookHandleHTTP)
xlog.Fatal("%v", http.ListenAndServe(":"+*webhookPort, nil))
}
func webhookHandleMessage(m *Message) {
tok := strings.Split(m.Text, " ")
if len(tok) < 1 {
return
}
switch tok[0] {
case "!webhook-add":
if len(tok) > 1 {
http.HandleFunc("/webhook/"+tok[1], webhookHandleHTTP)
}
default:
}
}
func webhookHandleHTTP(w http.ResponseWriter, r *http.Request) {
data := make(map[string]interface{})
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println("got webhook payload: ")
for k, v := range data {
fmt.Printf("%s : %v\n", k, v)
if k == "text" {
SayCh <- fmt.Sprintf("%s\n%v", *webhookChan, v)
}
}
}