-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslack.go
155 lines (144 loc) · 3.54 KB
/
slack.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package nopaste
import (
"encoding/json"
"fmt"
"io"
"log"
"math"
"net/http"
"net/url"
"time"
)
const SlackMaxBackOff = 3600
var (
SlackThrottleWindow = 1 * time.Second
SlackInitialBackOff = 30
Epoch = time.Unix(0, 0)
)
type SlackMessage struct {
Channel string `json:"channel"`
Text string `json:"text"`
IconEmoji string `json:"icon_emoji,omitempty"`
IconURL string `json:"icon_url,omitempty"`
Username string `json:"username"`
LinkNames int `json:"link_names,omitempty"`
}
type SlackMessageChan chan SlackMessage
func (ch SlackMessageChan) PostNopaste(np nopasteContent, url string) {
summary := np.Summary
nick := np.Nick
var text string
if summary == "" {
text = fmt.Sprintf("<%s|%s>", url, url)
} else {
text = fmt.Sprintf("%s <%s|show details>", summary, url)
}
msg := SlackMessage{
Channel: np.Channel,
Username: nick,
Text: text,
IconEmoji: np.IconEmoji,
IconURL: np.IconURL,
LinkNames: np.LinkNames,
}
log.Printf("[debug] post to slack: %#v", msg)
select {
case ch <- msg:
default:
log.Println("[warn] Can't send msg to Slack")
}
}
func (ch SlackMessageChan) PostMsgr(req *http.Request) {
username := req.FormValue("username")
if username == "" {
username = "msgr"
}
msg := SlackMessage{
Channel: req.FormValue("channel"),
Text: req.FormValue("msg"),
Username: username,
IconEmoji: req.FormValue("icon_emoji"),
IconURL: req.FormValue("icon_url"),
LinkNames: 0, // default notice as IRC
}
if _notice := req.FormValue("notice"); _notice == "0" {
msg.LinkNames = 1
}
log.Printf("[debug] post to slack: %#v", msg)
select {
case ch <- msg:
default:
log.Println("[warn] Can't send msg to Slack")
}
}
type SlackAgent struct {
WebhookURL string
client *http.Client
}
func (a *SlackAgent) Post(m SlackMessage) error {
payload, _ := json.Marshal(&m)
v := url.Values{}
v.Set("payload", string(payload))
log.Println("[debug] post to slack", a, string(payload))
resp, err := a.client.PostForm(a.WebhookURL, v)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return nil
}
if body, err := io.ReadAll(resp.Body); err == nil {
return fmt.Errorf("failed post to slack:%s", body)
} else {
return err
}
}
func RunSlackAgent(c *Config, ch chan SlackMessage) {
log.Println("[info] runing slack agent")
joined := make(map[string]chan SlackMessage)
agent := &SlackAgent{
WebhookURL: c.Slack.WebhookURL,
client: &http.Client{},
}
for {
select {
case msg := <-ch:
if _, ok := joined[msg.Channel]; !ok {
joined[msg.Channel] = make(chan SlackMessage, MsgBufferLen)
go sendMsgToSlackChannel(agent, joined[msg.Channel])
}
select {
case joined[msg.Channel] <- msg:
default:
log.Println("[warn] Can't send msg to Slack. Channel buffer flooding.")
}
}
}
}
func sendMsgToSlackChannel(agent *SlackAgent, ch chan SlackMessage) {
lastPostedAt := time.Now()
ignoreUntil := Epoch
backoff := SlackInitialBackOff
for {
select {
case msg := <-ch:
if time.Now().Before(ignoreUntil) {
// ignored
continue
}
throttle(lastPostedAt, SlackThrottleWindow)
err := agent.Post(msg)
lastPostedAt = time.Now()
if err != nil {
backoff = int(math.Min(float64(backoff)*2, SlackMaxBackOff))
d, _ := time.ParseDuration(fmt.Sprintf("%ds", backoff))
ignoreUntil = lastPostedAt.Add(d)
log.Println("[warn]", err, msg.Channel, "will be ignored until", ignoreUntil)
} else if !ignoreUntil.Equal(Epoch) {
ignoreUntil = Epoch
backoff = SlackInitialBackOff
}
}
}
}