-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.go
85 lines (69 loc) · 1.92 KB
/
slack.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"golang.org/x/net/websocket"
)
type startResponse struct {
Ok bool `json:"ok"`
Error string `json:"error"`
Url string `json:"url"`
Self self `json:"self"`
}
type botID string
type self struct {
ID botID `json:"id"`
Name string `json:"name"`
Prefs map[string]interface{} `json:"prefs"`
Created int `json:"created"`
ManualPresence string `json:"manual_presence"`
}
func connect(apiKey string) (*websocket.Conn, botID, error) {
resp, err := http.Get(fmt.Sprintf("https://slack.com/api/rtm.start?token=%s", apiKey))
if err != nil {
return nil, "", err
}
if resp.StatusCode != 200 {
return nil, "", fmt.Errorf("Expected status 200")
}
body, err := ioutil.ReadAll(resp.Body)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return nil, "", err
}
startResponse := startResponse{}
err = json.Unmarshal(body, &startResponse)
if err != nil {
return nil, "", err
}
if !startResponse.Ok {
return nil, "", fmt.Errorf("Start response not ok, got: %+v", startResponse)
}
// Connect to the websocket using the URL we received
webSocket, err := websocket.Dial(startResponse.Url, "", "https://api.slack.com/")
if err != nil {
return nil, "", err
}
// Return the bot ID, it is the ID that is returned in meesages when the bot is mentioned
return webSocket, startResponse.Self.ID, nil
}
type Message struct {
ID int `json:"id,omitempty"`
Type string `json:"type"`
Channel string `json:"channel"`
Text string `json:"text"`
}
func getMessage(ws *websocket.Conn) (*Message, error) {
msg := &Message{}
return msg, websocket.JSON.Receive(ws, &msg)
}
var messageNumber int
func postMessage(ws *websocket.Conn, msg *Message) error {
messageNumber++
msg.ID = messageNumber
return websocket.JSON.Send(ws, msg)
}