401 Unauthorized error using streamR

645 Views Asked by At

I am trying to connect to twitter's streaming API using streamR and the required ROAuth package. I follow the exact procedure from the documentation here, but when I have finished all the steps with no errors I receive a 401 Unauthorized error when callingfilterStream or sampleStream.

Here are the steps that appear to work fine:

library(ROAuth)
library(streamR)

requestURL <- "https://api.twitter.com/oauth/request_token"
accessURL <- "https://api.twitter.com/oauth/access_token"
authURL <- "https://api.twitter.com/oauth/authorize"
consumerKey <- "--redacted--"
consumerSecret <- "--redacted--"

my_oauth <- OAuthFactory$new(consumerKey = consumerKey, 
                             consumerSecret = consumerSecret, 
                             requestURL = requestURL, 
                             accessURL = accessURL, 
                             authURL = authURL)

my_oauth$handshake(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl"))

When I run the final line a browser window is opened which asks me to authorize the app to use my twitter account. When I click to authorize a PIN appears which I am copy/pasting into Rstudio after the prompt reading "When complete, record the PIN given to you and provide it here:"

After running the above lines, I am sending a call like this to filterStream: filterStream(file.name = "test_tweets.json", track = c("sat"), timeout = 120, oauth = my_oauth)

The generated file test_tweets.json reads: Problem accessing '/1.1/statuses/filter.json'. Reason: Unauthorized

To resolve the problem I have tried creating a new twitter app, updating R and all packages. None of these actions produced any differing results. Additionally, I tried the same credentials with the twitteR package, which worked fine, but unfortunately I need to connect to the streaming api which is not available through the twitteR package. Any tips greatly appreciated!

Note this question is related to, but different from, this unanswered question.

2

There are 2 best solutions below

0
On

You need to regenerate your customerKey and customerSecret when you change your twitter permissions from Read - Write to Read-Write and Direct Messages.

0
On

For whatever reason, creating a new twitter account fixed this problem; but only after I had associated my phone with the account AND checked all the boxes in the mobile notifications section. Bizarre, but it worked. After I got it working I was able to uncheck the notifications and it still worked.

You, reader, fellow mysterious-error-receiver, are not alone: http://xkcd.com/979/