Saturday, July 18, 2015

How to tweet using R

This blog post intends to teach you to POST tweets using R. Obviously this is to some Twitter account that you either own or can get access to. You will need to get hold of the authentication credentials to post to this account as detailed here

So onto the R scripting.
I found that I needed the following packages.

install.packages("httr")
install.packages("rjson")
install.packages("base64enc")
install.packages("Unicode")

library("httr")
library("rjson")
library("base64enc")
library("Unicode")



  • With that out of the way - we now need to authenticate into our account.
  • If you have just the Twitter account you need to get hold of a Twitter Application Account.
  • Create an application with whatever name you please and associate it with your twitter account.
  • Go to "Keys and Access Tokens" - You must have the "Consumer Key (API Key)" and the "Consumer Secret (API Secret)" populated already.
  • You will need to create the "Access Tokens" which will give you the Access Token (named as "Public-Token" in the R script) and the Access Token Secret (named as Private-Token)
  • With these authentication entities we are ready to use OAuth to authenticate into our account from other places on the web.



You create a signature to be used in the HTTP GET/POST requests. The HTTP POST request that we use needs this signature. Note that we use OAuth 1.0 here.

myapp = oauth_app("twitter", key="Consumer Key (API Key)", secret="Private-Key")
sig = sign_oauth1.0(myapp, token="Public-Token", token_secret = "Private-Token")

Next we create our tweet itself:

twit <- URLencode("Thanks! Bulla_ki_Jaana First #Twitter Post")
paste("https://api.twitter.com/1.1/statuses/update.json?status=", twit,sep='')
POST(url, sig)

The POST response should indicate the HTTP Status of 200 indicating Success. A Status code of 400 usually means that the authentication credentials were not presented to Twitter correctly.

You should log on to your Twitter account and check that your tweet appeared as intended.