> For the complete documentation index, see [llms.txt](https://developer.relaypro.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.relaypro.com/integrations/servicenow-alerts.md).

# ServiceNow Alerts

## Overview

[ServiceNow](https://www.servicenow.com/) is an IT service management platform that tracks work as records on tables. Its **Business Rules** engine runs server-side JavaScript whenever a record is inserted or updated. Business Rules can make outbound REST calls with the built-in `sn_ws.RESTMessageV2` API, so a ServiceNow instance can call any publicly reachable HTTPS endpoint.

That is all you need to turn a critical ticket into a voice alert in a technician's hand: ServiceNow detects the priority change, posts to the [Relay Alerts API](https://developer.relaypro.com/docs/relay-alerts-api), and every device in the target Workflow Group speaks the message until someone taps the talk button to accept the job.

This page builds a complete, working **critical incident** alert.

```mermaid
flowchart LR
    A["Incident<br/>Priority = 1 - Critical"] --> C["ServiceNow<br/>Business Rule<br/>after insert/update, async"]
    C --> E["RESTMessageV2<br/>POST /alerts"]
    E --> F["Relay devices<br/>in Workflow Group"]
    F --> G["Acknowledged"]
```

### Why Alerts and not Broadcasts

Relay offers two notification types. Use **Alerts** for critical incidents. An alert repeats every 30 seconds until a human acknowledges it, and it records who accepted the job, which is the accountability an urgent ticket needs. A [broadcast](https://developer.relaypro.com/docs/relay-broadcasts-api) plays once with no acknowledgement. That is fine for shift announcements, but generally the wrong approach for a critical ticket.

### Why a Business Rule and not Flow Designer

ServiceNow's Flow Designer can also call REST endpoints, but its **REST step** is part of the **Integration Hub** spoke, which requires an Integration Hub subscription and is not installed on every instance. A Business Rule works on every ServiceNow instance with no additional licensing, so this guide uses one. If your organization already has Integration Hub, you can build the equivalent flow with the same endpoint, header, and JSON body shown below.

***

## Prerequisites

<table><thead><tr><th width="180">Side</th><th>Requirement</th></tr></thead><tbody><tr><td>Relay</td><td>An <strong>enterprise plan</strong> account. API keys are not available on lower tiers.</td></tr><tr><td>Relay</td><td>A <strong>Workflow Group</strong> containing the users who should receive critical incident calls.</td></tr><tr><td>Relay</td><td>Your <strong>subscriber ID</strong> and an <strong>API key</strong>.</td></tr><tr><td>ServiceNow</td><td>An instance where you have the <strong>admin</strong> role (a <a href="https://developer.servicenow.com/">Personal Developer Instance</a> works for trying this out). This guide was verified on the <strong>Brazil</strong> release.</td></tr><tr><td>ServiceNow</td><td>Outbound HTTPS access from the instance to <code>api.relaypro.com</code>. Hosted instances allow this by default; self-hosted or restricted instances may need an egress rule.</td></tr></tbody></table>

***

{% stepper %}
{% step %}

## Create the Relay Workflow Group

In [Relay Dash](https://dash.relaypro.com/), open **Incidents** in the left-hand navigation.

Select **Workflow Groups**, then **Create Workflow Group**.

Name the group. This guide uses `maintenance`.

Set the type to **No Type**.

Select the new group, choose **Edit Membership**, and add the users who should be called.

The group name is what ServiceNow will send in the `groups` array of the API payload.
{% endstep %}

{% step %}

## Collect your Relay credentials

| Value           | Where to find it                                                                              |
| --------------- | --------------------------------------------------------------------------------------------- |
| `subscriber_id` | Relay Dash → **Help** → **Diagnostic Logs** → **Server Details**, listed under **Subscriber** |
| `apikey`        | Relay Dash → **Help** → [**API Keys**](https://dash.relaypro.com/api-keys) → create a key     |

{% hint style="warning" %}
Create a **dedicated API key for this integration** rather than reusing one. If the ServiceNow instance is ever compromised, or an admin leaves with access, you want to revoke one key without breaking every other integration you run.
{% endhint %}
{% endstep %}

{% step %}

## Prove the Relay side works

Fire the alert by hand first:

```sh
export subscriber_id=your_subscriber_id
export apikey=your_api_key

curl -X POST \
  -H "Authorization: RelayApiKey $apikey" \
  -H "Content-Type: application/json" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts" \
  -d '{"notification": "Test alert from ServiceNow integration", "groups": ["maintenance"]}' \
  -i
```

A successful call returns `HTTP/2 200` and a task ID:

```json
{"task_id":"P9CThKfTsEbJx23trAArHCD"}
```

Devices in `maintenance` should now be speaking the message every 30 seconds. Tap the talk button on one to acknowledge, or cancel it from the terminal:

```sh
curl -X DELETE \
  -H "Authorization: RelayApiKey $apikey" \
  "https://api.relaypro.com/subscribers/$subscriber_id/api/v1/alerts/P9CThKfTsEbJx23trAArHCD"
```

{% hint style="success" %}
If this curl works and the ServiceNow rule does not, the problem is in the rule, not in Relay.
{% endhint %}
{% endstep %}

{% step %}

## Store the credentials as System Properties

Keep the subscriber ID, API key, and group name out of the script by storing them as system properties.

In ServiceNow, type `sys_properties.list` into the navigator filter and press Enter, then select **New** for each of the following:

| Name                  | Type        | Value                                              |
| --------------------- | ----------- | -------------------------------------------------- |
| `relay.subscriber_id` | `string`    | Your subscriber ID from Step 2                     |
| `relay.api_key`       | `password2` | Your API key from Step 2                           |
| `relay.group`         | `string`    | The Workflow Group name, for example `maintenance` |

Leave **Application** as **Global** and select **Submit** on each.

{% hint style="info" %}
Setting the type to **`password2`** stores the API key encrypted, so it is not readable in the property list. The script reads it with `gs.getProperty()` like any other property.
{% endhint %}

If `relay.group` is missing, the script falls back to a group named `maintenance`.
{% endstep %}

{% step %}

## Create the Business Rule

Type `sys_script.list` into the navigator filter, press Enter, and select **New**. Fill in the form as follows.

| Field        | Value                                |
| ------------ | ------------------------------------ |
| **Name**     | `Relay - Alert on Critical Incident` |
| **Table**    | `Incident [incident]`                |
| **Active**   | Checked                              |
| **Advanced** | Checked                              |

On the **When to run** tab:

| Field      | Value   |
| ---------- | ------- |
| **When**   | `async` |
| **Order**  | `100`   |
| **Insert** | Checked |
| **Update** | Checked |

On the **Advanced** tab, set **Condition** to:

```javascript
current.priority.changesTo(1)
```

Then replace the contents of the **Script** field with:

```javascript
(function executeRule(current, previous /*null when async*/ ) {

    var subscriberId = gs.getProperty('relay.subscriber_id');
    var apiKey = gs.getProperty('relay.api_key');
    var group = gs.getProperty('relay.group', 'maintenance');

    var num = current.getValue('number');
    var desc = (current.getValue('short_description') || '').replace(/[^A-Za-z0-9 .,'-]/g, ' ');

    var payload = {
        notification: 'Critical incident ' + num + '. ' + desc + '. Please respond.',
        groups: [group],
        quorum: 1,
        timeout: 600,
        name: 'servicenow-incident',
        on_ack: 'Accepted. You are assigned to ' + num + '.',
        on_quorum: 'Another technician has taken this call.',
        on_timeout: 'Critical incident ' + num + ' was not acknowledged.'
    };

    var req = new sn_ws.RESTMessageV2();
    req.setEndpoint('https://api.relaypro.com/subscribers/' + subscriberId + '/api/v1/alerts');
    req.setHttpMethod('POST');
    req.setRequestHeader('Authorization', 'RelayApiKey ' + apiKey);
    req.setRequestHeader('Content-Type', 'application/json');
    req.setRequestBody(JSON.stringify(payload));

    try {
        var res = req.execute();
        var code = res.getStatusCode();
        if (code === 200) {
            gs.info('Relay alert sent for ' + num + ', task_id=' + JSON.parse(res.getBody()).task_id);
        } else {
            gs.error('Relay alert failed for ' + num + ': HTTP ' + code + ' ' + res.getBody());
        }
    } catch (e) {
        gs.error('Relay alert exception for ' + num + ': ' + e.message);
    }

})(current, previous);
```

Select **Submit** to save the rule.

{% hint style="info" %}
**Why `async`?** An async rule runs in the background shortly after the record is saved, so a slow or failed call to Relay never delays or blocks the person saving the ticket. A `before` or `after` rule would hold the form until the HTTP call finished.
{% endhint %}

{% hint style="warning" %}
The literal string `RelayApiKey` and a space must precede the key. `Authorization: YOUR_API_KEY` returns 401.
{% endhint %}
{% endstep %}

{% step %}

## Test it end to end

Create a test incident (type `incident.do` into the navigator filter, or use **Incident → Create New**):

1. Set a **Caller** and a **Short description** such as `Press 7 on Line B is down`.
2. Set **Impact** to `1 - High` and **Urgency** to `1 - High`. **Priority** recalculates to `1 - Critical`.
3. Select **Submit**.

Within a few seconds a device in your Workflow Group should speak:

> Critical incident INC0010001. Press 7 on Line B is down. Please respond.

Tap the talk button to acknowledge. The device that accepts hears *Accepted. You are assigned to INC0010001.* and the other devices in the group stop alerting.

To confirm from the ServiceNow side, open **System Logs → System Log → All** and filter **Message** contains `Relay alert`. A successful call logs:

```
Relay alert sent for INC0010001, task_id=Q55jJRTWi3zPYtcFAaI5cD
```

{% hint style="success" %}
The `task_id` in the log is the same ID the Relay API returned. Use it to cancel the alert with the `DELETE` call from Step 3, or to correlate with analytics events (see [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)).
{% endhint %}
{% endstep %}
{% endstepper %}

***

## How the trigger works

The **Condition** `current.priority.changesTo(1)` is true when an incident is **inserted with Priority 1** or **updated so that Priority becomes 1**. It does not fire on later edits to a ticket that is already Priority 1, so adding a comment or reassigning the ticket will not page the group again.

Two behaviors to be aware of:

* If a ticket moves from Priority 1 to another priority and later back to Priority 1, the rule fires again and a new alert is sent.
* Priority is normally calculated from **Impact** and **Urgency**. Changing either field can move Priority to 1 and trigger the rule.

### Changing what counts as urgent

Edit the **Condition** on the Business Rule. Some common variations:

| Goal                                            | Condition                                                                        |
| ----------------------------------------------- | -------------------------------------------------------------------------------- |
| Priority 1 or 2                                 | `current.priority.changesTo(1) \|\| current.priority.changesTo(2)`               |
| High urgency, regardless of priority            | `current.urgency.changesTo(1)`                                                   |
| Priority 1 only for a specific assignment group | `current.priority.changesTo(1) && current.assignment_group.name == 'Facilities'` |

To route different tickets to different Relay groups, replace the `group` variable in the script with a value computed from the record, for example from `current.getValue('category')`. The value must match a Workflow Group name (or URN) in Relay Dash.

***

## Payload reference

### Relay alert keys

`notification` and `groups` are required. Everything else is optional.

| Key            | Type          | Default                      | Behavior                                                                                           |
| -------------- | ------------- | ---------------------------- | -------------------------------------------------------------------------------------------------- |
| `notification` | string        | —                            | Spoken on every device in the group via text-to-speech.                                            |
| `groups`       | array         | —                            | Workflow Group names or URNs to alert.                                                             |
| `quorum`       | integer       | all devices must acknowledge | Cancels remaining alerts after this many acknowledgements. **Set this to `1` for incident calls.** |
| `on_ack`       | string        | nothing spoken               | Spoken on the device that acknowledged.                                                            |
| `on_quorum`    | string        | nothing spoken               | Spoken on devices that had not yet acknowledged once quorum is met.                                |
| `timeout`      | integer (sec) | `300`                        | Cancels remaining alerts after this long.                                                          |
| `on_timeout`   | string        | nothing spoken               | Spoken on devices that never acknowledged, after timeout.                                          |
| `name`         | string        | `alerts`                     | Controls serial/concurrent alerting behavior and appears in analytics events for correlation.      |

Leaving `quorum` at its default means the alert keeps sounding on every other device until **all** of them acknowledge. That is not what you want for an incident call where one technician takes the job. Set `quorum: 1`.

### ServiceNow fields used in the message

The script reads these fields from the incident (`current`):

| Field                                   | Used for                                       |
| --------------------------------------- | ---------------------------------------------- |
| `current.getValue('number')`            | Spoken ticket number, for example `INC0010001` |
| `current.getValue('short_description')` | Spoken problem summary                         |

Other fields you can read the same way include `priority`, `category`, `location`, `cmdb_ci`, and `assignment_group`. For reference fields such as `location`, use `current.location.getDisplayValue()` to get the human-readable name rather than the record's `sys_id`.

{% hint style="warning" %}
**Write for text-to-speech, not for a log file.**

Use display names, not `sys_id` values or machine keys. A `sys_id` spoken aloud is 32 characters of noise.

Free-text fields such as `short_description` and `description` are typed by people and can contain codes, URLs, and punctuation that sound like gibberish when spoken. The script above replaces everything except letters, digits, spaces, and `. , ' -` with a space. Keep spoken messages to a sentence or two. Do not interpolate `description` or work notes.
{% endhint %}

{% hint style="info" %}
The script builds the request body with `JSON.stringify()`, so a double quote, backslash, or newline in a ticket field cannot produce invalid JSON. If you adapt this to build the body by string concatenation instead, those characters will cause Relay to reject the request with a 400.
{% endhint %}

***

## Troubleshooting

Start with the log: **System Logs → System Log → All**, filter **Message** contains `Relay alert`. Every run of the rule writes exactly one line.

| Symptom                                              | Likely cause and fix                                                                                                                                                                                                                 |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| No `Relay alert` line in the log at all              | The rule did not run. Check that it is **Active**, that **Insert** and **Update** are checked, and that the incident's Priority actually changed to `1 - Critical` in this save. A ticket that was already Priority 1 will not fire. |
| `HTTP 401`                                           | The `Authorization` header is wrong. It must be `RelayApiKey <key>` with a space. Also confirm the key was copied completely and has not been revoked.                                                                               |
| `HTTP 400`                                           | The request body was rejected. If you changed the script to build JSON by hand, check for unescaped quotes or newlines in interpolated values.                                                                                       |
| `HTTP 404`                                           | The subscriber ID in `relay.subscriber_id` is wrong or has stray whitespace.                                                                                                                                                         |
| `Relay alert exception ...`                          | The call never reached Relay (DNS, firewall, or timeout). Confirm the instance can reach `api.relaypro.com` over HTTPS.                                                                                                              |
| Log says `sent`, but no device speaks                | The alert was accepted, so check the Relay side. The `relay.group` value must exactly match a Workflow Group name, and that group must have members whose devices are online.                                                        |
| The alert keeps repeating after someone started work | Alerts repeat every 30 seconds until acknowledged on a device or until `timeout`. Acknowledge on the device, or cancel with the `DELETE` call in Step 3.                                                                             |

{% hint style="success" %}
If the curl command in Step 3 works but the rule does not, the problem is in ServiceNow, not in Relay.
{% endhint %}

***

## Reference

### ServiceNow

* [Business rules](https://www.servicenow.com/docs/r/platform-administration/business-rules.html)
* [RESTMessageV2 API](https://developer.servicenow.com/dev.do#!/reference/api/latest/server/sn_ws-namespace/c_RESTMessageV2API)
* [Flow Designer REST step (requires Integration Hub)](https://www.servicenow.com/docs/r/build-workflows/workflow-studio/rest-request-action-designer.html)

### Relay

* [Alerts overview](https://developer.relaypro.com/docs/relay-alerts-api)
* [Triggering an Alert](https://developer.relaypro.com/docs/relay-alerts-api/triggering-an-alert)
* [Customizing Your Alerts](https://developer.relaypro.com/docs/relay-alerts-api/customizing-your-alerts)
* [Advanced Configuration](https://developer.relaypro.com/docs/relay-alerts-api/advanced-configuration)
* [Broadcasts](https://developer.relaypro.com/docs/relay-broadcasts-api)
