Accessing Twitter Ads API from R using twitteR package? - r

I am trying to access Twitter Ads API from R, using twitteR package to authenticate, however, I cannot move further, any ideas, did anybody try it using a similar approach? Current error I get as this one (below) My app is whitelisted for ads, and my credentials work through Twurl, using this credential I can without problem access public API, but struggle with Ads one. Thanks!
Error: $ operator is invalid for atomic vectors
library(twitteR)
library(BBmisc)
library(httr)
appname <- “xxxxx”
api_key <- “xxxxxxx”
api_secret <- “xxxxxxxx”
access_token <- “xxxxxxx”
access_secret <- “xxxxxx”
account_id <- “xxxxxxx”
setup_twitter_oauth(api_key,api_secret, access_token, access_secret)
campaign_id <- itostr(18257572,base=36)
reach_campaign.request <- GET(“https://ads-api.twitter.com/2/stats/accounts/xxxxxxx/reach/campaigns?start_time=2018-06-10T00:00:00+01:00Z&campaign_ids=xxxxx&end_time=2018-06-15T00:00:00+01:00Z”,
query = list(granularity = “DAY”,
metric_groups = “ENGAGEMENT”,
placement = “ALL_ON_TWITTER”),
accept_json(),
config(token = access_token))

Related

Etsy api OAuth2 using httr oauth2.0_token

I am trying to use the etsy API which requires both an API key and oauth2 authentication. The example authentication URL that they provide in the docs looks like this:
https://www.etsy.com/oauth/connect?
response_type=code&
redirect_uri=http://localhost:3003/oauth/redirect&
scope=email_r&
client_id=1aa2bb33c44d55eeeeee6fff&
state=superstring&
code_challenge=DSWlW2Abh-cf8CeLL8-g3hQ2WQyYdKyiu83u_s7nRhI&
code_challenge_method=S256
Cobbling together what I can from tutorials for the r httr package I have the following code:
shopID <- '111111' # not real values
etsy_keystring <- 'foobar'
etsy_shared_secret <- 'foobarbaz'
options(httr_oob_default=TRUE)
etsy_endpoint <- oauth_endpoint(authorize = "https://www.etsy.com/oauth/connect",
access = "https://openapi.etsy.com/v3/public/oauth/token")
etsyApp <- oauth_app("etsyApp",
key = etsy_keystring,
secret = etsy_shared_secret,
redirect_uri = "http://localhost:1410")
oauth2.0_token(endpoint = etsy_endpoint,
app = etsyApp,
scope = 'billing_r',
oob_value = "http://localhost:1410")
which opens the browser to the following url:
https://www.etsy.com/oauth/connect?
client_id=foobar&
scope=billing_r&
redirect_uri=http%3A%2F%2Flocalhost%3A1410&
response_type=code
Which etsy gives an error page for. What I think I am missing, is a way to generate PKCE tokens. Is this possible with httr? Or am I missing something completely obvious.

Why am I scraping Twitter data with R, and the collected tweets are not complete sentences?

I am trying to scrape tweets from Twitter by searching keyword, but it seems that the tweets I collected are not complete sentences. Long tweets only contain half of the whole content. Is there any word limit or sth?
library(devtools)
library(rjson)
library(bit64)
library(httr)
library(base64enc)
library(httpuv)
library(twitteR)
library(ROAuth)
options(httr_oauth_cache=T)
## Twitter authentication
consumer_key <-"**************"
consumer_secret <- "**************"
access_token<-"**************"
access_secret <- "**************"
setup_twitter_oauth(consumer_key, consumer_secret, access_token,
access_secret)
tweets11 <- searchTwitter("#iphone11",lang="en",n=2000)
Many thanks!
twitteR has been archived and deprecated in favor of rTweet.
If you check the feature comparison in the README for rTweet you will see that twitteR does not support extended Tweets.
rTweet's syntax for search is very similar, and it includes the tweet_mode=extended parameter transparently for you.

Error Crawling Data Twitter With R Programming

How do I fix an error like this:
library(twitteR)
library(ROAuth)
customer_key<-"-aaaaaa"
customer_secret<-"aaaaaaaa"
access_token<-"212123213-aaaaa"
access_secret<-"ccccccccccccc"
setup_twitter_oauth(customer_key,customer_secret,access_token,access_secret)
Tweets = searchTwitter("anxiety", n=100, lang = "en")
Error: invalid assignment for reference class field ‘language’, should be from class “character” or a subclass (was class “NULL”)
I User RStudio for run this source code, this is my first time using the twitter API. before I saw the tutorial and they succeeded, after I tried it and there was an error like that. thankyou
consumer_key <- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
consumer_secret <- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
access_token <- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
access_secret <- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
The steps below are the process of extracting Twitter with keyword #statistics and retrieving 10000 data
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)
tw = searchTwitter('#statistics',
n = 10000,
retryOnRateLimit = 1617)
Make sure the token you use has been updated, and the possibility that the word you will scrape is "anxiety" does not exist in the last 7 days. Because scraping using the API will extract data 7 days back only. Suppose I extract data on the 8th, the data that will be pulled is data or sentences containing the word "anxiety" from the 2nd to the 8th.

Using RGoogleAnalytics to retrieve data from google

I'm using RGoogleAnalytics to retrieve mutiple dimensions data ,but every time I try to run ga.data <- ga$GetReportData(query)
then I got an error message :Error in fromJSON(api.response.json, method = "C") :
unexpected escaped character '\'' at pos 53
It's ok when I try other functions
How could I fix this?
I use the following code:
require("RGoogleAnalytics")
query <- QueryBuilder()
access_token <- query$authorize()
ga <- RGoogleAnalytics()
ga.profiles <- ga$GetProfileData(access_token)
profile <- ga.profiles$id[3]
startdate <- "2013-10-01"
enddate <- "2013-12-31"
dimension <- "ga:date,ga:source,ga:medium,ga:keyword,ga:city,ga:operatingSystem,ga:landingPagePath"
metric <- "ga:visits,ga:goal1Completions,ga:goal3Completions"
sort <- "ga:visits"
maxresults <- 500000
query$Init(start.date = startdate,
end.date = enddate,
dimensions = dimension,
metrics = metric,
max.results = maxresults,
table.id = paste("ga:",profile,sep="",collapse=","),
access_token=access_token)
ga.data <- ga$GetReportData(query)
I had some trouble with this too,figured out a way.
Step 1: Install Packages
# lubridate
install.packages("lubridate")
# httr
install.packages("httr")
#RGoogleAnalytics
Use this link to download this particular version of RGoogleAnalytics
http://cran.r-project.org/web/packages/RGoogleAnalytics/index.html
Step 2: Create Client ID and Secret ID
Navigate to Google Developers Console.
(https://console.developers.google.com/project)
Create a New Project and Open it.
Navigate to APIs and ensure that the Analytics API is turned On for your project.
Navigate to Credentials and create a New Client ID.
Select Application Type – Installed Application.
Once your Client ID and Client Secret are created, copy them to your R Script.
client.id <- "xxxxxxxxxxxxxxxxxxxxxxxxx"
client.secret <- "xxxxxxxxxxxxxxx"
token <- Auth(client.id,client.secret)
Save the token object for future sessions
save(token,file="./token_file")
In future sessions, you need not generate the Access Token every time. Assumming that you have saved it to a file,
it can be loaded via the following snippet -
load("./token_file")
Validate and refresh the token
ValidateToken(token)
Step 3: Build required query
query.list <- Init( start.date = "2014-08-01",
end.date = "2014-09-01",
dimensions = "ga:sourceMedium",
metrics = "ga:sessions,ga:transactions",
max.results = 10000,
sort = "-ga:transactions",
table.id = "ga:0000000")
Create the Query Builder object so that the query parameters are validated
ga.query <- QueryBuilder(query.list)
Extract the data and store it in a data-frame
ga.data <- GetReportData(ga.query, token,paginate_query = FALSE)
Handy Links
Common Errors: developers.google.com/analytics/devguides/reporting/core/v3/coreErrors#standard_errors
Query Explorer:
ga-dev-tools.appspot.com/query-explorer/?csw=1
Dimensions and metrics:
developers.google.com/analytics/devguides/reporting/core/dimsmets
It seems that this error appears when the Rjson library isn't able to parse Google Analytics JSON Feed properly. Please try out the recently released and updated version of the RGoogleAnalytics library from CRAN.

Using R to send tweets

I saw a cute demonstration of tweeting from R in a presentation some months ago. The scratch code used by the presenter is here:
http://www.r-bloggers.com/twitter-from-r%E2%80%A6-sure-why-not/
the code is short and sweet:
library("RCurl")
opts <- curlOptions(header = FALSE,
userpwd = "username:password", netrc = FALSE)
tweet <- function(status){
method <- "http://twitter.com/statuses/update.xml?status="
encoded_status <- URLencode(status)
request <- paste(method,encoded_status,sep = "")
postForm(request,.opts = opts)
}
With this function, you can send a tweet simply by using the update function:
tweet("This tweet comes from R! #rstats")
I thought that this could be a useful way of announcing when long jobs are completed. I tried to run this on my machine, and I got some error:
[1] "\n\n Basic authentication is not supported\n\n"
attr(,"Content-Type")
charset
"application/xml" "utf-8"
Warning message:
In postForm(request, .opts = opts) : No inputs passed to form
I'm wondering if there has been some changes on the twitter end of this, that make this code produce this error? I don't know too much about getting R to talk to webpages, so any guidance is much appreciated!!
E
Yes, the basic authentication scheme was disabled on the 16th August 2010.. You'll need to set it up to use OAuth. Unfortunately that is not nearly as simple as using basic authentication
See this twitter wiki page for more information and this StackOverflow question about OAuth for R.
Besides the code you show, there is also a full-blown twitteR package on CRAN you could look at.
The easiest way to tweet in R through the Twitter-API is to use the twitteR Package.
You can set your Twitter-API-APP here: https://apps.twitter.com/
First step is to authenticate:
consumer_key <- "yourcredentials"
consumer_secret <- "yourcredentials"
access_token <- "yourcredentials"
access_secret <- "yourcredentials"
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)
And just tweet (limit per day:2400 tweets):
tweet("Hello World")
If twitteR does not work or you simply want to try to build it yourself ...
See here for a demo of how to do your own Twitter authentication and use of the API with help of the httr package.

Resources