How to program a Twitter bot

26 Nov

I have made many “Tweet bots” over the last year, but I’m just now getting around to sharing.

One of the simplest ones I have created is the “current conditions” auto-tweet. It  simply scrapes the weather observation data from the NWS website and then tweets it out.

I have the R script set up to run in batch mode a couple of times a day (times specified by me in my Task Scheduler).

tweetbot

 

You must first create an app in Twitter via the Twitter Developer Website.

You must then obtain a consumer key and secret. Here is a good how-to.

Play around with the R Twitter package (twitteR) and familiarize yourself with its functions.

I use the httr package for Twitter Authentication.


###
###This script will scrape the latest conditions from the NWS for KPBI and
###tweet out the current conditions including an image of sky cover.
###

###Have to first go through all the twitter stuff:
require(twitteR)
library(httr)
library(stringr)
library(rvest)
require(httpuv)

#detach("package:Rfacebook", unload=TRUE)

# returns string w/o leading or trailing whitespace
trim <- function (x) gsub("^\\s+|\\s+$", "", x)

setwd("C:/Users/Lisa/Desktop/facebook") #setting this folder as directory bc that is whwere the facebook/twitter api stuff is.


api_key             <- "ABC123"
api_secret          <- "YOURSECRET123"
access_token        <- "ZYZ123"
access_token_secret <- "BLAHBLAHBLAH123"

options(httr_oauth_cache = TRUE)
#install_github("twitteR")

httr:::guess_cache()
httr:::use_cache()
getwd()

# 1. Find OAuth settings for twitter:
#    https://dev.twitter.com/docs/auth/oauth
oauth_endpoints("twitter")

# 2. Register an application at https://apps.twitter.com/
#    Insert your values below - if secret is omitted, it will look it up in
#    the TWITTER_CONSUMER_SECRET environmental variable.
#    Make sure to set callback url to "http://127.0.0.1:1410"
myapp <- oauth_app("twitter", key = api_key, secret=api_secret)

# 3. Get OAuth credentials
#options(httr_oauth_cache=T)
twitter_token <- oauth1.0_token(oauth_endpoints("twitter"), myapp)

# 4. Use API
req <- GET("https://api.twitter.com/1.1/statuses/home_timeline.json",
           config(token = twitter_token))
stop_for_status(req)
#content(req)

# 5. Get authorization
setup_twitter_oauth(api_key, api_secret, access_token)



##############
############## Now scrape the NWS data
##############
#This function takes in a vector and returns the very last 
get.first.last <- function(x){
  length <- length(x)
  return(c(x[1],x[length]))
}


#library(gdata) #for dropping levels.
library(XML) #for html scraping.

theurl   <- "http://w1.weather.gov/data/obhistory/KPBI.html"
#tables  <- readHTMLTable(theurl)
doc      <- html(theurl)
tables   <- theurl %>% html() %>% html_nodes(xpath = "/html/body/table") %>% html_table(fill = TRUE)
tables
tables[[4]]

data <- data.frame(tables[[4]], stringsAsFactors = FALSE)
names(data) <- c("date", "time", "wind", "vis", "weather", "sky",
                 "temp", "dp", "6hrmax", "6hrmin", "rh", "windchill", 
                 "heatindex", "altimeter", "sealevel_mb", "precip1", "precip2",
                 "precip3")

num.rows <- nrow(data)

data         <- data[-c(1,2,(num.rows-2):num.rows), ]  #Get rid of first two rows.
new.num.rows <- nrow(data)
data         <- data[(new.num.rows:1),] #re-order data.  Earliest obs first.  

format(Sys.time(), "%a %b %d %X %Y")
month <- format(Sys.time(), "%m")
year  <- format(Sys.time(), "%Y")

date.time <- paste(paste(year, paste(month, paste(data$date), sep = "-"), sep = "-"), 
                   paste(data$time))
#date.time <- as.POSIXlt(date.time)
#date.time <- strftime(date.time, format = "%m-%d-%Y %H:%M")

data$date       <- paste(data$date)
data$temp       <- as.numeric(paste(data$temp))
data$heatindex  <- as.numeric(paste(data$heatindex))

current.weather <- paste(data[nrow(data), ]$weather)
current.temp    <- data[nrow(data), ]$temp
current.dp      <- paste(data[nrow(data), ]$dp)
current.hi      <- data$heatindex[nrow(data)]

###
###Get image
###
url <- "http://forecast.weather.gov/MapClick.php?lat=26.714212397984852&lon=-80.06510906003427"
url <- html(url)
# 
image_url <- url %>%  
  html_nodes("#current-conditions-body img") %>% 
  html_attr("src")

link = paste("http://forecast.weather.gov/", image_url, sep = '')
download.file(link, destfile = "C:/Users/Lisa/Desktop/currents/currents.png", 
              mode = "wb")


#Set some conditions for the text.
if(current.temp >= 90 & current.dp > 69){a <- c("Hot & humid!")}
if(current.temp < 90){a <- " "}


x <- c("Right now:", "Currently:", "Current Conditions:", "Right now weather:")
y <- sample(x, 1) #Choose a phrase at random so it doesn't look like a tweet bot
y

tweet.text <- paste("Right now:", a,
                    current.temp, "degrees", 
                    "&", current.weather, 
                    "in West Palm.",
                    "#flwx")

tweet.text <- trim(tweet.text)
tweet.text

random <- runif(1, 1, 5*60) #wait between 1 second and 5 minutes, just to randomize a little
#Sys.sleep(random)
#updateStatus(tweet.text, 
#            mediaPath = "C:/Users/Lisa/Desktop/currents/currents.png")
#updateStatus(paste(tweet.text, "http://w1.weather.gov/data/obhistory/KPBI.html"))
#updateStatus(paste(tweet.text))
updateStatus(tweet.text, mediaPath = "C:/Users/Lisa/Desktop/currents/currents.png")

Once you’ve got this done, you’ll need to set up a batch file. I do this by creating a new R script (within Rstudio) and typing the following:

"C:\Program Files\R\R-3.1.2\bin\x64\R.exe" CMD BATCH "C:\Users\Lisa\Desktop\currents\currents.r"

Then, save this file as a ‘.bat’ file instead of a ‘.r’ file – this is very simple to do in Rstudio. (I don’t know about the R console…)

It is this ‘.bat’ file that you will want to trigger using your computer’s task scheduler.

Advertisements

3 Responses to “How to program a Twitter bot”

  1. Bot@gmail.com December 3, 2015 at 7:46 pm #

    Or use one already finished

  2. RONAK SHAH . May 23, 2016 at 6:19 pm #

    How can I keep this bot alive 24 X 7. The problem with task scheduler is that it runs only when my system is on and not otherwise. How can I keep it online along with some time scheduler?

    • weatherlisa May 26, 2016 at 7:37 pm #

      Unfortunately I’m not sure. I keep my computer running constantly. 😏

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

MEAGHAN THOMAS

BROADCAST METEOROLOGIST

%d bloggers like this: