Last active
March 21, 2016 16:36
-
-
Save fsaravia/98eb471539be80d72254 to your computer and use it in GitHub Desktop.
Post random text to Slack using Go
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 ( | |
"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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
First replace the
URL
constant with the URL from your configured incoming webhook#your-channel
can also be replaced by@a_username