Tutorial: How to set up a Twitter bot using R

February 2, 2017
By

(This article was first published on eoda english R news, and kindly contributed to R-bloggers)

On occasion of the 10,000th R package on CRAN, eoda operated an automated Twitter account which regularly posted the current number of packages available on CRAN until the 10,000-package milestone has been passed on January 28, 2017.

To operate this account, we wrote an R script for reading the current number of R packages on CRAN every hour and automatically sending a Tweet with the status quo. All we needed to make this work was the Twitter API as well as the twitteR package.

For using the Twitter API, it is necessary to create a corresponding app for the Twitter account.

For this, log in with the respective account on apps.twitter.com and fill out the form under Create New App.

Einrichten einer Twitter App auf apps.twitter.com
Creating a Twitter app on apps.twitter.com

In the next window, you can set among other things the permissions of the app, “read only”, “read and write” or “read, write and access direct messages”. To operate the app, you also need the Consumer Key and Consumer Secret as well as the Access Token and Access Token Secret you can find in the tab Key and Access Tokens.

Application Settings
Application Settings
Access Token
Access Token

We transferred this information into an extra file in order to be able to load them into the R script later on. Now the app is ready for use.

For sending Tweets out of R, you need the functions setup_twitter_oauth and tweet from the twitter package. The function setup_twitter_oauth manages the authentication and tweet finally sends the appropriate Tweet.

The following R script demonstrates how we applied this to our Rstatsgoes10k account:

# Packages ----------------------------------------------------------------

library(rvest)
library(stringr)
library(dplyr)
library(twitteR)


# get number of packages --------------------------------------------------

url < - "https://cran.r-project.org/web/packages/"


page <- read_html(url)

n_packages <- page %>%
  html_text() %>% 
  str_extract("[[:digit:]]* available packages") %>% 
  str_extract("[[:digit:]]*") %>% 
  as.numeric()

n_packages_last_time < - read.table(file = "n_packages.csv",stringsAsFactors = F, sep = ";")

n_packages_last_time <- n_packages_last_time$V2[nrow(n_packages_last_time)]

## check if news packages are published, new tweet only when number of packages changed
if(n_packages > n_packages_last_time) {
  
  # Twitter -----------------------------------------------------------------
  
  # set up twitter api
  api_keys < - read.csv2("twitter_access.csv", stringsAsFactors = FALSE)
  
  setup_twitter_oauth(consumer_key = api_keys$consumer_key,
                      consumer_secret = api_keys$consumer_secret,
                      access_token = api_keys$access_token,
                      access_secret = api_keys$access_secret)
  
  
  
  time <- Sys.time()
  
  # create tweet
  tweet_text <- paste0("#Rstatsgoes10k - Hello World, it's ", time, " and currently there are ", n_packages, " packages on CRAN. ")
  
  # send tweet
  tweet(tweet_text)
  
  
  # write n to file ---------------------------------------------------------
  
  n_packages_df <- data.frame(time = Sys.time(), n = n_packages)
  
  write.table(n_packages_df, file = "n_packages.csv", row.names = FALSE,col.names = FALSE,
              append = TRUE, sep = ";")
  
}

To leave a comment for the author, please follow the link and comment on their blog: eoda english R news.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)