Twitter API v2.0 DELETE request using httr and R - r

With little experience in API programming, I am looking for a way to send a DELETE or POST request using the Twitter API v2.0 with the httr package in R. I usually use the academictwitteR package to interact with the API, but the package uses a bearer token authentication that seems to me to not be adequate for write privileges (required by DELETE and POST). Therefore, it seemed that the first step is setting up the OAuth 1.0a authentication credintials as described here. I downloaded and stored the four variables (oauth_token; oauth_token_secret; oauth_consumer_key; oauth_consumer_secret) from the app I created, but then I am stuck as to how to set up the request with httr.
I can't provide an example since I could not figure out the code, I hope you understand. Any help is much appreciated!

Not sure about your specific requirements and what you tried before.
Would it be a solution to just use the rtweet package?
It is quite handy and offers quite a lot of functions to interact with the twitter api(also posting and deleting tweets possible)
E.g.
#Posting
post_tweet("hello world")
#Following
post_follow("someuser")
# Not sure about deleting, but should work like this
post_tweet(destroy_id= "postID")
To get you post ID to delete it, you can get maybe use get_my_timeline. This should give your posts with ids.
See here in the vignette for a short intro about functions.
Of course you also need an access token first.
They have a very good explanation page on how to do this. Also a FAQ for problems. The explanation is rather long and probably too specific to go through in detail here. But would be interesting to know if it works for you.
Further things:
Make sure you have httpuv installed
Be sure to have the very latest rtweet version (best is from github I think)
Also check the following: Go to developer.twitter.com/en/apps and then to your app. Under 'Permissions' make sure to give Read and Write. Under 'App Detail' add 127.0.0.1:1410 as Callback Url. Under 'Keys and tokens' create your Keys
Regenerate your tokens/keys
So try this:
install.packages("httpuv")
devtools::install_github("mkearney/rtweet")
library(rtweet)
library(httpuv)
create_token(
app = appname,
consumer_key = key,
consumer_secret = secret,
access_token = access_token,
access_secret = access_secret
)
Update
I just saw, on the very latest version in github they completely changed their methods and create_token is now depreciated.
Here is the new way to do it: documentation
So seems you habe to use rtweet_bot() now.
library("askpass")
rtweet_bot(
api_key = askpass("API key"),
api_secret = askpass("API secret"),
access_token = askpass("access token"),
access_secret = askpass("access token")
)
The rest of the code I posted should stay the same.
In general it seems there are 3 ways of authenticating now:
rtweet_user() interactively authenticates an existing twitter user.
This form is most appropriate if you want rtweet to control your
twitter account.
rtweet_app() authenticates as a twitter application. An application
can't perform actions (i.e. it can't tweet) but otherwise has
generally higher rate limits (i.e. you can do more searches). See
details at
https://developer.twitter.com/en/docs/basics/rate-limits.html. This
form is most appropriate if you are collecting data.
rtweet_bot() authenticates as bot that takes actions on behalf of an
app. This form is most appropriate if you want to create a twitter
account that is run by a computer, rather than a human.

I looked at the curl examples for DELETE and POST requests you provided. They are rewrotten in R below. You need to replace the $OAUTH_SIGNATURE though. Please let me know if it works for you as I cannot check the code as I do not have a Twitter account nor do I have the OAuth token.
library(httr)
r <- DELETE(url = "https://api.twitter.com/2/users/2244994945/following/6253282",
add_headers('Authorization'= 'OAuth $OAUTH_SIGNATURE'))
content(r)
r <- POST(
url = "https://api.twitter.com/2/users/6253282/following",
body = c("target_user_id" = "2244994945"),
add_headers('Authorization'= 'OAuth $OAUTH_SIGNATURE'),
content_type_json()
)
content(r)

Related

Is the rfacebookstat package secure?

Full disclaimer - I'm a bit of an API noob and I don't have much experience with OAuth or token authorization in general.
I see that the rfacebookstat package is on CRAN but I'm in particular concerned about the following function:
function(
app_id = NULL,
scopes = c("ads_read", "business_management", "pages_manage_ads", "ads_management", "public_profile") ){
if(is.null(app_id)) stop("Enter your app id.")
scopes <- paste(scopes, collapse = ",")
utils::browseURL(paste0("https://www.facebook.com/dialog/oauth?client_id=",app_id ,"&display=popup&redirect_uri=https://selesnow.github.io/rfacebookstat/getToken/get_token.html&response_type=token&scope=",scopes))
token <- readline(prompt = "Enter your token: ")
options(rfacebookstat.access_token = token)
return(token)
}
I see there's a redirect to the package creator's personal github site and that makes me a bit nervous. From the .R file I see that this is needed in order to convert the short time token into a long time token - does this represent a security concern? Anyone else have experience with this package? Want to use but I also don't want to leak any campaign data externally.
Alternatively, if I were to write my own wrapper of the above function, could I use localhost as the redirect URI? I just need to query the API to pull historical campaign data, the script I'm writing isn't for any webapp.

Using httr in R to establish an implicit Oauth2 flow with StackOverflow.com

I am trying to establish an "implicit" Oauth2 authorization flow for my test connect in R to StackOverflow via the StackExchange API.
I am in situation #3 of this related post, that specifies how to set the redirect_uri and other values in a lanugage-agnostic way.
I've taken the steps described, namely setting up the app on StackApps.com to enable implicit authentication.
I've replicated the linked instructions in R with the httr library, the only major adaptation is that apparently httr requires the client secret earlier in the process than StackOverflow actually requires it.
library(httr)
# in the StackApps answer stackoverflow.com was used here.
# that just took me to the landing page.
# the docs use this URI and it gets me closer but
# it just says "Authorizing Application" with a blank page under that
# and it never completes.
end <- oauth_endpoint(authorize = "stackoverflow.com/oauth",
access = "stackoverflow.com/oauth")
client_secret = "secret_code_here"
myapp <- oauth_app("myapp",
key = "12665", # not a secret
secret = client_secret,
redirect_uri="https://stackexchange.com/oauth/login_success")
token <- oauth2.0_token(end,
myapp,
scope=NULL)
#,use_oob=T)
When I run my code a browser automatically opens and goes to StackOverflow.com. However, it just takes me to the landing page and Oauth never completes.
I tried it with use_oob=T and the only difference was that R prompted me for an authorization code that was never provided.

Are there new facebook restriction for Rfacebook package?

I want to get some data from Facebook, so I wanted to create application to get token for 60 days like I did few months ago. Then everything worked well, I just followed steps from the tutorial like this:
http://thinktostart.com/analyzing-facebook-with-r/
So It was enough to create "empty" application, write in R with proper id and secret
fb_oauth <- fbOAuth(app_id="123456789", app_secret="1A2B3C4D",extended_permissions = TRUE)
fill website page as http://localhost:1410/ and autenthication was complete and I was able to make get some data from facebook. It seems that it is not so easy anymore.
When I try to follow exactly the same steps it seems that now I have to fill in my application (with some description, photos...) and "send" it to submission.
Do you have similar problem or I just miss something? I just want to use information from facebook for my own use, not for business or something. Is there any (other) way to get a token for R which allows me to get some information from Facebook without filling application. I don't think that filling it with some fake data will pass facebook verification.
I just want to use information from facebook for my own use
Then you don’t need to submit it for review.
See https://developers.facebook.com/docs/apps/faq#roles – it explains that you can ask any user that has a “role” in the app (meaning admin, developer or tester) for any permission without prior review.
For one, this is of course implemented this way, so that people can actually test the functionality they are developing properly. And it is also an “official loophole” for apps such as yours, that are for “private use” only, and not meant to be used by the general public in the first place.
(And this has nothing whatsoever with the Rfacebook package – it is the same for all apps, no matter what framework/SDK they might be using.)
UPDATE
As #CBroe said earlier, you do not need an approved app, you just need to add the users of the app as admin in the app's role menu in Facebook Developers.
Follow these steps and you will get your permanent FB token:
Create new application at https://developers.facebook.com/apps/ with basic setup
Fill in the app name in lower case and without the words Facebook or FB for display name and namespace, category set to Business
In "Settings/Basic" I added a new "Website" platform with the URL of http://localhost:1410/ and localhost as the "App Domain"
In the "Settings/Advanced" tab I added http://localhost:1410/ as the Valid OAuth redirect URIs
Then, run this code:
library(httr)
app <- oauth_app('facebook', appid, appsecret)
Sys.setenv("HTTR_SERVER_PORT" = "1410/")
tkn <- oauth2.0_token(
oauth_endpoints('facebook'), app, scope = c('ads_management', 'read_insights'),
type = 'application/x-www-form-urlencoded', cache = FALSE)
save(tkn, file = "~/Documents/RFiles/fb_token") # save the token for future use
Make sure you put 'read_insights' in scope, otherwise you are not telling Facebook what kind of permissions you want the app to take.
Finally you can use the token:
library(Rfacebook)
load("~/Documents/RFiles/fb_token")

Don't see .httr-oauth file after use of setup_twitter_oauth; want to use it to work with StreamR

I am trying to use setup_twitter_oauth authentication (from TwitteR package) to later on run StreamR search.
There is a related question in Stackoverflow about the same subject -
Retrieving cached oauth token with packages httr, twitteR, and streamR
However my problem that I don't see .httr-oauth file in my working directory
The code I use to establish connection with Twitter is below
setup_twitter_oauth(consumer_key, consumer_secret, access_token=NULL, access_secret=NULL)
(I use proper keys from my registered Twitter App)
It works I am getting [1] Using direct authentication message after execute it.
However there is no file called .httr-oaut in my work directory. Other hidden files are visible.
getOption("httr_oauth_cache") returns TRUE
What am I doing wrong and how can I get this file and use it in the future to establish connection with Twitter using StreamR, like for example in the command below
filterStream( file="tweets_rstats.json", track="rstats",
locations=c(-74,40,-73,41), timeout=600, oauth=my_oauth)
As I understood I need to pass it as oauth, so need in some way to save the token in my_oauth variable
Any help is appreciated

OAuth2 GitHub API token

I have a Client ID and Client Secret after having set up an application in github, I'm not sure what the URL or the callback URL is meant to be for that...which i think is causing me problems
I also have a private repo that I would like the application to access...
The way I would like to access the private repo would be via R, so I have found some packages that might help including ROAuth and oauth, but I'm not too sure how to go about using these to get the tokens, as they tend to require a bunch of URLs to make the requests from, and I am unsure as to what the URLs are to get these requests for tokens.
Looking at http://developer.github.com/v3/oauth/ doesn't seem to be amazingly helpful in terms of my inputs for oauth or Oauth2Authorize functions for each of the respective packages.
The end goal is to source files from the private repo, since source_url('private.repo.file.url') doesn't work
I tried the basic authentication using curl through bash, but wasn't able to find a token.
Any walkthrough examples of how to go about doing this would be greatly appreciated.
P.S. this is a follow up question from r sourcing private repos from github
You just need to create an oAuth token at https://github.com/settings/tokens
and get required file via GitHub API using code like below
library(RCurl)
library(devtools)
jsonRawFile <- fromJSON(getURL("https://api.github.com/repos/USERNAME/REPONAME/contents/filename.R",
httpheader = c(Authorization = "token 38ebb0393fe1757ffde9c45d81adzzzzzzzzz",
"User-Agent" = "RCurl"),
.opts = list(ssl.verifypeer = FALSE)))
source_url(jsonRawFile$download_url)
The format of Authorization header should be strictly "token " + your_token_from_account.

Resources