DEV Community

Nico Martin
Nico Martin

Posted on

Uptime Monitoring Slackbot

In the first two parts we initialized out Firebase app and we configured our could functions to check the status of our site. Now, we also want to be notified.

Create a slack app

First, we need to create a slack app. This can be done via the following URL:
https://api.slack.com/apps?new_app=1

In the prompt a new app can be created "From scratch".
A name and a workspace must be selected. On the next page webhooks can be activated via the button "Incoming Webhooks" and on the following page "Activate Incoming Webhooks".
Once activated, you should see a button "Add New Webhook to Workspace", which opens another prompt to select the target channel.
Now you can use the generated Webhook URL to send messages to this channel.

Time to work on our code.

Send message

First, we create a helper function that sends the message. It is basically just a POST request to the Webhook URL:

const fetch = require("node-fetch");

export const sendMessage = async (text: string) => {
  const payload = {
    username: "Uptime Slackbot",
    text,
  };

  return fetch(process.env.WEBHOOK, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: "payload=" + encodeURIComponent(JSON.stringify(payload)),
  });
};
Enter fullscreen mode Exit fullscreen mode

https://github.com/nico-martin/uptime-slackbot/blob/main/functions/src/utils/message.ts

In this example we assume the Webhook URL is saved as WEBHOOK in our .env file.

As the last step, instead of only log the Up- and Downtime of our app, we can send the same string also using our sendMessage function.

// requestOnWrite.ts 
if (request.ok) {
  const downtimeMillis = request.started.toMillis() - uptimeEntry.created.toMillis();
  uptimeEntry.responseOk = true;
  uptimeEntry.downtimeMillis = downtimeMillis;
  await db.update(context.params.uptimeId, uptimeEntry);
  functions.logger.log(`Uptime Monitor is UP: ${request.url}. It was down for ${formatSeconds(Math.round(downtimeMillis / 1000))}.`);
  await sendMessage(`Uptime Monitor is UP: ${request.url}. It was down for ${formatSeconds(Math.round(downtimeMillis / 1000))}.`);
}
Enter fullscreen mode Exit fullscreen mode
// scheduleUptime.ts
if (!check.ok) {
  functions.logger.log(`Uptime Monitor is DOWN: ${check.url} - StatusCode: ${check.statusCode}`);
  await sendMessage(`Uptime Monitor is DOWN: ${check.url} - StatusCode: ${check.statusCode}`);
}
Enter fullscreen mode Exit fullscreen mode

There we go. Whenever our site is down, we will be notified. And whenever it is up again, we will be notified again.

The whole source code is on GitHub and can be used right away. Have fun :)

https://github.com/nico-martin/uptime-slackbot

Top comments (0)