Debian Codegraph @

docs/examples.md

raw
1 # Examples
2
3 There are a million ways to use ntfy, but here are some inspirations. I try to collect
4 <a href="https://github.com/binwiederhier/ntfy/tree/main/examples">examples on GitHub</a>, so be sure to check
5 those out, too.
6
7 !!! info
8 Many of these examples were contributed by ntfy users. If you have other examples of how you use ntfy, please
9 [create a pull request](https://github.com/binwiederhier/ntfy/pulls), and I'll happily include it. Also note, that
10 I cannot guarantee that all of these examples are functional. Many of them I have not tried myself.
11
12 ## Cronjobs
13 ntfy is perfect for any kind of cronjobs or just when long processes are done (backups, pipelines, rsync copy commands, ...).
14
15 I started adding notifications pretty much all of my scripts. Typically, I just chain the <tt>curl</tt> call
16 directly to the command I'm running. The following example will either send <i>Laptop backup succeeded</i>
17 or ⚠️ <i>Laptop backup failed</i> directly to my phone:
18
19 ``` bash
20 rsync -a root@laptop /backups/laptop \
21 && zfs snapshot ... \
22 && curl -H prio:low -d "Laptop backup succeeded" ntfy.sh/backups \
23 || curl -H tags:warning -H prio:high -d "Laptop backup failed" ntfy.sh/backups
24 ```
25
26 Here's one for the history books. I desperately want the `github.com/ntfy` organization, but all my tickets with
27 GitHub have been hopeless. In case it ever becomes available, I want to know immediately.
28
29 ```
30 # Check github/ntfy user
31 */6 * * * * if curl -s https://api.github.com/users/ntfy | grep "Not Found"; then curl -d "github.com/ntfy is available" -H "Tags: tada" -H "Prio: high" ntfy.sh/my-alerts; fi
32 ```
33
34 You can also use [`ntfy-run`](https://github.com/quantum5/ntfy-run) to send the output of your cronjob in the
35 notification, so that you know exactly why it failed:
36
37 ```
38 0 0 * * * ntfy-run -n https://ntfy.sh/backups --success-priority low --failure-tags warning ~/backup-computer
39 ```
40
41 ## Low disk space alerts
42 Here's a simple cronjob that I use to alert me when the disk space on the root disk is running low. It's simple, but
43 effective.
44
45 ``` bash
46 #!/bin/bash
47
48 mingigs=10
49 avail=$(df | awk '$6 == "/" && $4 < '$mingigs' * 1024*1024 { print $4/1024/1024 }')
50 topicurl=https://ntfy.sh/mytopic
51
52 if [ -n "$avail" ]; then
53 curl \
54 -d "Only $avail GB available on the root disk. Better clean that up." \
55 -H "Title: Low disk space alert on $(hostname)" \
56 -H "Priority: high" \
57 -H "Tags: warning,cd" \
58 $topicurl
59 fi
60 ```
61
62 ## SSH login alerts
63 Years ago my home server was broken into. That shook me hard, so every time someone logs into any machine that I
64 own, I now message myself. Here's an example of how to use <a href="https://en.wikipedia.org/wiki/Linux_PAM">PAM</a>
65 to notify yourself on SSH login.
66
67 === "/etc/pam.d/sshd"
68 ```
69 # at the end of the file
70 session optional pam_exec.so /usr/bin/ntfy-ssh-login.sh
71 ```
72
73 === "/usr/bin/ntfy-ssh-login.sh"
74 ```bash
75 #!/bin/bash
76 if [ "${PAM_TYPE}" = "open_session" ]; then
77 curl \
78 -H prio:high \
79 -H tags:warning \
80 -d "SSH login: ${PAM_USER} from ${PAM_RHOST}" \
81 ntfy.sh/alerts
82 fi
83 ```
84
85 ## Collect data from multiple machines
86 The other day I was running tasks on 20 servers, and I wanted to collect the interim results
87 as a CSV in one place. Each of the servers was publishing to a topic as the results completed (`publish-result.sh`),
88 and I had one central collector to grab the results as they came in (`collect-results.sh`).
89
90 It looked something like this:
91
92 === "collect-results.sh"
93 ```bash
94 while read result; do
95 [ -n "$result" ] && echo "$result" >> results.csv
96 done < <(stdbuf -i0 -o0 curl -s ntfy.sh/results/raw)
97 ```
98 === "publish-result.sh"
99 ```bash
100 // This script was run on each of the 20 servers. It was doing heavy processing ...
101
102 // Publish script results
103 curl -d "$(hostname),$count,$time" ntfy.sh/results
104 ```
105
106 ## Ansible, Salt and Puppet
107 You can easily integrate ntfy into Ansible, Salt, or Puppet to notify you when runs are done or are highstated.
108 One of my co-workers uses the following Ansible task to let him know when things are done:
109
110 ``` yaml
111 - name: Send ntfy.sh update
112 uri:
113 url: "https://ntfy.sh/{{ ntfy_channel }}"
114 method: POST
115 body: "{{ inventory_hostname }} reseeding complete"
116 ```
117
118 There's also a dedicated Ansible action plugin (one which runs on the Ansible controller) called
119 [ansible-ntfy](https://github.com/jpmens/ansible-ntfy). The following task posts a message
120 to ntfy at its default URL (`attrs` and other attributes are optional):
121
122 ``` yaml
123 - name: "Notify ntfy that we're done"
124 ntfy:
125 msg: "deployment on {{ inventory_hostname }} is complete. 🐄"
126 attrs:
127 tags: [ heavy_check_mark ]
128 priority: 1
129 ```
130
131 ## GitHub Actions
132 You can send a message during a workflow run with curl. Here is an example sending info about the repo, commit and job status.
133 ``` yaml
134 - name: Actions Ntfy
135 run: |
136 curl \
137 -u ${{ secrets.NTFY_CRED }} \
138 -H "Title: Title here" \
139 -H "Content-Type: text/plain" \
140 -d $'Repo: ${{ github.repository }}\nCommit: ${{ github.sha }}\nRef: ${{ github.ref }}\nStatus: ${{ job.status}}' \
141 ${{ secrets.NTFY_URL }}
142 ```
143
144 ## Changedetection.io
145 ntfy is an excellent choice for getting notifications when a website has a change sent to your mobile (or desktop),
146 [changedetection.io](https://changedetection.io) or on GitHub ([dgtlmoon/changedetection.io](https://github.com/dgtlmoon/changedetection.io))
147 uses [apprise](https://github.com/caronc/apprise) library for notification integrations.
148
149 To add any ntfy(s) notification to a website change simply add the [ntfy style URL](https://github.com/caronc/apprise/wiki/Notify_ntfy)
150 to the notification list.
151
152 For example `ntfy://{topic}` or `ntfy://{user}:{password}@{host}:{port}/{topics}`
153
154 In your changedetection.io installation, click `Edit` > `Notifications` on a single website watch (or group) then add
155 the special ntfy Apprise Notification URL to the Notification List.
156
157 ![ntfy alerts on website change](static/img/cdio-setup.jpg)
158
159 ## Watchtower (shoutrrr)
160 You can use [shoutrrr](https://containrrr.dev/shoutrrr/latest/services/ntfy/) to send
161 [Watchtower](https://github.com/containrrr/watchtower/) notifications to your ntfy topic.
162
163 Example docker-compose.yml:
164
165 ``` yaml
166 services:
167 watchtower:
168 image: containrrr/watchtower
169 environment:
170 - WATCHTOWER_NOTIFICATION_SKIP_TITLE=True
171 - WATCHTOWER_NOTIFICATION_URL=ntfy://ntfy.sh/my_watchtower_topic?title=WatchtowerUpdates
172 ```
173
174 The environment variable `WATCHTOWER_NOTIFICATION_SKIP_TITLE` is required to prevent Watchtower from [replacing the `title` query parameter](https://containrrr.dev/watchtower/notifications/#settings). If omitted, the provided notification title will not be used.
175
176 Or, if you only want to send notifications using shoutrrr:
177 ```
178 shoutrrr send -u "ntfy://ntfy.sh/my_watchtower_topic?title=WatchtowerUpdates" -m "testMessage"
179 ```
180
181 Authentication tokens are also supported:
182
183 - (Recommended) Ntfy url format (replace the domain, topic and token with your own):
184 ```
185 ntfy://:TOKEN@DOMAIN/TOPIC
186 ```
187
188 - Generic webhook and authorization header using this url format (replace the domain, topic and token with your own):
189
190 ```
191 generic+https://DOMAIN/TOPIC?@authorization=Bearer+TOKEN`
192 ```
193
194 ## Sonarr, Radarr, Lidarr, Readarr, Prowlarr, SABnzbd
195
196 <!-- Sonarr v4 is in beta as of May 2023, should be updated to remove v3 reference when stable -->
197
198 Radarr, Prowlarr, and Sonarr v4 support ntfy natively under Settings > Connect.
199
200 Sonarr v3, Readarr, and SABnzbd support custom scripts for downloads, warnings, grabs, etc.
201 Some simple bash scripts to achieve this are kindly provided in [nickexyz's ntfy-shellscripts repository](https://github.com/nickexyz/ntfy-shellscripts).
202
203 ## Node-RED
204 You can use the HTTP request node to send messages with [Node-RED](https://nodered.org), some examples:
205
206 <details>
207 <summary>Example: Send a message (click to expand)</summary>
208
209 ``` json
210 [
211 {
212 "id": "c956e688cc74ad8e",
213 "type": "http request",
214 "z": "fabdd7a3.4045a",
215 "name": "ntfy.sh",
216 "method": "POST",
217 "ret": "txt",
218 "paytoqs": "ignore",
219 "url": "https://ntfy.sh/mytopic",
220 "tls": "",
221 "persist": false,
222 "proxy": "",
223 "authType": "",
224 "senderr": false,
225 "credentials":
226 {
227 "user": "",
228 "password": ""
229 },
230 "x": 590,
231 "y": 3160,
232 "wires":
233 [
234 []
235 ]
236 },
237 {
238 "id": "32ee1eade51fae50",
239 "type": "function",
240 "z": "fabdd7a3.4045a",
241 "name": "data",
242 "func": "msg.payload = \"Something happened\";\nmsg.headers = {};\nmsg.headers['tags'] = 'house';\nmsg.headers['X-Title'] = 'Home Assistant';\n\nreturn msg;",
243 "outputs": 1,
244 "noerr": 0,
245 "initialize": "",
246 "finalize": "",
247 "libs": [],
248 "x": 470,
249 "y": 3160,
250 "wires":
251 [
252 [
253 "c956e688cc74ad8e"
254 ]
255 ]
256 },
257 {
258 "id": "b287e59cd2311815",
259 "type": "inject",
260 "z": "fabdd7a3.4045a",
261 "name": "Manual start",
262 "props":
263 [
264 {
265 "p": "payload"
266 },
267 {
268 "p": "topic",
269 "vt": "str"
270 }
271 ],
272 "repeat": "",
273 "crontab": "",
274 "once": false,
275 "onceDelay": "20",
276 "topic": "",
277 "payload": "",
278 "payloadType": "date",
279 "x": 330,
280 "y": 3160,
281 "wires":
282 [
283 [
284 "32ee1eade51fae50"
285 ]
286 ]
287 }
288 ]
289 ```
290
291 </details>
292
293 ![Node red message flow](static/img/nodered-message.png)
294
295 <details>
296 <summary>Example: Send a picture (click to expand)</summary>
297
298 ``` json
299 [
300 {
301 "id": "d135a13eadeb9d6d",
302 "type": "http request",
303 "z": "fabdd7a3.4045a",
304 "name": "Download image",
305 "method": "GET",
306 "ret": "bin",
307 "paytoqs": "ignore",
308 "url": "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png",
309 "tls": "",
310 "persist": false,
311 "proxy": "",
312 "authType": "",
313 "senderr": false,
314 "credentials":
315 {
316 "user": "",
317 "password": ""
318 },
319 "x": 490,
320 "y": 3320,
321 "wires":
322 [
323 [
324 "6e75bc41d2ec4a03"
325 ]
326 ]
327 },
328 {
329 "id": "6e75bc41d2ec4a03",
330 "type": "function",
331 "z": "fabdd7a3.4045a",
332 "name": "data",
333 "func": "msg.payload = msg.payload;\nmsg.headers = {};\nmsg.headers['tags'] = 'house';\nmsg.headers['X-Title'] = 'Home Assistant - Picture';\n\nreturn msg;",
334 "outputs": 1,
335 "noerr": 0,
336 "initialize": "",
337 "finalize": "",
338 "libs": [],
339 "x": 650,
340 "y": 3320,
341 "wires":
342 [
343 [
344 "eb160615b6ceda98"
345 ]
346 ]
347 },
348 {
349 "id": "eb160615b6ceda98",
350 "type": "http request",
351 "z": "fabdd7a3.4045a",
352 "name": "ntfy.sh",
353 "method": "PUT",
354 "ret": "bin",
355 "paytoqs": "ignore",
356 "url": "https://ntfy.sh/mytopic",
357 "tls": "",
358 "persist": false,
359 "proxy": "",
360 "authType": "",
361 "senderr": false,
362 "credentials":
363 {
364 "user": "",
365 "password": ""
366 },
367 "x": 770,
368 "y": 3320,
369 "wires":
370 [
371 []
372 ]
373 },
374 {
375 "id": "5b8dbf15c8a7a3a5",
376 "type": "inject",
377 "z": "fabdd7a3.4045a",
378 "name": "Manual start",
379 "props":
380 [
381 {
382 "p": "payload"
383 },
384 {
385 "p": "topic",
386 "vt": "str"
387 }
388 ],
389 "repeat": "",
390 "crontab": "",
391 "once": false,
392 "onceDelay": "20",
393 "topic": "",
394 "payload": "",
395 "payloadType": "date",
396 "x": 310,
397 "y": 3320,
398 "wires":
399 [
400 [
401 "d135a13eadeb9d6d"
402 ]
403 ]
404 }
405 ]
406 ```
407
408 </details>
409
410 ![Node red picture flow](static/img/nodered-picture.png)
411
412 ## Gatus
413 To use ntfy with [Gatus](https://github.com/TwiN/gatus), you can use the `ntfy` alerting provider like so:
414
415 ```yaml
416 alerting:
417 ntfy:
418 url: "https://ntfy.sh"
419 topic: "YOUR_NTFY_TOPIC"
420 priority: 3
421 ```
422
423 For more information on using ntfy with Gatus, refer to [Configuring ntfy alerts](https://github.com/TwiN/gatus#configuring-ntfy-alerts).
424
425 <details>
426 <summary>Alternative: Using the custom alerting provider</summary>
427
428 ```yaml
429 alerting:
430 custom:
431 url: "https://ntfy.sh"
432 method: "POST"
433 body: |
434 {
435 "topic": "mytopic",
436 "message": "[ENDPOINT_NAME] - [ALERT_DESCRIPTION]",
437 "title": "Gatus",
438 "tags": ["[ALERT_TRIGGERED_OR_RESOLVED]"],
439 "priority": 3
440 }
441 default-alert:
442 enabled: true
443 description: "health check failed"
444 send-on-resolved: true
445 failure-threshold: 3
446 success-threshold: 3
447 placeholders:
448 ALERT_TRIGGERED_OR_RESOLVED:
449 TRIGGERED: "warning"
450 RESOLVED: "white_check_mark"
451 ```
452
453 </details>
454
455
456 ## Jellyseerr/Overseerr webhook
457 Here is an example for [jellyseerr](https://github.com/Fallenbagel/jellyseerr)/[overseerr](https://overseerr.dev/) webhook
458 JSON payload. Remember to change the `https://request.example.com` to your URL as the value of the JSON key click.
459 And if you're not using the request `topic`, make sure to change it in the JSON payload to your topic.
460
461 ``` json
462 {
463 "topic": "requests",
464 "title": "{{event}}",
465 "message": "{{subject}}\n{{message}}\n\nRequested by: {{requestedBy_username}}\n\nStatus: {{media_status}}\nRequest Id: {{request_id}}",
466 "priority": 4,
467 "attach": "{{image}}",
468 "click": "https://requests.example.com/{{media_type}}/{{media_tmdbid}}"
469 }
470 ```
471
472 ## Home Assistant
473 Here is an example for the configuration.yml file to setup a REST notify component.
474 Since Home Assistant is going to POST JSON, you need to specify the root of your ntfy resource.
475
476 ```yaml
477 notify:
478 - name: ntfy
479 platform: rest
480 method: POST_JSON
481 data:
482 topic: YOUR_NTFY_TOPIC
483 title_param_name: title
484 message_param_name: message
485 resource: https://ntfy.sh
486 ```
487
488 If you need to authenticate to your ntfy resource, define the authentication, username and password as below:
489
490 ```yaml
491 notify:
492 - name: ntfy
493 platform: rest
494 method: POST_JSON
495 authentication: basic
496 username: YOUR_USERNAME
497 password: YOUR_PASSWORD
498 data:
499 topic: YOUR_NTFY_TOPIC
500 title_param_name: title
501 message_param_name: message
502 resource: https://ntfy.sh
503 ```
504
505 If you need to add any other [ntfy specific parameters](https://ntfy.sh/docs/publish/#publish-as-json) such as priority, tags, etc., add them to the `data` array in the example yml. For example:
506
507 ```yaml
508 notify:
509 - name: ntfy
510 platform: rest
511 method: POST_JSON
512 data:
513 topic: YOUR_NTFY_TOPIC
514 priority: 4
515 title_param_name: title
516 message_param_name: message
517 resource: https://ntfy.sh
518 ```
519
520 ## Uptime Kuma
521 Go to your [Uptime Kuma](https://github.com/louislam/uptime-kuma) Settings > Notifications, click on **Setup Notification**.
522 Then set your desired **title** (e.g. "Uptime Kuma"), **ntfy topic**, **Server URL** and **priority (1-5)**:
523
524 <div id="uptimekuma-screenshots" class="screenshots">
525 <a href="../static/img/uptimekuma-settings.png"><img src="../static/img/uptimekuma-settings.png"/></a>
526 <a href="../static/img/uptimekuma-setup.png"><img src="../static/img/uptimekuma-setup.png"/></a>
527 </div>
528
529 You can now test the notifications and apply them to monitors:
530
531 <div id="uptimekuma-monitor-screenshots" class="screenshots">
532 <a href="../static/img/uptimekuma-ios-test.jpg"><img src="../static/img/uptimekuma-ios-test.jpg"/></a>
533 <a href="../static/img/uptimekuma-ios-down.jpg"><img src="../static/img/uptimekuma-ios-down.jpg"/></a>
534 <a href="../static/img/uptimekuma-ios-up.jpg"><img src="../static/img/uptimekuma-ios-up.jpg"/></a>
535 </div>
536
537 ## UptimeRobot
538 Go to your [UptimeRobot](https://github.com/uptimerobot) My Settings > Alert Contacts > Add Alert Contact
539 Select **Alert Contact Type** = Webhook. Then set your desired **Friendly Name** (e.g. "ntfy-sh-UP"), **URL to Notify**, **POST value** and select checkbox **Send as JSON (application/json)**. Make sure to send the JSON POST request to ntfy.domain.com without the topic name in the url and include the "topic" name in the JSON body.
540
541 <div id="uptimerobot-monitor-setup" class="screenshots">
542 <a href="../static/img/uptimerobot-setup.jpg"><img src="../static/img/uptimerobot-setup.jpg"/></a>
543 </div>
544
545 ``` json
546 {
547 "topic":"myTopic",
548 "title": "*monitorFriendlyName* *alertTypeFriendlyName*",
549 "message": "*alertDetails*",
550 "tags": ["green_circle"],
551 "priority": 3,
552 "click": https://uptimerobot.com/dashboard#*monitorID*
553 }
554 ```
555 You can create two Alert Contacts each with a different icon and priority, for example:
556
557 ``` json
558 {
559 "topic":"myTopic",
560 "title": "*monitorFriendlyName* *alertTypeFriendlyName*",
561 "message": "*alertDetails*",
562 "tags": ["red_circle"],
563 "priority": 3,
564 "click": https://uptimerobot.com/dashboard#*monitorID*
565 }
566 ```
567 You can now add the created Alerts Contact(s) to the monitor(s) and test the notifications:
568
569 <div id="uptimerobot-monitor-screenshots" class="screenshots">
570 <a href="../static/img/uptimerobot-test.jpg"><img src="../static/img/uptimerobot-test.jpg"/></a>
571 </div>
572
573
574 ## Apprise
575 ntfy is integrated natively into [Apprise](https://github.com/caronc/apprise) (also check out the
576 [Apprise/ntfy wiki page](https://github.com/caronc/apprise/wiki/Notify_ntfy)).
577
578 You can use it like this:
579
580 ```
581 apprise -vv -t "Test Message Title" -b "Test Message Body" \
582 ntfy://mytopic
583 ```
584
585 Or with your own server like this:
586
587 ```
588 apprise -vv -t "Test Message Title" -b "Test Message Body" \
589 ntfy://ntfy.example.com/mytopic
590 ```
591
592
593 ## Rundeck
594 Rundeck by default sends only HTML email which is not processed by ntfy SMTP server. Append following configurations to
595 [rundeck-config.properties](https://docs.rundeck.com/docs/administration/configuration/config-file-reference.html) :
596
597 ```
598 # Template
599 rundeck.mail.template.file=/path/to/template.html
600 rundeck.mail.template.log.formatted=false
601 ```
602
603 Example `template.html`:
604 ```html
605 <div>Execution ${execution.id} was <b>${execution.status}</b></div>
606 <ul>
607 <li><a href="${execution.href}">Execution result</a></li>
608 <li><a href="${job.href}">Job</a></li>
609 <li><a href="${execution.projectHref}">Project: ${execution.project}</a></li>
610 <li><a href="${rundeck.href}">Rundeck</a></li>
611 </ul>
612 ```
613
614 Add notification on Rundeck (attachment type must be: `Attached as file to email`):
615 ![Rundeck](static/img/rundeck.png)
616
617 ## Traccar
618 This will only work on selfhosted [traccar](https://www.traccar.org/) ([Github](https://github.com/traccar/traccar)) instances, as you need to be able to set `sms.http.*` keys, which is not possible through the UI attributes
619
620 The easiest way to integrate traccar with ntfy, is to configure ntfy as the SMS provider for your instance. You then can set your ntfy topic as your account's phone number in traccar. Sending the email notifications to ntfy will not work, as ntfy does not support HTML emails.
621
622 **Info:** Add a phone number to your traccar account not in device, as otherwise it will not try to send SMS.
623
624 **Caution:** JSON publishing is only possible, when POST-ing to the root URL of the ntfy instance. (see [documentation](publish.md#publish-as-json))
625 ```xml
626 <entry key='sms.http.url'>https://ntfy.sh</entry>
627 <entry key='sms.http.template'>
628 {
629 "topic": "{phone}",
630 "message": "{message}"
631 }
632 </entry>
633 ```
634 If [access control](config.md#access-control) is enabled, and the target topic does not support anonymous writes, you'll also have to provide an authorization header, for example in form of a privileged token
635 ```xml
636 <entry key='sms.http.authorization'>Bearer tk_JhbsnoMrgy2FcfHeofv97Pi5uXaZZ</entry>
637 ```
638 or by simply providing traccar with a valid username/password combination.
639 ```xml
640 <entry key='sms.http.user'>phil</entry>
641 <entry key='sms.http.password'>mypass</entry>
642 ```
643
644 ## Flowtriq DDoS detection
645 [Flowtriq](https://flowtriq.com) is a real-time DDoS detection and mitigation platform. Its Linux agent, ftagent,
646 supports webhook alerts that can POST directly to an ntfy topic, so you get push notifications on your phone
647 whenever an attack is detected.
648
649 Configure the webhook URL in your ftagent configuration to point to your ntfy topic:
650
651 ```yaml
652 # /etc/ftagent/ftagent.yml
653 alerts:
654 webhooks:
655 - url: https://ntfy.sh/flowtriq-attacks
656 method: POST
657 ```
658
659 You can also use curl to test the integration manually with a sample attack alert:
660
661 ```bash
662 curl \
663 -H "Title: DDoS Attack Detected" \
664 -H "Priority: urgent" \
665 -H "Tags: rotating_light" \
666 -d "Attack detected on 203.0.113.5: 14.2 Gbps UDP flood from 3,482 sources" \
667 ntfy.sh/flowtriq-attacks
668 ```
669
670 ## Terminal Notifications for Long-Running Commands
671
672 This example provides a simple way to send notifications using [ntfy.sh](https://ntfy.sh) when a terminal command completes. It includes success or failure indicators based on the command's exit status.
673
674 Store your ntfy.sh bearer token securely if access control is enabled:
675
676 ```sh
677 echo "your_bearer_token_here" > ~/.ntfy_token
678 chmod 600 ~/.ntfy_token
679 ```
680
681 Add the following function and alias to your `.bashrc` or `.bash_profile`:
682
683 ```sh
684 # Function for alert notifications using ntfy.sh
685 notify_via_ntfy() {
686 local exit_status=$? # Capture the exit status before doing anything else
687 local token=$(< ~/.ntfy_token) # Securely read the token
688 local status_icon="$([ $exit_status -eq 0 ] && echo magic_wand || echo warning)"
689 local last_command=$(history | tail -n1 | sed -e 's/^[[:space:]]*[0-9]\{1,\}[[:space:]]*//' -e 's/[;&|][[:space:]]*alert$//')
690 # for zsh users, use the same sed pattern but get the history differently.
691 # local last_command=$(history "$HISTCMD" | sed -e 's/^[[:space:]]*[0-9]\{1,\}[[:space:]]*//' -e 's/[;&|][[:space:]]*alert$//')
692
693 curl -s -X POST "https://n.example.dev/alerts" \
694 -H "Authorization: Bearer $token" \
695 -H "Title: Terminal" \
696 -H "X-Priority: 3" \
697 -H "Tags: $status_icon" \
698 -d "Command: $last_command (Exit: $exit_status)"
699
700 echo "Tags: $status_icon"
701 echo "$last_command (Exit: $exit_status)"
702 }
703
704 # Add an "alert" alias for long running commands using ntfy.sh
705 alias alert='notify_via_ntfy'
706 ```
707
708 Now you can run any long-running command and append `alert` to notify when it completes:
709
710 ```sh
711 sleep 10; alert
712 ```
713 ![ntfy notifications on mobile device](static/img/mobile-screenshot-notification.png)
714
715 **Notification Sent** with a success 🪄 (`magic_wand`) or failure ⚠️ (`warning`) tag.
716
717 To test failure notifications:
718
719 ```sh
720 false; alert # Always fails (exit 1)
721 ls --invalid; alert # Invalid option
722 cat nonexistent_file; alert # File not found
723 ```