Retrieving cached oauth token with packages httr,

2020-07-17 02:10发布

The only way I've found to get myself authenticated with the twitter API is the following:

library(twitteR)

setup_twitter_oauth(consumer_key = "a", 
                consumer_secret = "b", 
                access_token = "c", 
                access_secret = "d")

After running this, I can use all functions in twitteR just fine. However, I would also like to use the streamR package, which needs the token as an OAuth object:

filterStream("tweets.json", track = c("Obama", "Biden"), timeout = 20, oauth=my_oauth)

From what I gather, the setup_twitter_oauth function above is a wrapper around some httr functions to get my authorization token. This token is cached in my working directory as a file called ".httr-oauth". My question is: how do I load this file into R, such that I get an OAuth object that I can use with streamR?

2条回答
混吃等死
2楼-- · 2020-07-17 02:47

This is a hack and doesn't directly retrieve the OAuth object from setup_twitter_oauth , but it works (adapted from http://www.datablog.sytpp.net/2014/04/scraping-twitter-with-r-a-how-to/).

Do the below once after you've setup your consumer_key and consumer_secret

    twitCred <- OAuthFactory$new(consumerKey=consumer_key,
    consumerSecret=consumer_secret,
    requestURL="https://api.twitter.com/oauth/request_token",
    accessURL="https://api.twitter.com/oauth/access_token",
    authURL="http://api.twitter.com/oauth/authorize")
    twitCred$handshake()
    save(twitCred, file="credentials.RData")

When mixing TwitteR and streamR, use twitCred as the OAuth for streamR calls

    twitCred<- NULL
    load("credentials.RData")

Sample test streamR call to retrieve Tweets relating to football

    foo<- filterStream(file.name="",track =c("Football","NFL"),oauth=twitCred,timeout=30)
查看更多
唯我独甜
3楼-- · 2020-07-17 02:49

Use readRDS()

readRDS('.httr-oauth')
$xxxx0x000xxxx00000x0xx0x000000xx


 request:   https://api.twitter.com/oauth/request_token
 authorize: https://api.twitter.com/oauth/authenticate
 access:    https://api.twitter.com/oauth/access_token
 twitter
  key:    xxxxxxxxxx0xxxxxxxxxxxxxx
  secret: 
 oauth_token, oauth_token_secret, user_id, screen_name

Access the environment in the list through $long-alphanumeric-hash and within that access $credentials and $oauth_token/$oauth_token_secret

查看更多
登录 后发表回答