Retrieving cached oauth token with packages httr, twitteR, and streamR - r

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?

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

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)

Related

LinkedIn API error of redirect uri from httr

I'm trying to access LinkedIn's API using R and the httr package.
When I execute the last oauth2.0_token() function, in order to gain an authorization token, I get the following error from LinkedIn: "The redirect_uri does not match the registered value".
I've set my redirected url on the LinkedIn Developer site to http://my_app_54321
Does anyone know what the solution is?
# Packages
library(httr)
# Client info
clientid <- "my_id"
secret <- "my_secret"
# App
app <- oauth_app(appname = "app name", key = clientid, secret = secret)
# Endpoints
endpoint <- oauth_endpoint(base_url = "https://www.linkedin.com/uas/oauth2",
authorize = "authorization", access = "accessToken")
# Access token
token <- oauth2.0_token(endpoint = endpoint, app = app)
token
Changing my redirected url to the following solved it since I just needed the application to run locally.
http://localhost:1410/
The comments from the GitHub of httr package pointed in this direction:
https://github.com/r-lib/httr/blob/master/demo/oauth2-linkedin.r

API in R & Ravelry

I'm trying to use the Ravelry API to do some data analysis and I'm having difficulties.
I'm modeling my code after this link but I'm afraid this blog may have been written before there were different kinds of permissions on the Ravelry API.
I have a OAuth 1.0a API with a text file with my username, key, and secret
library(httr)
# user_rav.txt contains API username and password
credentials <- readLines("user_rav.txt")
names(credentials) <- c("user","access_key","secret_key")
OpenConnection <- function(credentials){
# Args: login info for the Ravelry API
# Returns oauth token
# Open connection to Ravelry API and return token
reqURL <- "https://www.ravelry.com/oauth/request_token"
accessURL <- "https://www.ravelry.com/oauth/access_token"
authURL <- "https://www.ravelry.com/oauth/authorize"
ravelry.app <- oauth_app("ravelry", key=credentials["access_key"],
secret=credentials["secret_key"])
ravelry.urls <- oauth_endpoint(reqURL, authURL, accessURL)
return(oauth1.0_token(ravelry.urls, ravelry.app))
}
# Quick test of API connection by getting connected user info
TestConnection <- function(ravelry.token) {
# Arg: API token
# Returns name of the user connected with this token
test <- GET("https://api.ravelry.com/current_user.json",
config=config("token"=ravelry.token))
print(content(test)$user$username)
}
ravelry.token <- OpenConnection(credentials)
The last line, "ravelry.token <- OpenConnection(credentials)" produces this error:
Error in init_oauth1.0(self$endpoint, self$app, permission = self$params$permission, :
Internal Server Error (HTTP 500).
I've googled this error and, if you can believe it, there were only four hits. two weren't avaliable and the others were specific to an R package with the API that i'm not using.
I would appreciate any help.
I apologize. It was something as simple as the column heads in the credential file that needed to be edited.

Trouble receiving data from Twitter in R

I want to get data from a tweet.
But these are the errors.
Please help me get data?
by code
install.packages("rtweet")
library(rtweet)
# plotting and pipes - tidyverse!
library(ggplot2)
library(dplyr)
# text mining library
library(tidytext)
# whatever name you assigned to your created app
appname <- "**********"
## api key (example below is not a real key)
key <- "**************"
## api secret (example below is not a real key)
secret <- "***********"
twitter_token <- create_token(
app = appname,
consumer_key = key,
consumer_secret = secret)
rstats_tweets <- search_tweets(q = "#rstats",
n = 500)
Error in check_twitter_oauth (): OAuth authentication error:
This most likely means that you have incorrectly called setup_twitter_oauth () '
Error in curl :: curl_fetch_memory (url, handle = handle):
Timeout was reached: Connection timed out after 10,000 milliseconds
The documentation claims:
API authorization
The first time you make an API request—e.g., search_tweets(), stream_tweets(), get_followers()—a browser window will open.
Log in to your Twitter account.
Agree/authorize the rtweet application.
And that’s it!
However, this did not work for me.
I had to follow the rtweet tutorial how obtaining and using access tokens:
# install from CRAN
install.packages("rtweet")
# load rtweet
library(rtweet)
I also had to install the httpuv package. This is not mentioned in the tutorial but you get a corresponding error message in R.
Error in oauth_listener(authorize_url, is_interactive) :
httpuv package required to capture OAuth credentials.
install.packages("httpuv")
Then Create your Twitter app with the correct Callback URL on apps.twiter.com:
To create a Twitter app, navigate to apps.twitter.com and create a new app by providing a Name,
Description, and Website of your choosing (example screenshot provided
below).
Important In the Callback URL field, make sure to enter the following: http://127.0.0.1:1410
Check yes if you agree and then click “Create your Twitter application”.
## whatever name you assigned to your created app
appname <- "rtweet_token"
## api key (example below is not a real key)
key <- "XYznzPFOFZR2a39FwWKN1Jp41"
## api secret (example below is not a real key)
secret <- "CtkGEWmSevZqJuKl6HHrBxbCybxI1xGLqrD5ynPd9jG0SoHZbD"
## create token named "twitter_token"
twitter_token <- create_token(
app = appname,
consumer_key = key,
consumer_secret = secret)
then, finally, a browser window opened after this code is executed (something like the following):
http://localhost:1410/?oauth_token=asdfasdfasdfaf5naw&oauth_verifier=dffasdfsdfsdfsdfsdfsk9jIQxDG6
showing the message:
Authentication complete. Please close this page and return to R.
and now you should be good to go.
See also:
https://developer.twitter.com/en/docs/basics/authentication/overview/oauth

Connecting to Bing API

I am looking to use Bing API to extract data in R. When I am using the following query in my browser
https://api.datamarket.azure.com/Bing/Search/Web?Query=%27analytics%27&$format=json
I am getting the search results in json format. But I have to enter the UserID (Blank) and password (authorization token) for authorization first.
How can I merge the query with the authorization token in R so that I can directly load the search results in my R environment?
You can use authenticate function as a part of httr package:
library(httr)
response = GET(url = 'https://api.datamarket.azure.com/Bing/Search/Web?Query=%27analytics%27&$format=json',
authenticate('','auth token', type = 'basic'))
res = content(response, encoding = 'json')

How to save twitter authentication credentials for repeated use in a shiny application?

I am new to R and Shiny
I am trying to create a simple shiny app that extracts tweets related to a search term from the twitter api.
In R Studio,
To access twitter api for tweets, I run the following for authentication.
> consumer_key<-'value1'
>consumer_secret<-'value2'
> access_token<-'value3'
> access_secret<-'value4'
> setup_twitter_oauth(consumer_key, consumer_secret, access_token,access_secret)
Only after above four lines I can do the actual search as shown below
tweets<-searchTwitter(search_term,n= input_number,since=start_date, until =end_date, lang= 'en')
(
i.e all the values to the variables in the searchTwitter() function are taken from the user)
Is there someway I could save the authentication credentials so that the app can always be online(running), and the credentials be loaded as and when a search is carried out.
Thanks.
This may not be the best way but
setup_twitter_oauth(consumer_key = "yourkey", consumer_secret = "yoursecret")
token <- get("oauth_token", twitteR:::oauth_cache)
token
Gives
<Token>
<oauth_endpoint>
request: https://api.twitter.com/oauth/request_token
authorize: https://api.twitter.com/oauth/authenticate
access: https://api.twitter.com/oauth/access_token
<oauth_app> twitter
key: xxxx
secret: <hidden>
<credentials> oauth_token, oauth_token_secret, user_id, screen_name, x_auth_expires
---
Then cache it
token$cache()

Resources