forked from trinchan/slackbot
/
main.go
86 lines (80 loc) · 1.89 KB
/
main.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
package main
import (
"encoding/json"
"github.com/gorilla/schema"
"github.com/trinchan/slackbot/robots"
"io"
"log"
"net/http"
"strconv"
"strings"
)
func main() {
http.HandleFunc("/slack", CommandHandler)
http.HandleFunc("/slack_hook", CommandHandler)
StartServer()
}
func CommandHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
hook := r.URL.Path == "/slack_hook"
if err == nil {
decoder := schema.NewDecoder()
command := new(robots.SlashCommand)
err := decoder.Decode(command, r.PostForm)
if err != nil {
log.Println("Couldn't parse post request:", err)
}
if hook {
c := strings.Split(command.Text, " ")
command.Command = c[1]
command.Text = strings.Join(c[2:], " ")
} else {
command.Command = command.Command[1:]
}
robot := GetRobot(command.Command)
w.WriteHeader(http.StatusOK)
if robot != nil {
if hook {
JSONResp(w, robot.Run(command))
} else {
plainResp(w, robot.Run(command))
}
} else {
r := "No robot for that command yet :("
if hook {
JSONResp(w, r)
} else {
plainResp(w, r)
}
}
}
}
func JSONResp(w http.ResponseWriter, msg string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
resp := map[string]string{"text": msg}
r, err := json.Marshal(resp)
if err != nil {
log.Println("Couldn't marshal hook response:", err)
} else {
io.WriteString(w, string(r))
}
}
func plainResp(w http.ResponseWriter, msg string) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
io.WriteString(w, msg)
}
func StartServer() {
port := robots.Config.Port
log.Printf("Starting HTTP server on %d", port)
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
if err != nil {
log.Fatal("Server start error: ", err)
}
}
func GetRobot(command string) robots.Robot {
if RobotInitFunction, ok := robots.Robots[command]; ok {
return RobotInitFunction()
} else {
return nil
}
}