Skip to content

Instantly share code, notes, and snippets.

@arcaravaggi
Created August 31, 2017 11:30
Show Gist options
  • Save arcaravaggi/bd4b99a5f006c999e9290fbd73637ec8 to your computer and use it in GitHub Desktop.
Save arcaravaggi/bd4b99a5f006c999e9290fbd73637ec8 to your computer and use it in GitHub Desktop.
Create a series of tweets from one text string.
# if tweetnow is set to TRUE, sends the tweets directly from R to Twitter
# this function requires installing the rtweet package and setting up the relevant
# Twitter user credentials
# otherwise, the tweetstorm outputs to the console; the user can copy/paste to Twitter manually
#
# From https://sites.tufts.edu/emotiononthebrain/2017/08/12/time-for-a-tweetstorm/
tweetstorm <- function(s, tweetnow = FALSE) {
#if you'll be tweeting directly from R, update the user name and token variables
# (no need to update these variables if you won't be tweeting directly from R)
self_user_name <- "YourTwitterHandle"
token <- "YourAccessToken"
#################################################################
s1 <- paste(strwrap(s,134), collapse="\n")
s2 <- strsplit(s1, "\n")
numlines <- length(s2[[1]])
index <- 1:numlines
if(tweetnow==FALSE){
counter <- paste(" ",index,"/",numlines,"\n\n")
counter <- gsub(" ","",counter)
counter <- gsub("n/"," n/",counter)
storm <- paste(strwrap(s2[[1]][index],140-max(index)+2+nchar(max(index))), counter[index])
cat(storm)
}
if(tweetnow==TRUE){
counter <- paste(" ",index,"/",numlines)
counter <- gsub(" ","",counter)
counter <- gsub("n/"," n/",counter)
storm <- paste(strwrap(s2[[1]][index],140-max(index)+2+nchar(max(index))), counter[index])
library(rtweet)
post_tweet(storm[1])
for (i in 2:length(storm)){
my_timeline <- get_timeline(self_user_name, n=1)
reply_id <- my_timeline[1,]$status_id
post_tweet(status=storm[[i]], in_reply_to_status_id=reply_id)
}
}
}
tweetstorm("",tweetnow=FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment