Skip to content

Commit 2c9378b

Browse files
authored
fix(slack): limit attachments to 100 (#241)
also removes last attachment if text is empty
1 parent 6dbcb12 commit 2c9378b

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

pkg/services/slack/slack_json.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,24 @@ type APIResponse struct {
7373
func CreateJSONPayload(config *Config, message string) interface{} {
7474

7575
var atts []attachment
76-
for _, line := range strings.Split(message, "\n") {
76+
for i, line := range strings.Split(message, "\n") {
77+
// When 100 attachments have been reached, append the remaining line to the last
78+
// attachment to prevent reaching the slack API limit
79+
if i >= 100 {
80+
atts[len(atts)-1].Text += "\n" + line
81+
continue
82+
}
7783
atts = append(atts, attachment{
7884
Text: line,
7985
Color: config.Color,
8086
})
8187
}
8288

89+
// Remove last attachment if empty
90+
if atts[len(atts)-1].Text == "" {
91+
atts = atts[:len(atts)-1]
92+
}
93+
8394
payload := MessagePayload{
8495
ThreadTS: config.ThreadTS,
8596
Text: config.Title,

pkg/services/slack/slack_test.go

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package slack_test
22

33
import (
44
"errors"
5+
"fmt"
56
"log"
7+
"strings"
68

79
"github.com/containrrr/shoutrrr/internal/testutils"
810
. "github.com/containrrr/shoutrrr/pkg/services/slack"
@@ -163,7 +165,29 @@ var _ = Describe("the slack service", func() {
163165
Expect(payload.IconURL).To(BeEmpty())
164166
})
165167
})
166-
168+
When("when more than 99 lines are being sent", func() {
169+
It("should append the exceeding lines to the last attachment", func() {
170+
config := Config{}
171+
sb := strings.Builder{}
172+
for i := 1; i <= 110; i++ {
173+
sb.WriteString(fmt.Sprintf("Line %d\n", i))
174+
}
175+
payload := CreateJSONPayload(&config, sb.String()).(MessagePayload)
176+
atts := payload.Attachments
177+
178+
fmt.Printf("\nLines: %d, Last: %#v\n", len(atts), atts[len(atts)-1])
179+
180+
Expect(atts).To(HaveLen(100))
181+
Expect(atts[len(atts)-1].Text).To(ContainSubstring("Line 110"))
182+
})
183+
})
184+
When("when the last message line ends with a newline", func() {
185+
It("should not send an empty attachment", func() {
186+
payload := CreateJSONPayload(&Config{}, "One\nTwo\nThree\n").(MessagePayload)
187+
atts := payload.Attachments
188+
Expect(atts[len(atts)-1].Text).NotTo(BeEmpty())
189+
})
190+
})
167191
})
168192

169193
Describe("sending the payload", func() {

0 commit comments

Comments
 (0)