flokati/modules/webhook.go

60 lines
1.2 KiB
Go
Raw Normal View History

2018-04-22 09:28:18 +00:00
// vi:ts=4:sts=4:sw=4:noet:tw=72
package modules
import (
"encoding/json"
2018-04-22 09:39:52 +00:00
"flag"
2018-04-22 09:28:18 +00:00
"fmt"
"net/http"
2018-04-22 12:21:58 +00:00
"strings"
2018-04-22 09:28:18 +00:00
"git.dnix.de/an/xlog"
)
2018-04-22 09:39:52 +00:00
var (
2018-04-22 11:54:06 +00:00
webhookPort = flag.String("webhook_port", "8080", "Webhook listener port")
webhookChan = flag.String("webhook_chan", "", "Channel to post into")
2018-04-22 09:39:52 +00:00
)
2018-04-22 09:28:18 +00:00
func init() {
MsgFuncs["webhook"] = webhookHandleMessage
RunFuncs["webhook"] = webhookRun
}
func webhookRun() {
xlog.Info("webhook listener started")
2018-04-22 11:54:06 +00:00
http.HandleFunc("/webhook", webhookHandleHTTP)
2018-04-22 12:05:56 +00:00
xlog.Fatal("%v", http.ListenAndServe(":8080", nil))
2018-04-22 09:28:18 +00:00
}
2018-04-22 11:54:39 +00:00
func webhookHandleMessage(m *Message) {
2018-04-22 12:21:58 +00:00
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:
}
2018-04-22 11:54:39 +00:00
}
2018-04-22 11:54:06 +00:00
2018-04-22 09:28:18 +00:00
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: ")
2018-04-22 09:31:15 +00:00
for k, v := range data {
2018-04-22 09:28:18 +00:00
fmt.Printf("%s : %v\n", k, v)
2018-04-22 09:39:52 +00:00
if k == "text" {
2018-04-22 09:45:53 +00:00
SayCh <- fmt.Sprintf("%s\n%v", *webhookChan, v)
2018-04-22 09:39:52 +00:00
}
2018-04-22 09:28:18 +00:00
}
}