-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslack.go
More file actions
83 lines (70 loc) · 1.65 KB
/
Copy pathslack.go
File metadata and controls
83 lines (70 loc) · 1.65 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"golang.org/x/net/websocket"
)
type responseRTMStart 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", botToken)
resp, err := http.Get(URL)
if err != nil {
log.Printf("error establishing connection %s:", err)
}
if resp.StatusCode != 200 {
err = fmt.Errorf("API request failed with code %d", resp.StatusCode)
return
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return
}
respObj := new(responseRTMStart)
err = json.Unmarshal(body, &respObj)
if err != nil {
return
}
if !respObj.Ok {
err = fmt.Errorf("Slack error: %s", respObj.Error)
return
}
wsURL = respObj.URL
id = respObj.Self.ID
return
}
type Message struct {
Type string `json:"type"`
Channel string `json:"channel"`
Text string `json:"text"`
}
func getMessage(ws *websocket.Conn) (m Message, err error) {
err = websocket.JSON.Receive(ws, &m)
return
}
func postMessage(ws *websocket.Conn, m Message) error {
return websocket.JSON.Send(ws, m)
}
// Begins Real-Time API session and returns the websocket and the ID of the bot
func slackConnect() (*websocket.Conn, string) {
websocketURL, ID, err := slackStart(botToken)
if err != nil {
log.Fatal(err)
}
webSocket, err := websocket.Dial(websocketURL, "", "https://api.slack.com/")
if err != nil {
log.Fatal(err)
}
return webSocket, ID
}