wxrobot.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package wxrobot
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/SongZihuan/web-watcher/src/config"
  7. "io"
  8. "net/http"
  9. )
  10. const (
  11. msgtypetext = "text"
  12. msgtypemarkdown = "markdown"
  13. )
  14. const atall = "@all"
  15. type WebhookText struct {
  16. Content string `json:"content"`
  17. MentionedList []string `json:"mentioned_list"`
  18. MentionedMobileList []string `json:"mentioned_mobile_list"`
  19. }
  20. type WebhookMarkdown struct {
  21. Content string `json:"content"`
  22. }
  23. type ReqWebhookMsg struct {
  24. MsgType string `json:"msgtype"`
  25. Text *WebhookText `json:"text,omitempty"`
  26. Markdown *WebhookMarkdown `json:"markdown,omitempty"`
  27. }
  28. type RespWebhookMsg struct {
  29. ErrCode int `json:"errcode"`
  30. ErrMsg string `json:"errmsg"`
  31. }
  32. func Send(msg string, atAll bool) error {
  33. if msg == "" {
  34. return nil
  35. }
  36. return send(fmt.Sprintf("【%s 消息提醒】\n%s", config.GetConfig().SystemName, msg), atAll)
  37. }
  38. func send(msg string, atAll bool) error {
  39. if !config.IsReady() {
  40. panic("config is not ready")
  41. }
  42. webhook := config.GetConfig().API.Webhook
  43. if webhook == "" || msg == "" {
  44. return nil
  45. }
  46. if len([]byte(msg)) >= 2048 {
  47. return fmt.Errorf("msg too long")
  48. }
  49. data := ReqWebhookMsg{
  50. MsgType: msgtypetext,
  51. Text: &WebhookText{
  52. Content: msg,
  53. },
  54. }
  55. if atAll {
  56. data.Text.MentionedMobileList = []string{atall}
  57. }
  58. webhookData, err := json.Marshal(data)
  59. if err != nil {
  60. return fmt.Errorf("json marshal error: %s", err.Error())
  61. }
  62. resp, err := http.Post(webhook, "application/json", bytes.NewBuffer(webhookData))
  63. if err != nil {
  64. return fmt.Errorf("http post error: %s", err.Error())
  65. }
  66. defer func() {
  67. _ = resp.Body.Close()
  68. }()
  69. respData, err := io.ReadAll(resp.Body)
  70. if err != nil {
  71. return fmt.Errorf("read response body error: %s", err.Error())
  72. }
  73. var respWebhook RespWebhookMsg
  74. err = json.Unmarshal(respData, &respWebhook)
  75. if err != nil {
  76. return fmt.Errorf("json unmarshal response body error: %s", err.Error())
  77. }
  78. if respWebhook.ErrCode != 0 {
  79. return fmt.Errorf("send message error [code: %d]: %s", respWebhook.ErrCode, respWebhook.ErrMsg)
  80. }
  81. return nil
  82. }