Skip to content

Instantly share code, notes, and snippets.

@fsaravia
Last active March 21, 2016 16:36
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 fsaravia/98eb471539be80d72254 to your computer and use it in GitHub Desktop.
Save fsaravia/98eb471539be80d72254 to your computer and use it in GitHub Desktop.
Post random text to Slack using Go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
const (
URL string = "https://example.org"
CONTENT_TYPE string = "application/json"
SLACK_USERNAME string = "The tiny Go bot"
SLACK_EMOJI string = "https://blog.golang.org/gopher/gopher.png"
)
func main() {
slackRequest := map[string]string{
"text": strings.Join(os.Args[2:], " "),
"username": SLACK_USERNAME,
"icon_url": SLACK_EMOJI,
"channel": os.Args[1],
}
jsonRequest, _ := json.Marshal(&slackRequest)
resp, err := http.Post(URL, CONTENT_TYPE, bytes.NewReader(jsonRequest))
if err != nil {
log.Fatalf("Error building request: %s", err)
}
if resp.StatusCode != http.StatusOK {
log.Printf("Wrong status code: %s", resp.Status)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error parsing response: %s", err)
}
fmt.Println(string(body))
}
@fsaravia
Copy link
Author

Usage

First replace the URL constant with the URL from your configured incoming webhook

go build slack-post.go
./slack-post "#your-channel" "This is a test"

#your-channel can also be replaced by @a_username

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment