slack.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. // Slack Webhooks documentation: https://api.slack.com/messaging/webhooks
  4. package slack // import "miniflux.app/v2/internal/integration/slack"
  5. import (
  6. "fmt"
  7. "log/slog"
  8. "net/http"
  9. "miniflux.app/v2/internal/http/client"
  10. "miniflux.app/v2/internal/model"
  11. "miniflux.app/v2/internal/urllib"
  12. )
  13. const slackMsgColor = "#5865F2"
  14. type Client struct {
  15. webhookURL string
  16. }
  17. func NewClient(webhookURL string) *Client {
  18. return &Client{webhookURL: webhookURL}
  19. }
  20. func (c *Client) SendSlackMsg(feed *model.Feed, entries model.Entries) error {
  21. for _, entry := range entries {
  22. slog.Debug("Sending Slack notification",
  23. slog.String("webhookURL", c.webhookURL),
  24. slog.String("title", feed.Title),
  25. slog.String("entry_url", entry.URL),
  26. )
  27. response, err := client.NewRequestBuilder(c.webhookURL).
  28. WithMethod(http.MethodPost).
  29. WithJSON(&slackMessage{
  30. Attachments: []slackAttachments{
  31. {
  32. Title: "RSS feed update from Miniflux",
  33. Color: slackMsgColor,
  34. Fields: []slackFields{
  35. {
  36. Title: "Updated feed",
  37. Value: feed.Title,
  38. },
  39. {
  40. Title: "Article title",
  41. Value: entry.Title,
  42. },
  43. {
  44. Title: "Article link",
  45. Value: entry.URL,
  46. },
  47. {
  48. Title: "Author",
  49. Value: entry.Author,
  50. Short: true,
  51. },
  52. {
  53. Title: "Source website",
  54. Value: urllib.RootURL(feed.SiteURL),
  55. Short: true,
  56. },
  57. },
  58. },
  59. },
  60. }).
  61. Do()
  62. if err != nil {
  63. return fmt.Errorf("slack: %w", err)
  64. }
  65. response.Body.Close()
  66. if response.StatusCode >= 400 {
  67. return fmt.Errorf("slack: unable to send a notification: url=%s status=%d", c.webhookURL, response.StatusCode)
  68. }
  69. }
  70. return nil
  71. }
  72. type slackFields struct {
  73. Title string `json:"title"`
  74. Value string `json:"value"`
  75. Short bool `json:"short,omitempty"`
  76. }
  77. type slackAttachments struct {
  78. Title string `json:"title"`
  79. Color string `json:"color"`
  80. Fields []slackFields `json:"fields"`
  81. }
  82. type slackMessage struct {
  83. Attachments []slackAttachments `json:"attachments"`
  84. }