forked from Empia/slackline
-
Notifications
You must be signed in to change notification settings - Fork 1
/
slackline.go
91 lines (73 loc) · 1.85 KB
/
slackline.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/codegangsta/martini"
"io"
"io/ioutil"
"net/http"
"os"
"regexp"
)
const postMessageURL = "/services/hooks/incoming-webhook?token="
type slackMessage struct {
Channel string `json:"channel"`
Username string `json:"username"`
Text string `json:"text"`
}
func (s slackMessage) payload() io.Reader {
content := []byte("payload=")
json, _ := json.Marshal(s)
content = append(content, json...)
return bytes.NewReader(content)
}
var mentionRegexp = regexp.MustCompile("<@([^>]+)>")
func (s *slackMessage) containsMention() bool {
return mentionRegexp.MatchString(s.Text)
}
func (s slackMessage) sendTo(domain, token string) (err error) {
payload := s.payload()
res, err := http.Post(
"https://"+domain+postMessageURL+token,
"application/x-www-form-urlencoded",
payload,
)
if res.StatusCode != 200 {
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return errors.New(res.Status + " - " + string(body))
}
return
}
func main() {
m := martini.Classic()
m.Post("/bridge", func(res http.ResponseWriter, req *http.Request) {
username := req.PostFormValue("user_name")
text := req.PostFormValue("text")
if username == "slackbot" {
// Avoid infinite loop
return
}
msg := slackMessage{
Username: username,
Text: text,
}
domain := req.URL.Query().Get("domain")
token := req.URL.Query().Get("token")
if os.Getenv("DEBUG_BRIDGE") == domain {
fmt.Printf("Request: %v\n", req.PostForm)
fmt.Printf("Message: %v\n", msg)
}
fmt.Printf("message=received domain=%s hasMention=%v token=%s\n", domain, msg.containsMention(), token)
err := msg.sendTo(domain, token)
if err != nil {
fmt.Printf("message=error description=%#v\n", err.Error())
res.WriteHeader(500)
} else {
fmt.Println("message=sent")
}
})
m.Run()
}