-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
117 lines (97 loc) · 2.5 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/slack-go/slack"
)
type Config struct {
SlackToken string
HttpPath string
BasicUser string
BasicPassword string
}
func readJSON(fn string, v interface{}) {
file, _ := os.Open(fn)
defer file.Close()
decoder := json.NewDecoder(file)
err := decoder.Decode(v)
if err != nil {
log.Println("error:", err)
}
}
var config Config
func main() {
config = Config{}
readJSON("config.json", &config)
api := slack.New(config.SlackToken)
rtm := api.NewRTM()
go rtm.ManageConnection()
log.Println("Slackbot started")
Loop:
for {
select {
case msg := <-rtm.IncomingEvents:
switch ev := msg.Data.(type) {
case *slack.HelloEvent:
// Ignore hello
case *slack.ConnectedEvent:
log.Println("Connection counter:", ev.ConnectionCount)
case *slack.MessageEvent:
if ev.Msg.User == "" {
continue
}
// only direct channels reply
if !strings.HasPrefix(ev.Msg.Channel, "D") {
continue
}
params := slack.OpenConversationParameters{ChannelID: ev.Msg.Channel}
userChannel, _, _, err := rtm.OpenConversation(¶ms)
if err != nil {
log.Printf("Get channel Error: %v\n", err)
continue
}
if userChannel.ID != ev.Msg.Channel {
continue
}
userInfo, err := rtm.GetUserInfo(ev.Msg.User)
if err != nil {
log.Printf("User info Error: %v\n", err)
continue
}
log.Printf("User: %v (%v); Message: %v\n", ev.Msg.User, userInfo.Profile.Email, ev.Msg.Text) // ev.Msg.User, ev.Msg.Channel
client := &http.Client{}
parameters := url.Values{}
parameters.Add("user", ev.Msg.User)
parameters.Add("message", ev.Msg.Text)
parameters.Add("email", userInfo.Profile.Email)
req, err := http.NewRequest("POST", config.HttpPath, strings.NewReader(parameters.Encode()))
if config.BasicUser != "" {
req.SetBasicAuth(config.BasicUser, config.BasicPassword)
}
resp, err := client.Do(req)
if err != nil {
log.Printf("HTTP request Error: %v\n", err)
continue
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("HTTP read Error %v\n", err)
} else {
log.Printf("HTTP response: %+v\n", string(body))
rtm.SendMessage(rtm.NewOutgoingMessage(string(body), ev.Msg.Channel))
}
case *slack.InvalidAuthEvent:
log.Printf("Invalid credentials")
break Loop
default:
// Ignore other events..
}
}
}
}