-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslack-api.go
92 lines (70 loc) · 1.68 KB
/
slack-api.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
package main
import (
"encoding/json"
"fmt"
"github.com/sger/wwdc-bot/Godeps/_workspace/src/golang.org/x/net/websocket"
"io/ioutil"
"log"
"net/http"
"sync/atomic"
)
const URL_SLACK_API = "https://api.slack.com/"
const URL_SLACK_API_RTM_START = "https://slack.com/api/rtm.start"
var counter uint64
type RtmStartResponse struct {
Ok bool `json:"ok"`
Error string `json:"error"`
Url string `json:"url"`
Self SelfResponse `json:"self"`
}
type SelfResponse struct {
Id string `json:"id"`
Name string `json:"name"`
}
type Message struct {
Id uint64 `json:"id"`
Type string `json:"type"`
Channel string `json:"channel"`
Text string `json:"text"`
User string `json:"user"`
}
func GetMessage(ws *websocket.Conn) (m Message, err error) {
err = websocket.JSON.Receive(ws, &m)
return
}
func PostMessage(ws *websocket.Conn, m Message) error {
m.Id = atomic.AddUint64(&counter, 1)
return websocket.JSON.Send(ws, m)
}
func Connect(token string) (*websocket.Conn, *RtmStartResponse, error) {
r, err := Start(token)
if err != nil {
log.Fatal(err)
}
ws, err := websocket.Dial(r.Url, "", URL_SLACK_API)
if err != nil {
log.Fatal(err)
}
return ws, r, err
}
func Start(token string) (*RtmStartResponse, error) {
url := fmt.Sprintf(URL_SLACK_API_RTM_START+"?token=%s", token)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
defer resp.Body.Close()
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var result RtmStartResponse
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return &result, nil
}