Skip to content

Instantly share code, notes, and snippets.

@lafolle
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lafolle/bb504fb36d62bd5e53b5 to your computer and use it in GitHub Desktop.
Save lafolle/bb504fb36d62bd5e53b5 to your computer and use it in GitHub Desktop.
Custom Slack Command to post random XKCD comic to Slack channel

There are 1500 comics in XKCD. This server/handler post a random comic (title, imgurl) to slack slack channel.

As response of Slack Custom Command cannot be unfurled by Slack, we make a post webhook request to the channel from which /xkcd command is issued.

package main
import (
"fmt"
"encoding/json"
"net/http"
"math/rand"
"io/ioutil"
"bytes"
)
const (
XKCD_COMIC_COUNT = 1550
SLACK_TOKEN = ""
SLACK_XKCD_WEBHOOK_URL = ""
)
var (
xkcd_url string = "http://xkcd.com/%d/info.0.json"
)
type XKCD struct {
Month string
Img string
Safe_title string
Year string
Title string
Day string
Num int
}
func (x XKCD) String() {
fmt.Println(x.Num, x.Title, x.Img)
}
func serveComic(w http.ResponseWriter, r *http.Request) {
var x XKCD
var token, url, channel string
var slack_resp map[string]interface{}= make(map[string]interface{})
token = r.URL.Query().Get("token")
if token != SLACK_TOKEN {
w.Write([]byte(""))
return
}
channel = r.URL.Query().Get("channel_name")
if len(channel) == 0 {
channel = "random"
}
url = fmt.Sprintf(xkcd_url, rand.Intn(XKCD_COMIC_COUNT))
resp, err := http.Get(url)
if err != nil {
panic(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
defer resp.Body.Close()
err = json.Unmarshal(body, &x)
if err != nil {
fmt.Println(err)
}
msg := fmt.Sprintf("%s <%s>", x.Title, x.Img)
slack_resp["text"] = msg
slack_resp["unfurl_media"] = true
slack_resp["unfurl_links"] = true
slack_resp["channel"] = fmt.Sprintf("#%s", channel)
var b bytes.Buffer
encoder := json.NewEncoder(&b)
encoder.Encode(slack_resp)
w.Header().Set("Content-Type", "application/json")
req, err := http.NewRequest("POST", SLACK_XKCD_WEBHOOK_URL, bytes.NewBuffer(b.Bytes()))
if err != nil {
panic(err)
}
client := &http.Client{}
resp, err = client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
}
func main() {
http.HandleFunc("/xkcd", serveComic)
http.ListenAndServe(":7080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment