Debian Codegraph @

docs/subscribe/cli.md

raw
1 # Subscribe via ntfy CLI
2 In addition to subscribing via the [web UI](web.md), the [phone app](phone.md), or the [API](api.md), you can subscribe
3 to topics via the ntfy CLI. The CLI is included in the same `ntfy` binary that can be used to [self-host a server](../install.md).
4
5 !!! info
6 The **ntfy CLI is not required to send or receive messages**. You can instead [send messages with curl](../publish.md),
7 and even use it to [subscribe to topics](api.md). It may be a little more convenient to use the ntfy CLI than writing
8 your own script. It all depends on the use case. 😀
9
10 ## Install + configure
11 To install the ntfy CLI, simply **follow the steps outlined on the [install page](../install.md)**. The ntfy server and
12 client are the same binary, so it's all very convenient. After installing, you can (optionally) configure the client
13 by creating `~/.config/ntfy/client.yml` (for the non-root user), `~/Library/Application Support/ntfy/client.yml` (for the macOS non-root user), or `/etc/ntfy/client.yml` (for the root user). You
14 can find a [skeleton config](https://github.com/binwiederhier/ntfy/blob/main/client/client.yml) on GitHub.
15
16 If you just want to use [ntfy.sh](https://ntfy.sh), you don't have to change anything. If you **self-host your own server**,
17 you may want to edit the `default-host` option:
18
19 ``` yaml
20 # Base URL used to expand short topic names in the "ntfy publish" and "ntfy subscribe" commands.
21 # If you self-host a ntfy server, you'll likely want to change this.
22 #
23 default-host: https://ntfy.myhost.com
24 ```
25
26 ## Publish messages
27 You can send messages with the ntfy CLI using the `ntfy publish` command (or any of its aliases `pub`, `send` or
28 `trigger`). There are a lot of examples on the page about [publishing messages](../publish.md), but here are a few
29 quick ones:
30
31 === "Simple send"
32 ```
33 ntfy publish mytopic This is a message
34 ntfy publish mytopic "This is a message"
35 ntfy pub mytopic "This is a message"
36 ```
37
38 === "Send with title, priority, and tags"
39 ```
40 ntfy publish \
41 --title="Thing sold on eBay" \
42 --priority=high \
43 --tags=partying_face \
44 mytopic \
45 "Somebody just bought the thing that you sell"
46 ```
47
48 === "Send at 8:30am"
49 ```
50 ntfy pub --at=8:30am delayed_topic Laterzz
51 ```
52
53 === "Triggering a webhook"
54 ```
55 ntfy trigger mywebhook
56 ntfy pub mywebhook
57 ```
58
59 ### Attaching a local file
60 You can easily upload and attach a local file to a notification:
61
62 ```
63 $ ntfy pub --file README.md mytopic | jq .
64 {
65 "id": "meIlClVLABJQ",
66 "time": 1655825460,
67 "event": "message",
68 "topic": "mytopic",
69 "message": "You received a file: README.md",
70 "attachment": {
71 "name": "README.md",
72 "type": "text/plain; charset=utf-8",
73 "size": 2892,
74 "expires": 1655836260,
75 "url": "https://ntfy.sh/file/meIlClVLABJQ.txt"
76 }
77 }
78 ```
79
80 ### Wait for PID/command
81 If you have a long-running command and want to **publish a notification when the command completes**,
82 you may wrap it with `ntfy publish --wait-cmd` (aliases: `--cmd`, `--done`). Or, if you forgot to wrap it, and the
83 command is already running, you can wait for the process to complete with `ntfy publish --wait-pid` (alias: `--pid`).
84
85 Run a command and wait for it to complete (here: `rsync ...`):
86
87 ```
88 $ ntfy pub --wait-cmd mytopic rsync -av ./ [email protected]:/backups/ | jq .
89 {
90 "id": "Re0rWXZQM8WB",
91 "time": 1655825624,
92 "event": "message",
93 "topic": "mytopic",
94 "message": "Command succeeded after 56.553s: rsync -av ./ [email protected]:/backups/"
95 }
96 ```
97
98 Or, if you already started the long-running process and want to wait for it using its process ID (PID), you can do this:
99
100 === "Using a PID directly"
101 ```
102 $ ntfy pub --wait-pid 8458 mytopic | jq .
103 {
104 "id": "orM6hJKNYkWb",
105 "time": 1655825827,
106 "event": "message",
107 "topic": "mytopic",
108 "message": "Process with PID 8458 exited after 2.003s"
109 }
110 ```
111
112 === "Using a `pidof`"
113 ```
114 $ ntfy pub --wait-pid $(pidof rsync) mytopic | jq .
115 {
116 "id": "orM6hJKNYkWb",
117 "time": 1655825827,
118 "event": "message",
119 "topic": "mytopic",
120 "message": "Process with PID 8458 exited after 2.003s"
121 }
122 ```
123
124 ## Subscribe to topics
125 You can subscribe to topics using `ntfy subscribe`. Depending on how it is called, this command
126 will either print or execute a command for every arriving message. There are a few different ways
127 in which the command can be run:
128
129 ### Stream messages as JSON
130 ```
131 ntfy subscribe TOPIC
132 ```
133 If you run the command like this, it prints the JSON representation of every incoming message. This is useful
134 when you have a command that wants to stream-read incoming JSON messages. Unless `--poll` is passed, this command
135 stays open forever.
136
137 ```
138 $ ntfy sub mytopic
139 {"id":"nZ8PjH5oox","time":1639971913,"event":"message","topic":"mytopic","message":"hi there"}
140 {"id":"sekSLWTujn","time":1639972063,"event":"message","topic":"mytopic",priority:5,"message":"Oh no!"}
141 ...
142 ```
143
144 <figure>
145 <video controls muted autoplay loop width="650" src="../../static/img/cli-subscribe-video-1.mp4"></video>
146 <figcaption>Subscribe in JSON mode</figcaption>
147 </figure>
148
149 ### Run command for every message
150 ```
151 ntfy subscribe TOPIC COMMAND
152 ```
153 If you run it like this, a COMMAND is executed for every incoming messages. Scroll down to see a list of available
154 environment variables. Here are a few examples:
155
156 ```
157 ntfy sub mytopic 'notify-send "$m"'
158 ntfy sub topic1 /my/script.sh
159 ntfy sub topic1 'echo "Message $m was received. Its title was $t and it had priority $p"'
160 ```
161
162 <figure>
163 <video controls muted autoplay loop width="650" src="../../static/img/cli-subscribe-video-2.webm"></video>
164 <figcaption>Execute command on incoming messages</figcaption>
165 </figure>
166
167 The message fields are passed to the command as environment variables and can be used in scripts. Note that since
168 these are environment variables, you typically don't have to worry about quoting too much, as long as you enclose them
169 in double-quotes, you should be fine:
170
171 | Variable | Aliases | Description |
172 |------------------|----------------------------|----------------------------------------|
173 | `$NTFY_ID` | `$id` | Unique message ID |
174 | `$NTFY_TIME` | `$time` | Unix timestamp of the message delivery |
175 | `$NTFY_TOPIC` | `$topic` | Topic name |
176 | `$NTFY_MESSAGE` | `$message`, `$m` | Message body |
177 | `$NTFY_TITLE` | `$title`, `$t` | Message title |
178 | `$NTFY_PRIORITY` | `$priority`, `$prio`, `$p` | Message priority (1=min, 5=max) |
179 | `$NTFY_TAGS` | `$tags`, `$tag`, `$ta` | Message tags (comma separated list) |
180 | `$NTFY_RAW` | `$raw` | Raw JSON message |
181
182 ### Subscribe to multiple topics
183 ```
184 ntfy subscribe --from-config
185 ```
186 To subscribe to multiple topics at once, and run different commands for each one, you can use `ntfy subscribe --from-config`,
187 which will read the `subscribe` config from the config file. Please also check out the [ntfy-client systemd service](#using-the-systemd-service).
188
189 Here's an example config file that subscribes to three different topics, executing a different command for each of them:
190
191 === "~/.config/ntfy/client.yml (Linux)"
192 ```yaml
193 default-host: https://ntfy.sh
194 default-user: phill
195 default-password: mypass
196
197 subscribe:
198 - topic: echo-this
199 command: 'echo "Message received: $message"'
200 - topic: alerts
201 command: notify-send -i /usr/share/ntfy/logo.png "Important" "$m"
202 if:
203 priority: high,urgent
204 - topic: calc
205 command: 'gnome-calculator 2>/dev/null &'
206 - topic: print-temp
207 command: |
208 echo "You can easily run inline scripts, too."
209 temp="$(sensors | awk '/Pack/ { print substr($4,2,2) }')"
210 if [ $temp -gt 80 ]; then
211 echo "Warning: CPU temperature is $temp. Too high."
212 else
213 echo "CPU temperature is $temp. That's alright."
214 fi
215 ```
216
217 === "~/Library/Application Support/ntfy/client.yml (macOS)"
218 ```yaml
219 default-host: https://ntfy.sh
220 default-user: phill
221 default-password: mypass
222
223 subscribe:
224 - topic: echo-this
225 command: 'echo "Message received: $message"'
226 - topic: alerts
227 command: osascript -e "display notification \"$message\""
228 if:
229 priority: high,urgent
230 - topic: calc
231 command: open -a Calculator
232 ```
233
234 === "%AppData%\ntfy\client.yml (Windows)"
235 ```yaml
236 default-host: https://ntfy.sh
237 default-user: phill
238 default-password: mypass
239
240 subscribe:
241 - topic: echo-this
242 command: 'echo Message received: %message%'
243 - topic: alerts
244 command: |
245 notifu /m "%NTFY_MESSAGE%"
246 exit 0
247 if:
248 priority: high,urgent
249 - topic: calc
250 command: calc
251 ```
252
253 In this example, when `ntfy subscribe --from-config` is executed:
254
255 * Messages to `echo-this` simply echos to standard out
256 * Messages to `alerts` display as desktop notification for high priority messages using [notify-send](https://manpages.ubuntu.com/manpages/focal/man1/notify-send.1.html) (Linux),
257 [notifu](https://www.paralint.com/projects/notifu/) (Windows) or `osascript` (macOS)
258 * Messages to `calc` open the calculator 😀 (*because, why not*)
259 * Messages to `print-temp` execute an inline script and print the CPU temperature (Linux version only)
260
261 I hope this shows how powerful this command is. Here's a short video that demonstrates the above example:
262
263 <figure>
264 <video controls muted autoplay loop width="650" src="../../static/img/cli-subscribe-video-3.webm"></video>
265 <figcaption>Execute all the things</figcaption>
266 </figure>
267
268 If most (or all) of your subscriptions use the same credentials, you can set defaults in `client.yml`. Use `default-user` and `default-password` or `default-token` (but not both).
269 You can also specify a `default-command` that will run when a message is received. If a subscription does not include credentials to use or does not have a command, the defaults
270 will be used, otherwise, the subscription settings will override the defaults.
271
272 !!! warning
273 Because the `default-user`, `default-password`, and `default-token` will be sent for each topic that does not have its own username/password (even if the topic does not
274 require authentication), be sure that the servers/topics you subscribe to use HTTPS to prevent leaking the username and password.
275
276 ### Using the systemd service
277 You can use the `ntfy-client` systemd services to subscribe to multiple topics just like in the example above.
278
279 You have the option of either enabling `ntfy-client` as a **system service** (see [here](https://github.com/binwiederhier/ntfy/blob/main/client/ntfy-client.service))
280 or **user service** (see [here](https://github.com/binwiederhier/ntfy/blob/main/client/user/ntfy-client.service)). Neither system service nor user service are enabled or started by default, so you have to do that yourself.
281
282 **System service:** The `ntfy-client` systemd system service runs as the `ntfy` user. When enabled, it is started at system boot. To configure it as a system
283 service, edit `/etc/ntfy/client.yml` and then enable/start the service (as root), like so:
284
285 ```
286 sudo systemctl enable ntfy-client
287 sudo systemctl restart ntfy-client
288 ```
289
290 The system service runs as user `ntfy`, meaning that typical Linux permission restrictions apply. It also means that the system service cannot run commands in your X session as the primary machine user (unlike the user service).
291
292 **User service:** The `ntfy-client` user service is run when the user logs into their desktop environment. To enable/start it, edit `~/.config/ntfy/client.yml` and
293 run the following commands (without sudo!):
294
295 ```
296 systemctl --user enable ntfy-client
297 systemctl --user restart ntfy-client
298 ```
299
300 Unlike the system service, the user service can interact with the user's desktop environment, and run commands like `notify-send` to display desktop notifications.
301 It can also run commands that require access to the user's home directory, such as `gnome-calculator`.
302
303 ### Authentication
304 Depending on whether the server is configured to support [access control](../config.md#access-control), some topics
305 may be read/write protected so that only users with the correct credentials can subscribe or publish to them.
306 To publish/subscribe to protected topics, you can use [Basic Auth](https://en.wikipedia.org/wiki/Basic_access_authentication)
307 with a valid username/password. For your self-hosted server, **be sure to use HTTPS to avoid eavesdropping** and exposing
308 your password.
309
310 You can either add your username and password to the configuration file:
311 === "~/.config/ntfy/client.yml"
312 ```yaml
313 - topic: secret
314 command: 'notify-send "$m"'
315 user: phill
316 password: mypass
317 ```
318
319 Or with the `ntfy subscribe` command:
320 ```
321 ntfy subscribe \
322 -u phil:mypass \
323 ntfy.example.com/mysecrets
324 ```