How to interact with Slack from R
Mar 11, 2020
Christopher Yee
2 minute read

I think my tweet speaks for itself:

The goal of this article is to document how to send #rstats code and plots directly to Slack.

Load packages

library(slackr)
library(slackteams)
library(slackreprex)

Slack credentials

Member ID

You can easily grab that from this guide here.

Slack Key ID

To retrieve your Slack key ID, login here and then follow the prompts.

API token & webhook

Last but not least, we can now use our newfound credentials and insert them into the following URL:

https://slackr-auth.herokuapp.com/creds/MEMBER_ID/SLACK_KEY_ID

The end result should provide the last pieces of our puzzle for the API token, webhook and the assigned channel for the Slack key ID.

Authenticate

slackrSetup(channel = "#thinktank",
            incoming_webhook_url = "https://hooks.slack.com/services/0123456789",
            api_token = "ABCDEFGHIJKLMNOPQRSTUVWXYZ")

Interacting from R

We’re now ready for a toast test:

slackr("toast test from R")

Even though we selected a specific channel we can easily switch to a different one without going through the entire process again:

slackr("toast test from R", channel = "#warroom")

Sending a plot

Let’s try to recreate a plot I saw awhile back on SEO twitter.

library(dplyr)
library(ggplot2)

technical <- tibble(website_size = seq(0, 100, 1),
                    importance = seq(0, 100, 1)) %>% 
  mutate(segment = "technical")

content <- tibble(website_size = rev(seq(0, 100, 1)),
                  importance = seq(0, 100, 1)) %>% 
  mutate(segment = "content")

df <- rbind(technical, content)

p <- df %>% 
  ggplot(aes(website_size, importance, color = segment)) +
  geom_point() +
  geom_line() +
  labs(color = NULL) +
  theme_light() +
  theme(legend.position = 'top')

Making sure the plot does what we want…

p

…and then beam it up over to Slack:

ggslackr(p)

Too. Easy.

Applications

Nearly 85% of my work communications (internal & client-facing) is completed in Slack so I can think of a few “real world” use cases for this:

  • Automated daily, weekly, monthly reporting
  • Incorporate analyses & insights then publish results directly to Slack
  • Ping the appropriate channels when performance surpasses a statistical threshold
  • Sharing code or final data output without jumping through hoops