matrix-handler/pkg/slack/slack.go

50 lines
1.0 KiB
Go
Raw Permalink Normal View History

2021-02-04 08:29:49 +00:00
package slack
import (
"encoding/json"
"io/ioutil"
"net/http"
"git.linuxrocker.com/mattburchett/matrix-handler/pkg/config"
"git.linuxrocker.com/mattburchett/matrix-handler/pkg/matrix"
"git.linuxrocker.com/mattburchett/matrix-handler/pkg/router"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
// Handle is the incoming handler for Slack-type requests.
func Handle(cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
// Get Matrix Token for User/Pass in path
token := matrix.GetToken(cfg, vars)
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Error().Err(err).Msg("An error has occurred")
}
data := parseSlack(reqBody)
2021-09-18 07:11:22 +00:00
// Attempt to join room before publishing
2021-02-04 23:50:52 +00:00
matrix.JoinRoom(cfg, vars, token)
// Publish to Matrix
2021-02-04 08:29:49 +00:00
resp := matrix.PublishText(cfg, vars, []byte(data), token)
router.Respond(w, 200, resp)
}
}
func parseSlack(body []byte) string {
reqBody := struct {
Text string
}{}
2021-02-04 08:33:52 +00:00
json.Unmarshal(body, &reqBody)
2021-02-04 08:29:49 +00:00
2021-02-04 08:33:52 +00:00
return reqBody.Text
2021-02-04 08:29:49 +00:00
}