I have a Script that sends a Notification to my Phone using ntfy.
It pings a Device and if the Ping responds with an Error, it sends a Notification to my Phone.
for ip in ap_ips:
try:
ping3.ping(ip)
requests.post(ntfy_adress,
data=("Das Gerät mit der IP-Adresse " + ip + " ist online.").encode(
encoding='utf-8'),
headers={
"Title": ("Unifi AP ist Online!"),
})
except:
requests.post(ntfy_adress,
data=("Das Gerät mit der IP-Adresse " + ip + " ist nicht mehr erreichbar.").encode(encoding='utf-8'),
headers={
"Title": ("Unifi AP ist Offline!"),
"Tags": "warning"
})
The Script is supposed to be running in a infinite Loop.
How do i get the Script to only send a Notification if the Ping Result is diffrent than before?
>Solution :
You have to store between two executions the status. Before your while loop do something like:
status = {}
And then, check that the previous status is not the current one
for ip in ap_ips:
try:
ping3.ping(ip)
if status.get(ip) != "OK":
requests.post(
ntfy_adress,
data=("Das Gerät mit der IP-Adresse " + ip + " ist online.").encode(
encoding="utf-8"
),
headers={
"Title": ("Unifi AP ist Online!"),
},
)
status[ip] = "OK"
except: # You should set explicitly which error type you expect here if ping fails.
if status.get(ip) != "KO":
requests.post(
ntfy_adress,
data=(
"Das Gerät mit der IP-Adresse " + ip + " ist nicht mehr erreichbar."
).encode(encoding="utf-8"),
headers={"Title": ("Unifi AP ist Offline!"), "Tags": "warning"},
)
status[ip] = "KO"