1
0
Fork 0
mirror of https://github.com/Luzifer/cmd-slack.git synced 2024-10-18 04:34:24 +00:00
cmd-slack/main.go

73 lines
1.7 KiB
Go
Raw Permalink Normal View History

2016-05-22 17:50:50 +00:00
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"os"
2016-05-22 17:50:50 +00:00
"os/exec"
"strings"
2016-05-22 17:50:50 +00:00
"github.com/Luzifer/rconfig"
)
var (
cfg = struct {
2016-05-22 18:23:10 +00:00
Hook string `flag:"hook,h" default:"" description:"Slack incoming webhook"`
Username string `flag:"username,u" default:"CmdSlack" description:"Username to use in WebHook command"`
Icon string `flag:"icon,i" default:":package:" description:"Icon to use for the webhook"`
Channel string `flag:"channel,c" default:"" description:"Channel to send the message to"`
Description string `flag:"description,d" default:"" description:"Add a piece of text to prepent to the output"`
2016-05-22 17:50:50 +00:00
}{}
version = "dev"
)
type slack struct {
Username string `json:"username,omitempty"`
Icon string `json:"icon_emoji,omitempty"`
Channel string `json:"channel,omitempty"`
Text string `json:"text"`
}
func main() {
rconfig.Parse(&cfg)
cmdline := rconfig.Args()[1:]
buf := bytes.NewBuffer([]byte{})
cmd := exec.Command(cmdline[0], cmdline[1:]...)
cmd.Stdout = buf
if err := cmd.Run(); err != nil {
log.Fatalf("Command error: %s", err)
}
if strings.TrimSpace(buf.String()) == "" {
log.Printf("Command had empty output, ignoring")
os.Exit(0)
}
2016-05-22 18:23:10 +00:00
text := "```\n" + buf.String() + "```"
if cfg.Description != "" {
text = cfg.Description + "\n" + text
}
2016-05-22 17:50:50 +00:00
slo := slack{
Username: cfg.Username,
Icon: cfg.Icon,
Channel: cfg.Channel,
2016-05-22 18:23:10 +00:00
Text: text,
2016-05-22 17:50:50 +00:00
}
body := bytes.NewBuffer([]byte{})
if err := json.NewEncoder(body).Encode(slo); err != nil {
log.Fatalf("Encoder error: %s", err)
}
if _, err := http.Post(cfg.Hook, "application/json", body); err != nil {
log.Fatalf("Posting error: %s", err)
}
log.Printf("Posted successfully")
}