Power Outage Data in AlertMedia

To get power outage alerts into AlertMedia, run a Python poller every 15 minutes that sends your sites' coordinates to the PowerOutage.us v2 REST API and, when a utility reports an outage covering a site, sends an AlertMedia notification to the group of employees at that site. The poller notifies once when a site loses power and once when the outage is no longer reported. AlertMedia's API reference is only visible to signed-in customers, so the poller fills in a request body you copy from it, rather than guessing AlertMedia's field names.

What you'll have

  • A notification to the employees at a store, branch or plant as soon as a utility reports an outage covering it, naming the utility, customers out, cause and estimated restoration.
  • One AlertMedia notification when a site loses power and one when the outage clears, rather than a repeat on every 15-minute run.
  • Recipients chosen per site by AlertMedia group, with the channels and templates your AlertMedia admins already use.
  • Up to 100 sites checked per request, with nothing sent when a check fails.

What you need

An API key (request one with the form below) and these endpoints. Full details are in the API reference.

EndpointMethodUsed forPackage
/geojson/at-pointPOSTChecks up to 100 site coordinates per request and returns, in request order, the active outages covering each one and the utilities serving it.Standard + Locations

Step 1: Check what you need

/geojson/at-point is in the Standard + Locations package, and the poller depends on it. In AlertMedia you need an Admin or Owner to create the API integration, a group for each site's employees, and access to your account's API reference at docs.alertmedia.com, which asks you to sign in. The poller runs on any host with Python 3.8 or later and outbound HTTPS to poweroutage.us and your AlertMedia API host.

Step 2: Create an API integration

In the AlertMedia dashboard, go to Settings > Company > API and select Add New next to API Integrations. Name it, for example PowerOutage.us, link it to an admin, select Generate Keys and save. Then select the Show Token icon and copy the API Admin Token; the same page shows your account's API host under Connection Information. The poller sends the Authorization header value you give it, so check the Connect to API page of the API reference for the scheme that goes in front of the token. Third-party integrations send Bearer followed by the API Admin Token, but your reference is the source to follow. The token can send notifications to your whole company, so keep it in the poller's environment file only.

Step 3: Copy the create-notification request into a template

Open Create a notification in the API reference. Set ALERTMEDIA_NOTIFICATION_URL to its URL on your API host, and save its example request body as /opt/poweroutage/alertmedia-notification.json. Edit that file so the notification goes to one group and uses the channels you want, then put the three tokens below where the subject, the message text and the group go. The poller replaces each token with a JSON value, quotes included, so write {{subject}}, not "{{subject}}"; a token can appear more than once, for example in an SMS message and an email message. Every run checks that the filled template is valid JSON before sending it.

text
Token          replaced with (as a JSON value, so leave it unquoted)
{{subject}}    "Power outage at <site name>", then
               "Power outage no longer reported at <site name>"
{{message}}    "The utility reports a power outage covering <site name>. <utility name>:
               <customersOut> customers out, cause: <cause>, estimated restoration (UTC):
               <estimatedRestorationAt>."  One sentence per outage covering the site
{{group}}      the site's group value from the sites file, such as 4812 or [4812, 4815]

Step 4: List your sites

Give each site a unique id, the name employees will read, coordinates in decimal degrees, and group: the AlertMedia group to notify, in the form your template expects at {{group}}, a single id or a list of ids. Look up group ids with the list-groups request in the API reference. The poller checks the sites in batches of 100, the endpoint maximum.

json
[
  {"id": "store-101", "name": "Store 101, Atlanta", "lat": 33.749, "lon": -84.388, "group": 4812},
  {"id": "store-214", "name": "Store 214, Savannah", "lat": 32.0809, "lon": -81.0912, "group": 4815}
]

Step 5: Write the poller

Save this as /opt/poweroutage/poweroutage_alertmedia.py. It uses only the Python standard library. It checks every site first and waits the Retry-After seconds after a 429, three tries at most, so a failed check stops the run before anything is sent. For each site inside one or more outages that it hasn't notified yet, it fills the template and sends one notification that lists every outage covering the site, each identified by utilityId and outageId. When no outage covers a notified site any more, it sends a second notification and forgets the site. The state file records which sites have been notified, only after AlertMedia accepts the request, and is saved even if the run fails partway. If AlertMedia refuses a request, its answer goes to stderr and the site is tried again on the next run.

python
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

os.umask(0o077)  # the state file is readable by this account only
API_KEY = os.environ['POWEROUTAGE_API_KEY']
# The create-notification URL and the Authorization header value, exactly as AlertMedia's
# API reference gives them for your account.
NOTIFICATION_URL = os.environ['ALERTMEDIA_NOTIFICATION_URL']
AUTHORIZATION = os.environ['ALERTMEDIA_AUTHORIZATION']
TEMPLATE = Path(os.environ['ALERTMEDIA_TEMPLATE']).read_text()  # request body with {{tokens}}
SITES = json.loads(Path(os.environ['SITES_FILE']).read_text())
STATE_FILE = Path(os.environ['STATE_FILE'])  # sites already notified, kept between runs


def outages_at(points):
    """Up to 100 points per call; waits out a 429 for as long as Retry-After says."""
    request = urllib.request.Request(
        'https://poweroutage.us/api/v2/geojson/at-point',
        data=json.dumps({'points': points}).encode(),
        headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'},
    )
    for attempt in range(3):
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)['data']['points']
        except urllib.error.HTTPError as err:
            if err.code != 429 or attempt == 2:
                raise
            time.sleep(int(err.headers.get('Retry-After', '10')))


def notify(site, subject, message):
    """Send one notification built from the template. False: try again next run."""
    body = (
        TEMPLATE.replace('{{subject}}', json.dumps(subject))
        .replace('{{message}}', json.dumps(message))
        .replace('{{group}}', json.dumps(site['group']))
    )
    json.loads(body)  # stops here if the filled template is not valid JSON
    request = urllib.request.Request(
        NOTIFICATION_URL,
        data=body.encode(),
        headers={'Authorization': AUTHORIZATION, 'Content-Type': 'application/json'},
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            response.read()
            print(f'AlertMedia accepted: {subject}')
            return True
    except urllib.error.HTTPError as err:
        print(f"AlertMedia answered {err.code} for {site['id']}: {err.read()[:300]!r}", file=sys.stderr)
        return False


# Outages covering each site, keyed poweroutage:<utilityId>:<outageId>.
# A failed request stops the run here, before any notification is sent.
current = {}
for i in range(0, len(SITES), 100):
    batch = SITES[i : i + 100]
    points = outages_at([{'lat': s['lat'], 'lon': s['lon']} for s in batch])
    for site, point in zip(batch, points):  # same order as the request
        names = {u['utilityId']: u['name'] for u in point['utilities']}
        for outage in point['outages']:
            utility = names.get(outage['utilityId']) or f"Utility {outage['utilityId']}"
            key = f"poweroutage:{outage['utilityId']}:{outage['outageId']}"
            current.setdefault(site['id'], {})[key] = (outage, utility)

by_id = {site['id']: site for site in SITES}
notified = json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}
try:
    for site_id, outages in current.items():
        if site_id in notified:  # still in an outage: no second message
            notified[site_id] = sorted(outages)
            continue
        site = by_id[site_id]
        lines = []
        for outage, utility in outages.values():
            out = 'an unreported number of' if outage['customersOut'] is None else f"{outage['customersOut']:,}"
            lines.append(
                f"{utility}: {out} customers out, cause: {outage['cause'] or 'not reported'}, "
                f"estimated restoration (UTC): {outage['estimatedRestorationAt'] or 'not given'}."
            )
        message = f"The utility reports a power outage covering {site['name']}. " + ' '.join(lines)
        if notify(site, f"Power outage at {site['name']}", message):
            notified[site_id] = sorted(outages)
    for site_id in [s for s in notified if s not in current]:
        site = by_id.get(site_id)
        if site is None:  # removed from the sites file
            del notified[site_id]
        elif notify(site, f"Power outage no longer reported at {site['name']}",
                    f"The utility no longer reports an outage covering {site['name']}."):
            del notified[site_id]
finally:
    STATE_FILE.write_text(json.dumps(notified, indent=2))
print(f'{len(current)} site(s) in an outage; {len(notified)} notified')

Step 6: Run it every 15 minutes

Put the API key, the AlertMedia URL and the Authorization value in an environment file that only the job's account can read, with every value in single quotes: the shell reads the file, so the space in the Authorization value, or an unquoted &, ; or backtick, breaks the run, and an unquoted $, backslash or double quote changes the value AlertMedia receives. Run the poller from that account's crontab. cron mails anything the poller writes to stderr, such as a refused request or a failed check, to MAILTO. Every 15 minutes is enough for most sites. The data updates every minute, so for the latest answers run it every 1 or 2 minutes (* * * * * or */2 * * * *). On its first run the poller sends a notification for every site an outage already covers, so aim the sites file at a test group in AlertMedia before going live.

text
# /opt/poweroutage/alertmedia.env: owned by the account that runs the job, chmod 600.
# Put every value in single quotes, as below; write a single quote inside a value as '\''.
POWEROUTAGE_API_KEY='...'
ALERTMEDIA_NOTIFICATION_URL='...'
ALERTMEDIA_AUTHORIZATION='Bearer ...'
ALERTMEDIA_TEMPLATE='/opt/poweroutage/alertmedia-notification.json'
SITES_FILE='/opt/poweroutage/alertmedia-sites.json'
STATE_FILE='/opt/poweroutage/alertmedia-notified.json'

# crontab -e, as that account. Errors go to MAILTO, the run summary to the log.
# flock -n skips a run while the previous one still holds the lock.
MAILTO=ops-alerts@example.com
*/15 * * * * set -a && . /opt/poweroutage/alertmedia.env && flock -n /opt/poweroutage/alertmedia.lock /usr/bin/python3 /opt/poweroutage/poweroutage_alertmedia.py >> /opt/poweroutage/poweroutage_alertmedia.log

Tips for AlertMedia

  • Test the template before the first scheduled run: point one site at a group that holds only your own user, and run the poller by hand to see the message on each channel.
  • Keep the subject and message short if your template sends SMS: the message grows by one sentence for each outage covering the site, and long site names repeat in both.
  • Some utilities publish outage counts by area but not where their outages are; the check marks them providesGeospatialData: false. A site served only by such utilities never triggers a notification, so list those sites for your AlertMedia admins, who may prefer to keep alerting those employees by hand.
  • Treat alertmedia-notified.json as part of the setup and keep it when you move the poller to another host. A fresh state file makes the next run notify the employees at every site that is still dark a second time.
  • Use a PowerOutage.us key that only this poller uses, restricted to your sites' states, and a separate AlertMedia API integration for it, so revoking either one stops only this job.

Used by

Related integrations

FAQ

Here are some commonly asked questions

Request API access

Tell us what you're building and we'll set you up with a trial key.