gocron/modules/notify/slack.go

78 lines
2.3 KiB
Go
Raw Normal View History

2017-04-28 03:54:46 +00:00
package notify
// 发送消息到slack
import (
"fmt"
"github.com/ouqiang/gocron/modules/httpclient"
"github.com/ouqiang/gocron/modules/logger"
"github.com/ouqiang/gocron/modules/utils"
2017-04-30 17:12:07 +00:00
"strings"
"github.com/ouqiang/gocron/models"
"strconv"
"time"
2017-04-28 03:54:46 +00:00
)
type Slack struct {}
func (slack *Slack) Send(msg Message) {
2017-04-30 17:12:07 +00:00
model := new(models.Setting)
slackSetting, err := model.Slack()
if err != nil {
logger.Error("#slack#从数据库获取slack配置失败", err)
return
}
if slackSetting.Url == "" {
logger.Error("#slack#webhook-url为空")
return
2017-04-28 03:54:46 +00:00
}
2017-04-30 17:12:07 +00:00
if len(slackSetting.Channels) == 0 {
logger.Error("#slack#channels配置为空")
2017-04-28 03:54:46 +00:00
return
}
2017-04-30 17:12:07 +00:00
logger.Debugf("%+v", slackSetting)
channels := slack.getActiveSlackChannels(slackSetting, msg)
logger.Debugf("%+v", channels)
for _, channel := range(channels) {
slack.send(msg, slackSetting.Url, channel)
}
}
func (slack *Slack) send(msg Message, slackUrl string, channel string) {
formatBody := slack.format(msg["content"].(string), channel)
2017-04-28 03:54:46 +00:00
timeout := 30
maxTimes := 3
i := 0
for i < maxTimes {
2017-04-30 17:12:07 +00:00
resp := httpclient.PostBody(slackUrl, formatBody, timeout)
2017-04-28 03:54:46 +00:00
if resp.StatusCode == 200 {
break;
}
i += 1
2017-04-30 17:12:07 +00:00
time.Sleep(2 * time.Second)
2017-04-28 03:54:46 +00:00
if i < maxTimes {
2017-04-30 17:12:07 +00:00
logger.Error("slack#发送消息失败#%s#消息内容-%s", resp.Body, msg["content"])
2017-04-28 03:54:46 +00:00
}
}
}
2017-04-30 17:12:07 +00:00
func (slack *Slack) getActiveSlackChannels(slackSetting models.Slack, msg Message) []string {
taskReceiverIds := strings.Split(msg["task_receiver_id"].(string), ",")
channels := []string{}
for _, v := range(slackSetting.Channels) {
if utils.InStringSlice(taskReceiverIds, strconv.Itoa(v.Id)) {
channels = append(channels, v.Name)
}
}
return channels
}
2017-04-28 03:54:46 +00:00
// 格式化消息内容
2017-04-30 17:12:07 +00:00
func (slack *Slack) format(content string, channel string) string {
2017-04-28 03:54:46 +00:00
content = utils.EscapeJson(content)
specialChars := []string{"&", "<", ">"}
replaceChars := []string{"&amp;", "&lt;", "&gt;"}
2017-04-28 06:55:24 +00:00
content = utils.ReplaceStrings(content, specialChars, replaceChars)
2017-04-28 03:54:46 +00:00
2017-04-30 17:12:07 +00:00
return fmt.Sprintf(`{"text":"%s","username":"监控", "channel":"%s"}`, content, channel)
2017-04-28 03:54:46 +00:00
}