| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- 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
- }
|