When you're working with scheduled R scripts, it could be useful to get an alert when something goes wrong. Of course, there are ways to send emails, but wouldn't it be nice if your entire team could get a notice in real time in Slack instead (or as a complement to emails)?
This is actually super easy to do. The first thing you need to do is to create your own Slack app. Head over to https://api.slack.com/apps and click on "Create New App". Choose a name for the app and what workspace it will belong to, as shown in the image below.
Now head over to "Incoming Webhooks" and activate it. Once it's been activated, a new field should appear, where you can choose to create a new webhook. Click on that option and pick a channel or user that you want to send the messages to. When you're done it should look as the following.
That's all you have to do in Slack to get this to work, just make sure to copy the webhook URL. If you check the channel you picked, there should be a message saying that you made a new integration to it.
Now, let's head over to RStudio! The key is to put the code you want to run within tryCatch. When an error occur, a message will be sent to Slack, using the webhook you created before.
library(httr) hook <- "https://hooks.slack.com/services/ABC/ABC/SOMETHING" title <- "Something went wrong when trying to update Google Search Console data to BigQuery" tryCatch({ thisWontwork(nonsense) }, error = function(err){ body <- list( text = title, attachments = list( list( color = "#f00", fields = list( list( value = as.character(err) ) ), footer = "<http://11.222.33.44|Go to RStudio>" ) ) ) POST(hook, encode = "json", body = body) })
Make sure you keep the structure in "body". This will format it the correct way, as the Slack API demands. If you want to play around with it, you can check what you can do at the Slack API Reference. From now on, every time an error occurs, you will receive the message immediatley in your Slack channel.
Comments