-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhou.go
102 lines (81 loc) · 1.97 KB
/
hou.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/nlopes/slack"
)
func createParams(filename string) slack.PostMessageParameters {
var params slack.PostMessageParameters
params.Username = "hou"
params.IconEmoji = ":bell:"
params.Parse = "full"
if filename == "" {
return params
}
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return params
}
err = json.Unmarshal(bytes, ¶ms)
if err != nil {
return params
}
return params
}
func handleError(err error, quiet bool) {
if !quiet {
log.Fatal(err)
}
os.Exit(1)
}
func main() {
var channel, filename, mention string
var asCode, quiet, silent bool
flag.StringVar(&channel, "channel", "", "Required: Which channel to send messages to")
flag.StringVar(&filename, "params-file", "", "Optional: Override slack.PostMessageParameters with JSON file")
flag.StringVar(&mention, "mention", "", "Optional: Add mention before message body")
flag.BoolVar(&asCode, "as-code", true, "Optional: Send message fenced by three backticks")
flag.BoolVar(&quiet, "quiet", true, "Optional: Suppress error message")
flag.BoolVar(&silent, "silent", false, "Optional: Suppress any output")
flag.Parse()
if silent {
quiet = true
}
if channel == "" {
handleError(errors.New("please set an argument: -channel"), quiet)
}
token := os.Getenv("SLACK_API_TOKEN")
if token == "" {
handleError(errors.New("please set an environment variable: SLACK_API_TOKEN"), quiet)
}
api := slack.New(token)
body, err := ioutil.ReadAll(os.Stdin)
if err != nil {
handleError(err, quiet)
}
text := string(body)
if !silent {
fmt.Print(text)
}
text = strings.TrimSpace(text)
if text == "" {
os.Exit(0)
}
if asCode {
text = fmt.Sprintf("```\n%s\n```", text)
}
if mention != "" {
text = fmt.Sprintf("%s\n%s", mention, text)
}
params := createParams(filename)
_, _, err = api.PostMessage(channel, text, params)
if err != nil {
handleError(err, quiet)
}
}