github.com/kvattikuti/drone@v0.2.1-0.20140603034306-d400229a327a/pkg/plugin/notify/slack.go (about) 1 package notify 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/url" 7 ) 8 9 const ( 10 slackEndpoint = "https://%s.slack.com/services/hooks/incoming-webhook?token=%s" 11 slackStartedMessage = "*Building* %s, commit <%s|%s>, author %s" 12 slackSuccessMessage = "*Success* %s, commit <%s|%s>, author %s" 13 slackFailureMessage = "*Failed* %s, commit <%s|%s>, author %s" 14 ) 15 16 type Slack struct { 17 Team string `yaml:"team,omitempty"` 18 Channel string `yaml:"channel,omitempty"` 19 Username string `yaml:"username,omitempty"` 20 Token string `yaml:"token,omitempty"` 21 Started bool `yaml:"on_started,omitempty"` 22 Success bool `yaml:"on_success,omitempty"` 23 Failure bool `yaml:"on_failure,omitempty"` 24 } 25 26 func (s *Slack) Send(context *Context) error { 27 switch { 28 case context.Commit.Status == "Started" && s.Started: 29 return s.sendStarted(context) 30 case context.Commit.Status == "Success" && s.Success: 31 return s.sendSuccess(context) 32 case context.Commit.Status == "Failure" && s.Failure: 33 return s.sendFailure(context) 34 } 35 36 return nil 37 } 38 39 func getBuildUrl(context *Context) string { 40 branchQuery := url.Values{} 41 if context.Commit.Branch != "" { 42 branchQuery.Set("branch", context.Commit.Branch) 43 } 44 45 return fmt.Sprintf("%s/%s/commit/%s?%s", context.Host, context.Repo.Slug, context.Commit.Hash, branchQuery.Encode()) 46 } 47 48 func getMessage(context *Context, message string) string { 49 url := getBuildUrl(context) 50 return fmt.Sprintf(message, context.Repo.Name, url, context.Commit.HashShort(), context.Commit.Author) 51 } 52 53 func (s *Slack) sendStarted(context *Context) error { 54 return s.send(getMessage(context, slackStartedMessage)) 55 } 56 57 func (s *Slack) sendSuccess(context *Context) error { 58 return s.send(getMessage(context, slackSuccessMessage)) 59 } 60 61 func (s *Slack) sendFailure(context *Context) error { 62 return s.send(getMessage(context, slackFailureMessage)) 63 } 64 65 // helper function to send HTTP requests 66 func (s *Slack) send(msg string) error { 67 // data will get posted in this format 68 data := struct { 69 Channel string `json:"channel"` 70 Username string `json:"username"` 71 Text string `json:"text"` 72 }{s.Channel, s.Username, msg} 73 74 // data json encoded 75 payload, err := json.Marshal(data) 76 if err != nil { 77 return err 78 } 79 80 // send payload 81 url := fmt.Sprintf(slackEndpoint, s.Team, s.Token) 82 go sendJson(url, payload) 83 84 return nil 85 }