Debian Codegraph @

docs/usage/go-package/index.md

raw
1 # Using the Shoutrrr Package
2
3 ## Overview
4
5 The Shoutrrr Go package (`github.com/nicholas-fedor/shoutrrr`) enables sending notifications to various services (e.g., `discord`, `slack`, `telegram`, `smtp`, etc.) using service URLs. It provides two primary methods: a direct `Send` function for simple use cases and a `Sender` struct for advanced scenarios with multiple URLs, message queuing, and parameter customization.
6
7 ### Minimum Supported Go Version
8
9 Projects importing Shoutrrr are expected to follow the latest Go minor and/or patch semantic versions; ergo, Shoutrrr follows the latest minor Go version, i.e. 1.27. (Go refers to minor semantic version releases as major releases.)
10
11 Go release information can be reviewed here: <https://go.dev/doc/devel/release>
12
13 ## Usage
14
15 ```go title="Go Import Statement"
16 import "github.com/nicholas-fedor/shoutrrr"
17 ```
18
19 ### Direct Send
20
21 Sends a notification to a single service URL.
22
23 - **Function**: `shoutrrr.Send(url string, message string) error`
24 - **Behavior**: Initializes a service from the provided URL, sends the message, and returns any error.
25
26 !!! Example
27 ```go title="Send to a Single Slack URL"
28 url := "slack://token-a/token-b/token-c"
29 err := shoutrrr.Send(url, "Hello, Slack!")
30 if err != nil {
31 fmt.Println("Error:", err)
32 }
33 ```
34
35 ### Sender
36
37 Creates a `Sender` (`*ServiceRouter`) to manage multiple service URLs, support message queuing, and allow parameter customization.
38
39 - **Function**: `shoutrrr.CreateSender(urls ...string) (*ServiceRouter, error)`
40 - **With options**: `shoutrrr.NewSenderWithOptions` / `CreateSenderWithOptions` accept `types.SenderOptions`. `HTTPClient` is injected into HTTP services. `DialContext` is injected into TCP services that implement `types.DialContextSetter`. `shoutrrr.Send` cannot take these options.
41 - **Methods**:
42 - `Send(message string, params *types.Params) []error`: Sends a message to all configured services.
43 - `SendItems(items []types.MessageItem, params types.Params) []error`: Sends structured message items to services that support rich formatting.
44 - `SendAsync(message string, params *types.Params) chan error`: Sends a message asynchronously and returns a channel of errors.
45 - `Enqueue(message string, v ...interface{})`: Queues a formatted message for later sending.
46 - `Flush(params *types.Params)`: Sends all queued messages and resets the queue.
47 - **Behavior**: Deduplicates URLs, initializes services, and sends asynchronously.
48
49 !!! Example
50 ```go title="Create Sender with Multiple URLs"
51 urls := []string{
52 "slack://token-a/token-b/token-c",
53 "telegram://110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw@telegram?channels=@mychannel",
54 }
55 sender, err := shoutrrr.CreateSender(urls...)
56 if err != nil {
57 log.Fatal(err)
58 }
59 params := types.Params{}
60 params.SetTitle("Test Notification")
61 errs := sender.Send("Hello, world!", &params)
62 if len(errs) > 0 {
63 for _, err := range errs {
64 fmt.Println("Error:", err)
65 }
66 }
67 ```
68
69 ### Message Queuing
70
71 Allows queuing messages for deferred sending, useful for aggregating notifications during a process.
72
73 - Queues messages with `Enqueue` and sends them with `Flush`. Queued messages use the `params` provided during `Flush`.
74
75 <!-- markdownlint-disable -->
76 !!! Example
77 ```go title="Queue and Flush Notifications"
78 url := "discord://abc123@123456789"
79 sender, err := shoutrrr.CreateSender(url)
80 if err != nil {
81 log.Fatal(err)
82 }
83 defer sender.Flush(nil)
84
85 sender.Enqueue("Started doing work")
86 if err := doWork(); err != nil {
87 sender.Enqueue("Error: %v", err)
88 return
89 }
90 sender.Enqueue("Work completed successfully!")
91 ```
92 <!-- markdownlint-restore -->
93
94 ### SendItems and RichSender
95
96 Sends structured message items to services that support rich formatting.
97 Services implementing `types.RichSender` receive the full `[]types.MessageItem` slice, preserving level, fields, and file attachments.
98 Services that do not implement `RichSender` fall back to plain text automatically.
99
100 - **Method**: `SendItems(items []types.MessageItem, params types.Params) []error`
101 - **Behavior**: Dispatches to `ContextAttachmentSender` if available, otherwise `RichSender`, otherwise falls back to `Send` with plain text.
102
103 !!! Example
104 ```go title="Send Structured Message Items"
105 items := []types.MessageItem{
106 {Text: "Deployment complete", Level: types.Info},
107 {Text: "Rollback available", Level: types.Warning},
108 }
109 sender, err := shoutrrr.CreateSender("discord://webhook")
110 if err != nil {
111 log.Fatal(err)
112 }
113 errs := sender.SendItems(items, types.Params{})
114 ```
115
116 ### Context Propagation
117
118 Services that implement `types.ContextSender` or `types.ContextAttachmentSender` receive a `context.Context` derived from the router's base context with a per-service timeout.
119 This enables cancellation and deadline propagation without changing the existing `Sender` or `RichSender` contracts.
120
121 ### Per-Target Errors
122
123 `*ServiceRouter.Send`, `*ServiceRouter.SendAsync`, `*ServiceRouter.SendItems`, and `*ServiceRouter.Route` return one error per unique configured target, in the deduplicated target order produced by `CreateSender`. Each error is wrapped in `*types.TargetError`, which carries the service URL/ID and supports `errors.Unwrap`, `errors.Is`, and `errors.As`.
124
125 !!! Example
126 ```go title="Handle Per-Target Errors"
127 errs := sender.Send("deploy complete", nil)
128 for i, err := range errs {
129 if err == nil {
130 continue
131 }
132 var targetErr *types.TargetError
133 if errors.As(err, &targetErr) {
134 log.Printf("failed to send to %s: %v", targetErr.URL, targetErr.Err)
135 }
136 }
137 ```
138
139 ### Message Levels
140
141 Services that support severity or priority can receive a semantic level through the `level` param.
142 Shoutrrr defines five levels: `Unknown`, `Debug`, `Info`, `Warning`, and `Error`.
143 The default is `Info`.
144
145 !!! Example
146 ```go title="Set Message Level"
147 params := types.Params{}
148 params.SetLevel(types.Warning)
149 params.SetTitle("Disk usage high")
150 sender, err := shoutrrr.CreateSender("discord://webhook")
151 if err != nil {
152 log.Fatal(err)
153 }
154 errs := sender.Send("Root partition at 92%", &params)
155 ```
156
157 ### Format Conversion
158
159 Converts message bodies between supported formats.
160
161 ```go title="Convert Message Format"
162 import "github.com/nicholas-fedor/shoutrrr/pkg/format"
163
164 body, err := format.ConvertFormat("Hello **world**", "markdown", "text")
165 ```
166
167 Supported conversions: `text` ↔ `markdown` ↔ `html`.
168
169 ### Service Discovery
170
171 Enumerates or checks available notification services without constructing a router.
172
173 ```go title="Discover Available Services"
174 import "github.com/nicholas-fedor/shoutrrr/pkg/services"
175
176 for _, schema := range services.SupportedSchemas() {
177 fmt.Println(schema)
178 }
179
180 if services.SupportsSchema("discord") {
181 // ...
182 }
183 ```
184
185 ## Examples
186
187 <!-- markdownlint-disable -->
188 ### Send with Parameters and Error Handling
189
190 !!! Example
191 ```go title="Send with Title and Error Handling"
192 url := "discord://abc123@123456789"
193 sender, err := shoutrrr.CreateSender(url)
194 if err != nil {
195 log.Fatal(err)
196 }
197 params := types.Params{}
198 params.SetTitle("Alert")
199 errs := sender.Send("System alert!", &params)
200 if len(errs) > 0 {
201 for _, err := range errs {
202 fmt.Println("Error:", err)
203 }
204 }
205 ```
206
207 ```text title="Expected Output (Success)"
208 (No output on success)
209 ```
210
211 ```text title="Expected Output (Error)"
212 Error: failed to send message: unexpected response status code
213 ```
214
215 ### Send to Multiple Services with Queuing
216
217 !!! Example
218 ```go title="Queue Messages for Multiple Services"
219 urls := []string{
220 "slack://token-a/token-b/token-c",
221 "discord://abc123@123456789",
222 }
223 sender, err := shoutrrr.CreateSender(urls...)
224 if err != nil {
225 log.Fatal(err)
226 }
227 start := time.Now()
228 params := types.Params{}
229 params.SetTitle("Task Summary")
230 defer sender.Flush(&params)
231 sender.Enqueue("Task started")
232 time.Sleep(time.Second)
233 sender.Enqueue("Task finished in %v", time.Now().Sub(start))
234 ```
235
236 ```text title="Expected Output (Success)"
237 (No output on success)
238 ```
239
240 ```text title="Expected Output (Error)"
241 Error: failed to initialize service: invalid URL format
242 ```
243 <!-- markdownlint-restore -->
244
245 ## Notes
246
247 - **Error Handling**: `Send` returns a single error. `Sender.Send`, `SendItems`, and `SendAsync` return one error per service. Check `len(errs) > 0` to handle failures. Each error is wrapped in `*types.TargetError` with the service URL.
248 - **Parameters**: `params` is a `*types.Params` value for `Send`, `SendAsync`, and `Flush`. `SendItems` accepts `types.Params` by value. Use setter methods such as `SetTitle`, `SetMessage`, and `SetLevel` to configure service-specific options. Use `shoutrrr docs` to view supported parameters for each service.
249 - **Timeouts**: The default is 10 seconds per service. A longer service timeout extends that service. A positive `SenderOptions.Timeout` is the exact fixed timeout for every service.
250 - **Deduplication**: Duplicate URLs are automatically removed when creating a `Sender`.