Skip to content

Instantly share code, notes, and snippets.

@koenbollen
Last active August 29, 2015 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koenbollen/bd7f47a94d25cfecf0c4 to your computer and use it in GitHub Desktop.
Save koenbollen/bd7f47a94d25cfecf0c4 to your computer and use it in GitHub Desktop.
Alerts for NS issues by keyword.
#!/usr/bin/env python3
# Koen Bollen, 2015
import sys
import urllib.request
import xml.etree.ElementTree
# Train stations you are interested in:
keywords = ("utrecht", "bijlmer", "amstel")
# If one of those keywords is found in the
# rss feed the status will be set to yellow
# and when two or more are found the status
# will be set to red.
# Leave like this (unless changed at NS):
rss = "http://www.ns.nl/storingen/index.rss"
def fetch_xml(url):
try:
h = urllib.request.urlopen(url)
return xml.etree.ElementTree.fromstring(h.read())
finally:
h.close()
root = fetch_xml(rss)
found = set()
topics = set()
fields = ('title', 'description')
for item in root.iter('item'):
texts = map(lambda f: item.find(f).text.strip(), fields)
text = ' '.join(texts).lower()
for key in keywords:
if key in text:
found.add( key )
topics.add( item.find('title').text.strip() )
status = 'green'
no_found = len(found)
if no_found == 1:
status = 'yellow'
elif no_found > 1:
status = 'red'
if '-v' in sys.argv:
print(status +':', ', '.join(topics))
# send your alert here (ex. using http://pushover.net)
@koenbollen
Copy link
Author

This is my addition to send a notification using pushover:

if '-n' in sys.argv:
  sys.exit(0)

if status != 'green':
  usr_key = "..snip..snip.."
  app_key = "..snip..snip.."
  msg_url = "https://api.pushover.net/1/messages.json"

  data = urllib.parse.urlencode({
    'token': app_key,
    'user': usr_key,
    'priority': 1,
    'url': 'http://www.ns.nl/storingen/',
    'url_title': "NS.nl",
    'title': "NS status: {}".format(status),
    'message': "status {} at: {}".format(status, ', '.join(topics))
  }).encode('utf-8')
  req = urllib.request.Request(msg_url)
  req.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
  f = urllib.request.urlopen(req, data)
  f.close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment