Skip to content

Instantly share code, notes, and snippets.

@jeremywho
Last active December 4, 2016 20:06
Show Gist options
  • Save jeremywho/4aa3f0f9854df0339a49f6b5760beb4f to your computer and use it in GitHub Desktop.
Save jeremywho/4aa3f0f9854df0339a49f6b5760beb4f to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/websocket"
)
type authResponse struct {
URL string `json:"url"`
}
type message struct {
ID string `json:"id"`
ReplyTo string `json:"reply_to"`
Type string `json:"type"`
Channel string `json:"channel"`
Text string `json:"text"`
}
func main() {
token := "xoxb-put your token here"
URL := getWebsocketURL(token)
var dialer *websocket.Dialer
conn, _, err := dialer.Dial(URL, nil)
if err != nil {
fmt.Println(err)
return
}
for {
m := message{}
err := conn.ReadJSON(&m)
if err != nil {
fmt.Println(err)
}
fmt.Printf("received: %+v\n", m)
if m.Type == "message" && m.ReplyTo != "1" {
echo := message{
ID: "1",
Type: m.Type,
Channel: m.Channel,
Text: m.Text,
}
conn.WriteJSON(echo)
}
}
}
func getWebsocketURL(token string) string {
url := "https://slack.com/api/rtm.start?token=" + token
resp, err := http.Get(url)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
res := authResponse{}
json.Unmarshal([]byte(body), &res)
return res.URL
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment