wecom.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package notification
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "github.com/0xJacky/Nginx-UI/model"
  9. "github.com/uozi-tech/cosy/map2struct"
  10. )
  11. // @external_notifier(WeCom)
  12. type WeCom struct {
  13. WebhookURL string `json:"webhook_url" title:"Webhook URL"`
  14. }
  15. type wecomMessage struct {
  16. MsgType string `json:"msgtype"`
  17. Text struct {
  18. Content string `json:"content"`
  19. } `json:"text"`
  20. }
  21. func init() {
  22. RegisterExternalNotifier("wecom", func(ctx context.Context, n *model.ExternalNotify, msg *ExternalMessage) error {
  23. wecomConfig := &WeCom{}
  24. err := map2struct.WeakDecode(n.Config, wecomConfig)
  25. if err != nil {
  26. return err
  27. }
  28. if wecomConfig.WebhookURL == "" {
  29. return ErrInvalidNotifierConfig
  30. }
  31. // Create message payload
  32. message := wecomMessage{
  33. MsgType: "text",
  34. }
  35. title := msg.GetTitle(n.Language)
  36. content := msg.GetContent(n.Language)
  37. // Combine title and content
  38. fullMessage := title
  39. if content != "" {
  40. fullMessage = fmt.Sprintf("%s\n\n%s", title, content)
  41. }
  42. message.Text.Content = fullMessage
  43. // Marshal to JSON
  44. payload, err := json.Marshal(message)
  45. if err != nil {
  46. return err
  47. }
  48. // Send HTTP POST request
  49. req, err := http.NewRequestWithContext(ctx, "POST", wecomConfig.WebhookURL, bytes.NewBuffer(payload))
  50. if err != nil {
  51. return err
  52. }
  53. req.Header.Set("Content-Type", "application/json")
  54. client := &http.Client{}
  55. resp, err := client.Do(req)
  56. if err != nil {
  57. return err
  58. }
  59. defer resp.Body.Close()
  60. if resp.StatusCode != http.StatusOK {
  61. return fmt.Errorf("weCom webhook returned status code: %d", resp.StatusCode)
  62. }
  63. return nil
  64. })
  65. }