How to Slack from R

See how to send text messages and files directly from an R script to Slack with the slackr package

How to Slack from R
Thinkstock

Using R to send a Slack message may sound like a parlor trick, but there are actually a lot of cases where that could come in handy. I’ve used Slack to send graphs to colleagues showing the latest web analytics trends. You can also use Slack to notify yourself or others when a lengthy R script finishes running.

Bob Rudis created the R package slackr that makes it easy to send Slack messages with R. It’s on CRAN, so you can install it with install.packages("slackr").

By far, the most complicated part of using slackr is initial setup. Fortunately, you only need to do that once. 

You’ll need to authorize R to use your specific Slack. Bob shows a sample configuration file to do this, in the following format:

api_token: YOUR_FULL_API_TOKEN
channel: #general
username: slackr
incoming_webhook_url: https://hooks.slack.com/services/XXXXX/XXXXX/XXXXX

So, you need an API token and an incoming webhook URL. Slack’s developer documentation for this can be tough to find. It turns out that you want to create a new Slack app in whatever Slack you want to message.

Go to api.slack.com/apps and click the green Create New App button. 

Slack Create App button Sharon Machlis, IDG

Create a Slack app as part of setting up R to work with a Slack workspace.

Next, select Incoming Webhooks.

Add webhook Sharon Machlis, IDG

Add a webhook to your new Slack app.

You’ll then see an option to activate them.

Activate Webhooks Sharon Machlis

The switch to active Webhooks on a Slack app.

Finally, scroll down and add a new webhook. You’ll be asked what channel you want to post to. Don’t worry, you can override that—you don’t need a new hook for each channel. Select a default channel, and then click install. You can see what all these steps look like in the video embedded at the top of this article.

After enabling webhooks, copy the resulting webhook URL into your R Slack configuration file. And make sure your configuration file is a plain text file and not an R script.

You also need an API token. A Slack “legacy” token works for this. Slack will flash many warnings advising you not to use them, but they do in fact let you connect R to your Slack. 

To get a legacy token, go to api.slack.com/custom-integrations/legacy-tokens. You should see your Slack workspace listed on that page. Click the Create Token button and copy the token string into your authorization file.

Slack setup is done.

Next up: Configure slackr to use the authorization file. That part is more straightforward, requiring one line of code with the slackr_setup() function.

slackr_setup() defaults to expecting a file named .slackr in your home directory. If you want to use another file in another location, add its name—including full file path if it’s not in your working directory—to slackr_setup(). In the code below, I’m using a file called .morewithr_slack in my current project directory.

slackr_setup(config_file = ".morewithr_slack")

You need to run the slackr_setup() function and any necessary arguments at the start of each session in which you’re using slackr.

Finally, the fun part: Send messages and files.

Below, I created a simple text string with my current system date and time and saved it to a variable my_message. To send it to Slack, I used the slackr_msg() function with the first argument my message text and the second argument the channel.

my_message <- paste("I'm sending a Slack message at", Sys.time(), "from my R script.")
slackr_msg(my_message, channel = "#slack-from-r")

Notice the channel name has a pound sign in front of it. If you want to send someone a private message, set the channel to their Slack name with an @ sign in front.

slackr_msg(paste("Now I'm sending a private message at", 
Sys.time()), channel = "@sharon_machlis")

It’s also easy to send an image or other file with the slackr_upload() command. As I did in the last “Do More With R” episode (“How to send email from R and Gmail”) I’ll create a graph of monthly U.S. unemployment data and save it to the file unemployment_graph.png. (That’s not the important part. I just need a break from mtcars and iris sample data.) 

The code below first sends a text message to Slack, followed by uploading the file.

pacman::p_load(quantmod, glue, xts, dplyr, ggplot2)
getSymbols("UNRATE", src="FRED")
unemployment <- coredata(UNRATE)
month_starting <- index(UNRATE)
series_length <- length(unemployment)
latest_msg <- glue("The latest US unemployment rate was {unemployment[series_length]},
in the month starting {month_starting[series_length]}.
That's {unemployment[series_length] - unemployment[series_length - 1]}
percentage points difference from the prior month.")
un_df <- data.frame(month_starting, unemployment) %>%
filter(month_starting >= as.Date("2000-01-01")) %>%
rename(unemployment = UNRATE)
mygraph <- ggplot(un_df, aes(month_starting, unemployment)) +
geom_line() +
ggtitle("US Monthly Unemployment") +
xlab("Month Starting") +
ylab ("")
ggsave("unemployment_graph.png")
msg_text <- glue("The latest US unemployment rate was {unemployment[series_length]}, in the month starting {month_starting[series_length]}. That's {unemployment[series_length] - unemployment[series_length - 1]} percentage points difference from the prior month. Here's a graph of the data since January 2000:")
slackr_msg(msg_text, channel = "#slack-from-r")
slackr_upload("unemployment_graph.png",
"US Monthly Unemployment Since Jan 2000",
channels = "#slack-from-r")

There you have it: Slack messages directly from an R script.

For more R tips, head to the “Do More With R” video page on InfoWorld or check out the “Do More With R” YouTube playlist.

Copyright © 2019 IDG Communications, Inc.

How to choose a low-code development platform