Power Outage Data in NinjaOne

To get power outage data into NinjaOne, run a Python poller every 15 minutes that sends your client locations' coordinates to the PowerOutage.us v2 REST API and creates a NinjaOne ticket for the organization and location when a utility outage covers it. When a whole site's devices drop offline, the ticket next to those alerts tells your technicians the utility already reports an outage there. The poller adds a private comment when the cause or restoration estimate changes and resolves the ticket once the outage no longer covers the location. NinjaOne only lets a signed-in technician write tickets, so the poller signs in once through the authorization code flow and keeps the refresh token.

What you'll have

  • A ticket on the right organization and location when a utility outage covers it, naming the utility, cause, customers out and estimated restoration in a private description.
  • One ticket per location and outage, keyed on the site plus utilityId and outageId, however many runs see the outage.
  • Private comments when the cause or restoration estimate changes, and the ticket set to Resolved when power returns.
  • Tickets resolved only after a complete, successful check, so a failed request never resolves one by mistake.

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 client locations per request and returns, in request order, the active outages covering each one and the utilities that serve it.Standard + Locations

Step 1: Check what you need

The poller needs /geojson/at-point, which is in the Standard + Locations package. In NinjaOne you need ticketing turned on, an administrator who can add client apps, and a technician account for the tickets to come from. Make that technician a dedicated account whose role allows ticketing for the organizations you watch and nothing on devices, with no scripts or remote access, because the saved refresh token acts as that technician. The poller runs on any host with Python 3.9 or later and outbound HTTPS to poweroutage.us and the NinjaOne host you sign in to: app.ninjarmm.com, us2.ninjarmm.com, eu.ninjarmm.com, ca.ninjarmm.com or oc.ninjarmm.com.

Step 2: Register a web client app

Go to Administration > Apps > API, open Client App IDs and select Add. Choose the Web application platform, not API Services: an API Services app signs in as itself and can read tickets, but creating and updating them needs a signed-in technician. Give it a name, add a redirect URI such as https://localhost/poweroutage (nothing has to answer there; you only copy the address the browser lands on), tick the Monitoring and Management scopes, and allow the Authorization Code and Refresh Token grant types. Save, then copy the client ID and client secret.

Step 3: Look up organizations, locations and the ticket form

NinjaOne locations have a name and an address but no coordinates, so the poller reads them from a CSV. These Public API calls give you the IDs for it, plus the ticket technician's uid, which the poller sets as every ticket's requester. NinjaOne's API documentation can send them for you with your session key or an access token.

text
GET https://<your NinjaOne host>/v2/organizations
    each client organization: id                 -> organization_id column
GET https://<your NinjaOne host>/v2/organization/<id>/locations
    its locations: id, name, address             -> location_id column
GET https://<your NinjaOne host>/v2/ticketing/ticket-form
    the ticket form for outage tickets: id       -> NINJA_TICKET_FORM_ID
GET https://<your NinjaOne host>/v2/users?userType=TECHNICIAN
    the ticket technician: uid                   -> NINJA_REQUESTER_UID

Step 4: List the locations to watch

Add one row per location with a unique site label (it appears in the ticket subject), coordinates in decimal degrees, the organization_id, and the location_id when you want the ticket filed under that location. Geocode each address once. Taking a row out resolves its open outage tickets on the next run.

text
site,lat,lon,organization_id,location_id
"Acme Dental, Plano",33.0198,-96.6989,3,17
"Acme Dental, Frisco",33.1507,-96.8236,3,21
"Brightline Logistics, Atlanta",33.749,-84.388,8,

Step 5: Write the poller

Save this as /opt/poweroutage/poweroutage_ninjaone.py; it needs only the Python standard library. Each run first checks every location, 100 per request, waiting out a 429 for its Retry-After seconds, and a failed check stops the run before NinjaOne is called. Only then does it swap the saved refresh token for an access token, saving the new refresh token if NinjaOne issues one. Outages are keyed <site>|poweroutage:<utilityId>:<outageId>: a new key gets a ticket, a changed cause or estimate gets a private comment, and a key that disappears gets one closing comment and the Resolved status. NinjaOne's update call replaces the whole ticket, needs a requester and refuses a direct move to Closed, so the poller reads the ticket first, keeps its fields and version, falls back to NINJA_REQUESTER_UID for the requester, and sets Resolved. A retried resolve doesn't repeat the comment, and tickets a technician already resolved or closed are left alone.

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

os.umask(0o077)  # the token and state files are readable by this account only
API_KEY = os.environ['POWEROUTAGE_API_KEY']
NINJA = 'https://' + os.environ['NINJA_HOST']  # app.ninjarmm.com, eu.ninjarmm.com, ca.ninjarmm.com ...
REDIRECT_URI = os.environ['NINJA_REDIRECT_URI']
TOKEN_FILE = Path(os.environ['NINJA_TOKEN_FILE'])  # the refresh token; NinjaOne may rotate it
TICKET_FORM_ID = int(os.environ['NINJA_TICKET_FORM_ID'])
REQUESTER_UID = os.environ['NINJA_REQUESTER_UID']  # the ticket technician's uid
STATE_FILE = Path(os.environ['STATE_FILE'])  # open tickets, kept between runs
RESOLVED, CLOSED = 5000, 6000  # built-in ticket statuses


def ninja_token(grant):
    form = urllib.parse.urlencode({
        'client_id': os.environ['NINJA_CLIENT_ID'],
        'client_secret': os.environ['NINJA_CLIENT_SECRET'],
        **grant,
    }).encode()
    with urllib.request.urlopen(f'{NINJA}/ws/oauth/token', data=form, timeout=30) as response:
        token = json.load(response)
    if token.get('refresh_token'):
        TOKEN_FILE.write_text(token['refresh_token'])
    return token['access_token']


if sys.argv[1:] == ['--authorize']:  # one-time sign-in as the technician who owns the tickets
    state = uuid.uuid4().hex
    print(f'{NINJA}/ws/oauth/authorize?' + urllib.parse.urlencode({
        'response_type': 'code',
        'client_id': os.environ['NINJA_CLIENT_ID'],
        'redirect_uri': REDIRECT_URI,
        'scope': 'monitoring management offline_access',
        'state': state,
    }))
    landed = input('Open that URL, approve, then paste the address the browser lands on: ')
    query = urllib.parse.parse_qs(urllib.parse.urlparse(landed).query)
    if query.get('state') != [state] or 'code' not in query:
        sys.exit('That address has no code for this sign-in; start again.')
    ninja_token({'grant_type': 'authorization_code', 'code': query['code'][0], 'redirect_uri': REDIRECT_URI})
    print(f'Saved the refresh token to {TOKEN_FILE}')
    sys.exit()

with open(os.environ['SITES_FILE'], newline='') as file:
    SITES = list(csv.DictReader(file))  # site,lat,lon,organization_id,location_id


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 ninja(method, path, body=None, content_type='application/json'):
    if body is not None and content_type == 'application/json':
        body = json.dumps(body).encode()
    request = urllib.request.Request(
        f'{NINJA}{path}', data=body, method=method,
        headers={'Authorization': f'Bearer {ACCESS_TOKEN}', 'Content-Type': content_type},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        raw = response.read()
    return json.loads(raw) if raw else None


def add_comment(ticket_id, text):
    """Comments are multipart, with the comment as a JSON part named 'comment'."""
    boundary = uuid.uuid4().hex
    body = (
        f'--{boundary}\r\nContent-Disposition: form-data; name="comment"\r\n'
        f'Content-Type: application/json\r\n\r\n{json.dumps({"public": False, "body": text})}\r\n'
        f'--{boundary}--\r\n'
    ).encode()
    ninja('POST', f'/v2/ticketing/ticket/{ticket_id}/comment', body,
          f'multipart/form-data; boundary={boundary}')


def resolve_ticket(entry):
    ticket_id = entry['ticket']
    ticket = ninja('GET', f'/v2/ticketing/ticket/{ticket_id}')
    if {ticket['status'].get('statusId'), ticket['status'].get('parentId')} & {RESOLVED, CLOSED}:
        return  # a technician already resolved or closed it
    if not entry.get('closing_noted'):  # a retried resolve doesn't repeat the comment
        add_comment(ticket_id, 'PowerOutage.us no longer reports this outage at the site.')
        entry['closing_noted'] = True
    keep = ('clientId', 'ticketFormId', 'locationId', 'nodeId', 'subject', 'type', 'priority',
            'severity', 'assignedAppUserId', 'additionalAssignedTechnicianIds', 'tags',
            'followupTime', 'version')
    update = {k: ticket[k] for k in keep if ticket.get(k) is not None}
    update['requesterUid'] = ticket.get('requesterUid') or REQUESTER_UID  # required by the update
    # Resolved, not Closed: the API refuses to close a ticket directly.
    ninja('PUT', f'/v2/ticketing/ticket/{ticket_id}', {**update, 'status': str(RESOLVED)})


def outage_details(outage, utility):
    return (
        f"{utility}. Cause: {outage.get('cause') or 'not reported'}. "
        f"Estimated restoration (UTC): {outage.get('estimatedRestorationAt') or 'not given'}."
    )


# Every outage covering a site, keyed '<site>|poweroutage:<utilityId>:<outageId>'.
# A failed request stops the run here, before any ticket is opened or resolved.
current = {}
for i in range(0, len(SITES), 100):
    batch = SITES[i : i + 100]
    points = outages_at([{'lat': float(s['lat']), 'lon': float(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']:
            key = f"{site['site']}|poweroutage:{outage['utilityId']}:{outage['outageId']}"
            utility = names.get(outage['utilityId']) or f"Utility {outage['utilityId']}"
            current[key] = (site, outage, utility)

try:
    ACCESS_TOKEN = ninja_token({'grant_type': 'refresh_token', 'refresh_token': TOKEN_FILE.read_text().strip()})
except urllib.error.HTTPError as err:
    if err.code not in (400, 401):
        raise
    sys.exit(f'NinjaOne refused the refresh token ({err.code}). Run this script with --authorize again.')
state = json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}
try:
    for key, (site, outage, utility) in current.items():
        details = outage_details(outage, utility)
        customers = f"Customers out: {outage.get('customersOut') or 'not reported'}."
        try:
            if key not in state:
                ticket = {
                    'clientId': int(site['organization_id']),
                    'ticketFormId': TICKET_FORM_ID,
                    'subject': f"Utility power outage at {site['site']}"[:200],
                    'description': {
                        'public': False,
                        'body': f"PowerOutage.us reports a utility outage at {site['site']}. "
                        f'{details} {customers} Outage key: {key}',
                    },
                    'status': '1000',  # New
                    'type': 'INCIDENT',
                    'requesterUid': REQUESTER_UID,
                }
                if site.get('location_id'):
                    ticket['locationId'] = int(site['location_id'])
                created = ninja('POST', '/v2/ticketing/ticket', ticket)
                state[key] = {'ticket': created['id'], 'details': details}
            elif state[key]['details'] != details:  # cause or restoration estimate changed
                add_comment(state[key]['ticket'], f'PowerOutage.us update. {details} {customers}')
                state[key]['details'] = details
        except urllib.error.HTTPError as err:
            print(f'NinjaOne answered {err.code} for {key}: {err.read()[:300]!r}', file=sys.stderr)
    for key in [k for k in state if k not in current]:
        try:
            resolve_ticket(state[key])
            del state[key]
        except urllib.error.HTTPError as err:
            print(f"NinjaOne answered {err.code} resolving ticket {state[key]['ticket']}", file=sys.stderr)
            if err.code == 404:
                del state[key]  # the ticket was deleted in NinjaOne
finally:
    STATE_FILE.write_text(json.dumps(state, indent=2))
print(f'{len(current)} site outage(s); {len(state)} ticket(s) open')

Step 6: Store the credentials and sign in once

Put the keys in an environment file that only the job's account can read. The shell reads the file, so keep every value in single quotes, as shown. Then run the poller once with --authorize: it prints a NinjaOne sign-in address, and after you sign in as the ticket technician and approve, the browser lands on the redirect URI with a code in the address bar. The page itself may not load. Paste the whole address back into the prompt and the poller saves the refresh token to NINJA_TOKEN_FILE, readable only by that account. That token acts as the technician until it is revoked, so keep it on a host you trust; if the host is ever compromised, revoke it under Administration > Apps > OAuth Tokens.

bash
# /opt/poweroutage/ninjaone.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='...'
NINJA_HOST='app.ninjarmm.com'
NINJA_CLIENT_ID='...'
NINJA_CLIENT_SECRET='...'
NINJA_REDIRECT_URI='https://localhost/poweroutage'
NINJA_TOKEN_FILE='/opt/poweroutage/ninjaone-refresh-token'
NINJA_TICKET_FORM_ID='...'
NINJA_REQUESTER_UID='...'
SITES_FILE='/opt/poweroutage/ninjaone-sites.csv'
STATE_FILE='/opt/poweroutage/ninjaone-tickets.json'

# Once, as the account that runs the job, signed in to NinjaOne as the technician
# the tickets should come from:
set -a && . /opt/poweroutage/ninjaone.env && set +a
python3 /opt/poweroutage/poweroutage_ninjaone.py --authorize

Step 7: Know what each ticket carries

This is every field the poller writes. The description and comments are sent with public set to false, so they stay internal to your technicians. To set a priority, severity or assignee on new tickets, add priority, severity or assignedAppUserId to the ticket body in the poller.

text
ticket field          value
clientId              organization_id from the sites file
locationId            location_id from the sites file, when it is filled in
ticketFormId          NINJA_TICKET_FORM_ID
subject               Utility power outage at <site>
description           private: PowerOutage.us reports a utility outage at <site>. <utility name>.
                      Cause: <cause>. Estimated restoration (UTC): <estimatedRestorationAt>.
                      Customers out: <customersOut>. Outage key: <site>|poweroutage:<utilityId>:<outageId>
status                1000 (New) on creation; 5000 (Resolved) when power returns
type                  INCIDENT
requesterUid          NINJA_REQUESTER_UID, the ticket technician

comment (private)     PowerOutage.us update. <utility>. Cause: ... Estimated restoration ...
                      Customers out: ... Added when the cause or restoration estimate changes
comment (private)     PowerOutage.us no longer reports this outage at the site.
                      Added once, just before the ticket is resolved

Step 8: Run it every 15 minutes

Schedule the poller from the crontab of the account that ran --authorize, because it owns the token file. Errors go to standard error, which cron mails to MAILTO; the run summary goes to the log. 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 * * * *). The first run creates tickets for every location already inside an outage.

bash
# crontab -e, as the account that ran --authorize. The run summary goes to the log,
# errors (such as a refused refresh token) to MAILTO. flock -n skips a run while the
# previous one still holds the lock.
MAILTO=alerts@yourmsp.example
*/15 * * * * set -a && . /opt/poweroutage/ninjaone.env && flock -n /opt/poweroutage/ninjaone.lock /usr/bin/python3 /opt/poweroutage/poweroutage_ninjaone.py >> /opt/poweroutage/poweroutage_ninjaone.log

Tips for NinjaOne

  • If NinjaOne refuses the refresh token, every run stops with a message until you run --authorize again. That happens when the technician's account is disabled, the token is revoked under Administration > Apps > OAuth Tokens, or the poller has been stopped long enough for the token to expire. Make sure the MAILTO mail reaches someone, or send standard error to a file your monitoring watches, because until then no outage gets a ticket.
  • If resolving a ticket keeps failing with 400, open it in NinjaOne. The update needs a requester, the ticket form and the current version; the poller rereads the version and fills a missing requester from NINJA_REQUESTER_UID, so check that the ticket form still exists and that the technician account behind that uid is still active.
  • Back up the state file but treat the token file like a password. If the state file is lost, tickets for outages still in progress are orphaned and the poller opens new ones; search for the subject "Utility power outage at" to find the old ones and resolve them yourself.
  • Where every utility serving a location reports providesGeospatialData: false in the response's utilities list, there is no outage shape to test the point against, so that location never gets a ticket. Keep NinjaOne's own offline alerts on for those.
  • Ticketing automations and notification rules in NinjaOne apply to these tickets. Check that none of them emails the client for a new outage ticket unless you want it to.

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.