package tools import ( "bytes" "context" "encoding/json" "errors" "fmt" "net/http" "time" ) type ( slackClient struct { address string timeout time.Duration username string iconEmoji string iconURL string channel string } slackmessage struct { c *slackClient Text string `json:"text"` // Markdown string `json:"markdown_text"` Username string `json:"username,omitempty"` IconEmoji string `json:"icon_emoji,omitempty"` IconURL string `json:"icon_url,omitempty"` Channel string `json:"channel,omitempty"` Blocks []*slackmessageblock `json:"blocks"` } slackmessageblock struct { Type string `json:"type"` Text slackmessageblocktext `json:"text"` } slackmessageblocktext struct { Type string `json:"type"` Text string `json:"text"` } ) func Slack(url string) *slackClient { return &slackClient{ address: url, } } func (s *slackClient) Message(text string) *slackmessage { return &slackmessage{ c: s, Text: text, Username: "bot", IconEmoji: ":ghost:", } } // func (s *slackClient) MessageMarkdown(text string) *slackmessage { // return &slackmessage{ // c: s, // Markdown: text, // Username: "bot", // IconEmoji: ":ghost:", // } // } func (m *slackmessage) Block(text string) *slackmessageblock { block := &slackmessageblock{ Type: "section", Text: slackmessageblocktext{ Type: "mrkdwn", Text: text, }, } if m.Blocks == nil { m.Blocks = []*slackmessageblock{} } m.Blocks = append(m.Blocks, block) return block } func (m *slackmessage) Send() (err error) { reqBody, _ := json.Marshal(m) //nolint:errchkjson r, nerr := http.NewRequestWithContext(context.TODO(), http.MethodPost, m.c.address, bytes.NewReader(reqBody)) if nerr != nil { return fmt.Errorf("create request: %w", nerr) } r.Header.Set("Content-Type", "application/json; charset=utf-8") hr := http.DefaultClient resp, derr := hr.Do(r) if derr != nil { return fmt.Errorf("execute request: %w", derr) } defer func() { err = errors.Join(err, resp.Body.Close()) }() if resp.StatusCode != http.StatusOK { return fmt.Errorf("unable to send the message- Code: %v, Status: %v", resp.StatusCode, resp.Status) } return nil }