slack.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package tools
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. )
  11. type (
  12. slackClient struct {
  13. address string
  14. timeout time.Duration
  15. username string
  16. iconEmoji string
  17. iconURL string
  18. channel string
  19. }
  20. slackmessage struct {
  21. c *slackClient
  22. Text string `json:"text"`
  23. // Markdown string `json:"markdown_text"`
  24. Username string `json:"username,omitempty"`
  25. IconEmoji string `json:"icon_emoji,omitempty"`
  26. IconURL string `json:"icon_url,omitempty"`
  27. Channel string `json:"channel,omitempty"`
  28. Blocks []*slackmessageblock `json:"blocks"`
  29. }
  30. slackmessageblock struct {
  31. Type string `json:"type"`
  32. Text slackmessageblocktext `json:"text"`
  33. }
  34. slackmessageblocktext struct {
  35. Type string `json:"type"`
  36. Text string `json:"text"`
  37. }
  38. )
  39. func Slack(url string) *slackClient {
  40. return &slackClient{
  41. address: url,
  42. }
  43. }
  44. func (s *slackClient) Message(text string) *slackmessage {
  45. return &slackmessage{
  46. c: s,
  47. Text: text,
  48. Username: "bot",
  49. IconEmoji: ":ghost:",
  50. }
  51. }
  52. // func (s *slackClient) MessageMarkdown(text string) *slackmessage {
  53. // return &slackmessage{
  54. // c: s,
  55. // Markdown: text,
  56. // Username: "bot",
  57. // IconEmoji: ":ghost:",
  58. // }
  59. // }
  60. func (m *slackmessage) Block(text string) *slackmessageblock {
  61. block := &slackmessageblock{
  62. Type: "section",
  63. Text: slackmessageblocktext{
  64. Type: "mrkdwn",
  65. Text: text,
  66. },
  67. }
  68. if m.Blocks == nil {
  69. m.Blocks = []*slackmessageblock{}
  70. }
  71. m.Blocks = append(m.Blocks, block)
  72. return block
  73. }
  74. func (m *slackmessage) Send() (err error) {
  75. reqBody, _ := json.Marshal(m) //nolint:errchkjson
  76. r, nerr := http.NewRequestWithContext(context.TODO(), http.MethodPost, m.c.address, bytes.NewReader(reqBody))
  77. if nerr != nil {
  78. return fmt.Errorf("create request: %w", nerr)
  79. }
  80. r.Header.Set("Content-Type", "application/json; charset=utf-8")
  81. hr := http.DefaultClient
  82. resp, derr := hr.Do(r)
  83. if derr != nil {
  84. return fmt.Errorf("execute request: %w", derr)
  85. }
  86. defer func() {
  87. err = errors.Join(err, resp.Body.Close())
  88. }()
  89. if resp.StatusCode != http.StatusOK {
  90. return fmt.Errorf("unable to send the message- Code: %v, Status: %v", resp.StatusCode, resp.Status)
  91. }
  92. return nil
  93. }