Using R to send tweets

2019-01-28 11:35发布

I saw a cute demonstration of tweeting from R in a presentation some months ago. The scratch code used by the presenter is here:

http://www.r-bloggers.com/twitter-from-r%E2%80%A6-sure-why-not/

the code is short and sweet: library("RCurl") opts <- curlOptions(header = FALSE, userpwd = "username:password", netrc = FALSE)

tweet <- function(status){
  method <- "http://twitter.com/statuses/update.xml?status="
  encoded_status <- URLencode(status)
  request <- paste(method,encoded_status,sep = "")
  postForm(request,.opts = opts)
}

With this function, you can send a tweet simply by using the update function:

tweet("This tweet comes from R! #rstats")

I thought that this could be a useful way of announcing when long jobs are completed. I tried to run this on my machine, and I got some error:

[1] "\n\n Basic authentication is not supported\n\n" attr(,"Content-Type") charset "application/xml" "utf-8" Warning message: In postForm(request, .opts = opts) : No inputs passed to form

I'm wondering if there has been some changes on the twitter end of this, that make this code produce this error? I don't know too much about getting R to talk to webpages, so any guidance is much appreciated!!

E

标签: r twitter
4条回答
Bombasti
2楼-- · 2019-01-28 11:53

Yes, the basic authentication scheme was disabled on the 16th August 2010.. You'll need to set it up to use OAuth. Unfortunately that is not nearly as simple as using basic authentication

See this twitter wiki page for more information and this StackOverflow question about OAuth for R.

查看更多
何必那么认真
3楼-- · 2019-01-28 11:59

The easiest way to tweet in R through the Twitter-API is to use the twitteR Package. You can set your Twitter-API-APP here: https://apps.twitter.com/

First step is to authenticate:

consumer_key <- "yourcredentials"
consumer_secret <- "yourcredentials"
access_token <- "yourcredentials"
access_secret <- "yourcredentials"
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)

And just tweet (limit per day:2400 tweets):

tweet("Hello World")
查看更多
劫难
4楼-- · 2019-01-28 12:09

If twitteR does not work or you simply want to try to build it yourself ...

See here for a demo of how to do your own Twitter authentication and use of the API with help of the httr package.

查看更多
Emotional °昔
5楼-- · 2019-01-28 12:15

Besides the code you show, there is also a full-blown twitteR package on CRAN you could look at.

查看更多
登录 后发表回答