ntfy: Send notifications through libnotify to Linux desktop
I've recently started using ntfy to send notifications to my phone from some scripts I'm running on my home NAS. This works great, but when I'm on my PC, I'd rather get notifications there instead of on the phone. There doesn't seem to be a desktop app for ntfy, but luckily the API is extremely simple. I've also recently started picking up Python, so I decided to whip together a simple ntfy notification delivery system for the Linux desktop. To use this, you need notify-send
(provided by the libnotify
package), and python3
.
ntfy-listener.py
:
from sys import argv
import requests
import json
import subprocess
# Sends desktop notifications to a subscribed ntfy topic through libnotify/notify-send
# Usage: python3 ntfy-listener.py topic-name
if len(argv) > 1:
try:
resp = requests.get(f"https://ntfy.sh/{argv[1]}/json", stream=True)
for line in resp.iter_lines():
if line:
ntfyData = json.loads(line)
if ntfyData["event"] == "message":
ntfyTitle = "ntfy"
if "title" in ntfyData:
ntfyTitle = ntfyData["title"]
subprocess.run(["notify-send", "-u", "normal", ntfyTitle, ntfyData["message"]])
except KeyboardInterrupt:
exit()
except Exception as e:
print(e)
Launch the script with python3 ntfy-listener.py ntfy-topic-name
, where ntfy-topic-name
is the ntfy topic you'd like to subscribe to, and any incoming notifications will be delivered though your DE's notification system! I've additionally added it to KDE's autostart, so it loads in the background when I log in:
~/.config/autostart/ntfy-listener.desktop
:
[Desktop Entry]
Exec=python3 /opt/scripts/python/ntfy-listener.py topic-name
Name=ntfy-listener
StartupNotify=true
Terminal=false
Type=Application