-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslack.go
More file actions
94 lines (73 loc) · 1.74 KB
/
slack.go
File metadata and controls
94 lines (73 loc) · 1.74 KB
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
package main
import (
"fmt"
"io/ioutil"
"encoding/json"
"sync/atomic"
"log"
"net/http"
"golang.org/x/net/websocket"
)
type rtmStartResponse struct {
Ok bool `json:"ok"`
Error string `json:"error"`
Url string `json:"url"`
Self responseSelf `json:"self"`
}
type responseSelf struct {
Id string `json:"id"`
}
func slackStart(token string) (wsurl, id string, err error) {
url := fmt.Sprintf("https://slack.com/api/rtm.start?token=%s", token)
resp, err := http.Get(url)
if err != nil {
return
}
if resp.StatusCode != 200 {
err = fmt.Errorf("Request failed with code %d", resp.StatusCode)
return
}
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return
}
var responseBody rtmStartResponse
err = json.Unmarshal(body, &responseBody)
if err != nil {
return
}
if !responseBody.Ok {
err = fmt.Errorf("Slack error: %s", responseBody.Error)
return
}
wsurl = responseBody.Url
id = responseBody.Self.Id
return
}
type SlackMessage struct {
Id uint64 `json:"id"`
Type string `json:"type"`
Channel string `json:"channel"`
Text string `json:"text"`
}
func getMessage(ws *websocket.Conn) (m SlackMessage, err error) {
err = websocket.JSON.Receive(ws, &m)
return
}
var messageCount uint64
func sendMessage(ws *websocket.Conn, m SlackMessage) error {
m.Id = atomic.AddUint64(&messageCount, 1)
return websocket.JSON.Send(ws, m)
}
func connectToSlack(token string) (*websocket.Conn, string) {
wsurl, id, err := slackStart(token)
if err != nil {
log.Fatal(err)
}
ws, err := websocket.Dial(wsurl, "", "https://api.slack.com/")
if err != nil {
log.Fatal(err)
}
return ws, id
}