Slack notifications about text messages & voicemails

Jakob
04.08.2020 0 4:43 min

What is sipgate.io?

sipgate.io is a collection of APIs, which enables sipgate’s customers to build flexible integrations matching their individual needs.
Among other things, it provides interfaces for sending and receiving text messages and faxes, monitoring the call history, as well as initiating and manipulating calls.
The webhook capability of sipgate.io allows for the real-time processing of call data and implementation of applications like IVRs (interactive voice recordings).

In this tutorial

You will learn how to notify a slack channel or a person about incoming text messages and voicemails.

Set up the project

For this project we will be using the official sipgate.io Node.js library, which makes working with sipgate’s APIs much easier.

But first, let’s create a new Node project.
To do that, create a new directory that will hold our project and inside run npm init -y.

This creates a package.json file containing some meta data for the project.
Open it up and add

"scripts": {
  "start": "node index.js"
}

inside the outer curly braces to register a start script that can later be called from the command line.

Now, to install the sipgate.io Node library run npm install -S sipgateio.

That’s it for now.
We will come back and install some more dependencies later.

Creating a client

Let’s get coding!

Create a new file named index.js.
First of all we create a sipgateio client to connect and authenticate us against the api. The historyModule will allow us to retrieve the history data of the account.

const { createHistoryModule, sipgateIO } = require("sipgateio");

const sipgateio = sipgateIO({
  tokenId: process.env.SIPGATE_TOKEN_ID,
  token: process.env.SIPGATE_TOKEN,
});

const historyModule = createHistoryModule(sipgateio);

For more information about personal access tokens visit https://www.sipgate.io/rest-api/authentication#personalAccessToken.

Fetch the history

To send notifications about new text messages and voicemails we have to repeatedly fetch the history (polling).

const handleEntries = (entries) => {
  entries.forEach((entry) => {
    console.log(entry);
  });
};

setInterval(() => {
  historyModule
    .fetchAll({
      types: [HistoryEntryType.SMS, HistoryEntryType.VOICEMAIL],
      directions: ["INCOMING"],
    })
    .then(handleEntries)
    .catch(console.error);
}, 5000);

The setInterval function runs the callback in the first parameter every 5 seconds as specified in the second parameter.
You can learn more about it here.

In the callback we fetch history entries with the fetchAll function filtering the type to receive only incoming text messages and voicemails.

Now it’s time for a test drive!

Start up the script with npm start.
Make sure that you set the following environment variables according to your account details correctly.

    SIPGATE_TOKEN_ID=your_SIPGATE_TOKEN_ID
    SIPGATE_TOKEN=your_SIPGATE_TOKEN

When sending a text message or recording a voicemail, you should now see the log of the incoming entry.

You will notice that the current code prints all history items even though we only want the ones we have not printed yet. To do so we’ll mark the received entries as archived:

const handleEntries = (entries) => {
  // ...
  historyModule.batchUpdateEvents(entries, () => {
    return { archived: true };
  });
};

When polling, we’ll apply a filter to only get the non-archived ones.

    // ...
    .fetchAll({
      // ...
      archived: false
    })
    // ...

Slack webhook

Now we are ready to send notifications about new text messages and voicemails using a slack webhook.
First of all we need to configure a new slack webhook for a channel or a person to send the message.
You can find more information on how to do that in the official slack documentation.

Once you have created the webhook, we can send a post request to the url generated by slack.
We will be using axios, a promise-based http client for sending the network request.
To install axios, run npm install -S axios.

It’s always a good idea to store sensitive and/or often changing configuration in environment variables.
We’ll be using a SLACK_WEBHOOK_URL variable to store the slack webhook URL.
We can then import axios and retrieve the Slack webhook URl from the environment variable by inserting the following statement at the top of the index.js file:

const axios = require("axios").default;

const slackWebhookUrl = process.env.SLACK_WEBHOOK_URL;
if (!slackWebhookUrl) {
  console.error(
    "Please provide a Slack webhook URL via the environment variable SLACK_WEBHOOK_URL"
  );
  return;
}

Instead of logging the entries we can now send it to slack.

const handleEntries = (entries) => {
  entries.forEach((entry) => {
    if (entry.type === HistoryEntryType.SMS) {
      axios.post(slackWebhookUrl, {
        text: `SMS received from ${entry.source}:\n${entry.smsContent}`,
      });
    }
    if (entry.type === HistoryEntryType.VOICEMAIL) {
      axios.post(slackWebhookUrl, {
        text: `New voicemail recording from ${entry.source}:\n${entry.recordingUrl}`,
      });
    }
  });

  historyModule.batchUpdateEvents(entries, () => {
    return { archived: true };
  });
};

To send different slack notifications for text messages and voicemails we’re first checking for the entry type.

Now were are ready to test our implementation.
Before you start the application with npm start make sure to correctly set the required environment variables.

You can now send text messages to your sipgate number or record voicemails to see them show up in slack.

You can checkout the complete source code here.

Keine Kommentare


Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert