Image for post
Image for post

Google Apps Script: AQI Slack bot

Christopher Holmes
Sep 14 · 6 min read

Working in a Global Security Operations Center usually involves monitoring current events and especially abnormal weather. Abnormal weather can cause facility closures, and a good operation will be constantly monitoring any changes to abnormal weather. Currently, we are suffering from poor air quality in the Bay Area due to fires throughout the state of California. As a result, most physical security operations are probably monitoring air quality.

Rather than manually update my team hourly, I used a slack bot that grabs the AQI from the air now API every hour. So I thought I’d share how I did it, and maybe if you use G Suite and Slack in your workplace you could set one up too.

First, I’d recommend checking out this article on how to set up the slack bot with api.slack.com and Google Apps Script. It’s well written and gets straight to the point.

Once you’re able to send out your first message with the slack bot based on the previous article using the giphy API — check back here to learn how to set up a slack bot that will update the air quality for your team.

Set Up Air Now API Account

Go to the following website and set up a free account. When you sign up you’ll be able to retrieve an API key. If you click File > Project properties in your apps script file. You can set the API key to a value in your project properties.

Image for post
Image for post

Fetch the AQI

First, we have to put together a URL to fetch some data. And the airnow API website makes this easy for developers because they have a query tool that will generate the request URL for you, including your API key last.

Image for post
Image for post
Air Now Query Tool

The Query tool makes getting a request URL extremely simple, just type in the zip code and distance you’ll get a request that will provide you some data containing the current air quality. At the top of my apps script file, I placed this URL in a constant called AIR_NOW_BASE and appended the API Key using the project property that I set.

//retrieve API Key from properties service
var AIR_NOW = PropertiesService
.getScriptProperties()
.getProperty('AIR_NOW');
// generate base url request for current conditions with in
//50 miles of the zip code 94103
var AIR_NOW_BASE = "http://www.airnowapi.org/aq/observation/zipCode/current/?format=application" +
"/json&zipCode=94103&distance=50&API_KEY=" + AIR_NOW
function airQuality()
{
var data
try {var response = UrlFetchApp.fetch(AIR_NOW_BASE);
data = JSON.parse(response)
} catch(error) {return "error retrieving AQI"

}
return data[1].AQI}

Awesome, now we have a method for retrieving the current AQI. And if it fails we will return an error message.

Send the AQI to the channel

Slack provides a lot of options for sending messages through a bot. Bots can be made to be quite interactive. But, all we are doing here is sending off a message periodically. No need for too much razzle-dazzle, just some good ol’ straight forward code.

I created a method called updateChannelAQI() that puts together a message that has a bit of formatting and returns a custom message depending on where the AQI is.

function updateChannelAQI()
{
var channel = "your_channel"
var aqi = airQuality()
var status = "Good"
// depending on where the AQI - the status will be updated
switch(true)
{
case aqi < 51: status = "Green"; break;
case aqi < 101: status = "Yellow"; break;
case aqi < 151: status = "Orange"; break;
case aqi < 201: status = "Red"; break;
case aqi < 301: status = "Purple"; break;
case aqi < 500: status = "Maroon"; break;
default: status = "Over 500..."


}

var block = [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "AQI Update :airwatch: ",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
//throw in the aqi and the status in the return text
"text": "AQI currently at " + aqi + " (*"+ status +"*)"
}
},
{
"type": "divider"
}
]

var blocks = JSON.stringify(block)

var payload = {token:SLACK_ACCESS_TOKEN, channel: channel, text:"",blocks: blocks};

fetchLogSuccess(payload)
}
var POST_MESSAGE_ENDPOINT = 'https://slack.com/api/chat.postMessage';function fetchLogSuccess(payload)
{
try{
var val = UrlFetchApp.fetch(POST_MESSAGE_ENDPOINT, {method: 'post', payload:payload});
var result = JSON.parse(val.getContentText())

if(result.ok)
{
console.log("success")
} else {
console.log(result.error)
}
} catch (e) {
console.log("failed to send message to slack")
console.log(e)
}
}
/**

If you’d like to learn more about using blocks check out the documentation. Otherwise, just replace the block that I’ve set with your custom title or message.

The fetchLogSuccess() method posts the message to the Slack bot. I have it separated in its method so that if I choose to give this bot some more features I won’t be repeating code. I can just pass it a payload that gets generated.

To test it out you can run the method in the editor and you should see a message like this pop into the channel that you selected.

Image for post
Image for post
Displaying AQI in Channel

Set up the Trigger

Having to manually go back to the Apps Script editor every hour to have the slack bot send a message would defeat the purpose of making the bot work on its own. So to do this we can set up a trigger in a google apps script to run the updateChannelAQI() method hourly.

Image for post
Image for post
The Trigger Button

Clicking on the button displayed above will open up a window that will allow you to see the triggers for the project. Select the Add Trigger button on the bottom right-hand side of the page.

From there you can select which function to run, and how often to run it. You can even choose how often you should be notified of any failures. Here you’d select the method that you’d like to run and how often you’d like to run it. Here’s what the trigger I set up looks like.

Image for post
Image for post

Now if you’ve made it this far and followed along Congratulations! You have successfully set up a Slack bot that will update the AQI into your slack channel every hour. This will save you and your teammates the time from having to collect the AQI hourly. I don’t know about you, but I’m not fond of tedious tasks that we can make scripts do for us.

And there is so much potential for improvement here. Maybe you only want the message to send when the AQI is above 150? Maybe you want to send a custom message to certain stakeholders when the AQI reaches over 200? Depending on the circumstances you want, you can write some code in Apps Script to get you there.

Christopher Holmes

Open to Work

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store