Created
July 2, 2016 16:53
-
-
Save gophertron/c210c75591f078f2bc7f887e1df38ed0 to your computer and use it in GitHub Desktop.
slack websocket api example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"golang.org/x/net/websocket" | |
) | |
type RtmResponse struct { | |
Ok bool `json:"ok"` | |
Error string `json:"error"` | |
Url string `json:"url"` | |
Self RtmResponseSelf `json:"self"` | |
} | |
type Message struct { | |
Id uint64 `json:"id"` | |
Type string `json:"type"` | |
Channel string `json:"channel"` | |
Text string `json:"text"` | |
} | |
type RtmResponseSelf struct { | |
Id string `json:"id"` | |
} | |
var token = flag.String("t", "", "slack token") | |
func main() { | |
flag.Parse() | |
url := fmt.Sprintf("https://slack.com/api/rtm.start?token=%s", *token) | |
resp, err := http.Get(url) | |
if err != nil { | |
log.Println("ERROR:", err) | |
return | |
} | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Println("ERROR:", err) | |
return | |
} | |
var rtmResp RtmResponse | |
err = json.Unmarshal(body, &rtmResp) | |
if err != nil { | |
log.Println("ERROR:", err) | |
return | |
} | |
log.Println("RESPONSE:", rtmResp.Url) | |
ws, err := websocket.Dial(rtmResp.Url, "", "https://api.slack.com/") | |
if err != nil { | |
log.Println("ERROR:", err) | |
return | |
} | |
for { | |
var m Message | |
err = websocket.JSON.Receive(ws, &m) | |
if err != nil { | |
log.Println("ERROR:", err) | |
} | |
log.Println("MESSAGE:", m.Type, m.Text) | |
if m.Type == "message" { | |
m.Text = "Reply" | |
websocket.JSON.Send(ws, m) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment