Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

r - Automated httr authentication with twitteR , provide response to interactive prompt in "batch" mode

I am using the R package twitteR to post items to Twitter. I put everything inside of a function and it works fine. However, I would like to run the function without being prompted for a response, and I haven't figured out how to do that. Any suggestions?

Here are the bare bones of my function:

doit <- function(<snip>) {
    <snip>
    # connect to Twitter
    setup_twitter_oauth(api_key, api_secret, access_token, access_token_secret)
    <snip>
    }

When I run the function from the command line, I am prompted for an interactive response.

[1] "Using direct authentication"
Use a local file to cache OAuth access credentials between R sessions?
1: Yes
2: No

Selection: 

I can provide this information directly in a script when the setup_twitter_oauth() function is outside of a function, by entering my response in the following line, much like can be done for other user input functions like readline() or scan().

setup_twitter_oauth(api_key, api_secret, access_token, access_token_secret)
1

However, I haven't been able to get this approach to work when setup_twitter_oauth() is INSIDE of a function.

I would appreciate any suggestions on how to get this to run without requiring user input.

=====

The answer from @NicE below did the trick. I incorporated the options setting in my function as:

doit <- function(<snip>) {
    <snip>
    # connect to Twitter
    origop <- options("httr_oauth_cache")
    options(httr_oauth_cache=TRUE)
    setup_twitter_oauth(api_key, api_secret, access_token, access_token_secret)
    options(httr_oauth_cache=origop)
    <snip>
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try setting the httr_oauth_cache option to TRUE:

options(httr_oauth_cache=T)

The twitteR package uses the httr package, on the Token manual page for that package they give tips about caching:

OAuth tokens are cached on disk in a file called .httr-oauth 
saved in the current working directory. Caching is enabled if:

The session is interactive, and the user agrees to it, OR

The .httr-oauth file is already present, OR

getOption("httr_oauth_cache") is TRUE

You can suppress caching by setting the httr_oauth_cache option to FALSE.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...