How do I find Client ID in Google Adwords Scripts - google-ads-api

Question 1: -
I am using the script below which works fine, but cant seem to get the Client ID (eg Bobs Bakers) I have many clients and want to run this from within google adwords scripts. (Not the API).
Question 2:
Is there a way to run this across all clients, giving me all campaigns they have? Or do I have to run this script from within each client?
function main() {
var campaignsIterator = AdWordsApp.campaigns()
.withCondition("Status = ENABLED");
.forDateRange('TODAY')
.get();
var csv = 'CampaignName, Impressions,Clicks,AveragePosition,AverageCpc,ConversionRate,Conversions,Ctr,Cost';
while (campaignsIterator.hasNext())
{
var campaign = campaignsIterator.next();
var stats = campaign.getStatsFor("TODAY");
var row = [
campaign,
stats.getImpressions(),
stats.getClicks(),
stats.getAveragePosition(),
stats.getAverageCpc(),
stats.getConversionRate(),
stats.getConversions(),
stats.getCtr(),
stats.getCost()];
csv += '\n' + row.join(',');
}
}

can't find the customer name, but here's a way to see the account id:
AdWordsApp.currentAccount().getCustomerId()
running the same script across accounts isn't possible as of yet. You'll have to run the script from within each client.

Related

Pull pagespeed in seconds from Chrome User Experience Report into a google sheet

By following the guide Create Your Own Google Pagespeed & Mobile Usability Tracking Google Sheet in 5 Steps I managed to set up mobile pagespeed score for a list of (up to 50) URLs.
However since late 2017 or something there is real data available from the Chrome User Experience Report that displays an average load time in seconds for a page based on chrome user data.
(This data is being used for example when using Pagespeed Insights by google.)
Instead of pulling a page score I as described above I would like to pull the average load time into my google sheet.
Is it possible to adapt the script used from the article above to pull load time in seconds instead of pagescore? Or is there any other way to do this?
Thanks in advance your help is much appreciated.
This is the script I run in script editor to get pagescore into google sheet according to the linked article with function =checkAll(C3):
/**
* Returns Mobile Pagespeed, Mobile Usability, and Desktop Pagespeed values in three adjacent columns
* by Cagri Sarigoz
*/
function checkAll(Url) {
//CHANGE YOUR API KEY WITH YOUR_API_KEY BELOW
var key = "AIzaSyB2SeOumbCd6YNfFWRg5Jo_WpISZi4gCFs";
var serviceUrlMobile = "https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url="+Url+"&strategy=mobile&key="+key;
var serviceUrlDesktop = "https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url="+Url+"&strategy=desktop&key="+key;
var array = [];
if (key == "YOUR_API_KEY")
return "Please enter your API key to the script";
var responseMobile = UrlFetchApp.fetch(serviceUrlMobile);
if(responseMobile.getResponseCode() == 200) {
var contentMobile = JSON.parse(responseMobile.getContentText());
if ( (contentMobile != null) && (contentMobile["ruleGroups"] != null) )
{
if (contentMobile["responseCode"] == 200)
{
var speedScoreMobile = contentMobile["ruleGroups"]["SPEED"]["score"];
var usabilityScoreMobile = contentMobile["ruleGroups"]["USABILITY"]["score"];
}
else
{
array.push(["Not Found!", "Not Found!", "Not Found!"]);
return array;
}
}
}
var responseDesktop = UrlFetchApp.fetch(serviceUrlDesktop);
if(responseDesktop.getResponseCode() == 200) {
var contentDesktop = JSON.parse(responseDesktop.getContentText());
if ( (contentDesktop != null) && (contentDesktop["ruleGroups"] != null) )
var speedScoreDesktop = contentDesktop["ruleGroups"]["SPEED"]["score"];
}
array.push([speedScoreMobile, usabilityScoreMobile, speedScoreDesktop]);
return array;
}
I am the writer of the blog post that you shared. As you said, the Google Apps Script there was using Google Pagespeed API v2. The current API version is v4, and v2 will be depreciated on June 30th.
So I updated the code with v4 on my own copy of the spreadsheet. You can make your own copy from here.
I also wanted to add the mobile-friendly test results but it turned out that Google Search Console's API quota restrictions were too tight, returning error almost all the time. So I commented out that part of the code for the time being.
I didn't have the time to update my blog post yet. You can see the new version of the script here.

Unable to save a query as a view table

I have a query that runs and can see the results. But while trying to save the query as a view table, I get error message saying
Failed to save view. No suitable credentials found to access Google
Drive. Contact the table owner for assistance.
I think the problem is caused by a table used in the query. The table is uploaded from a google sheet (with source URI), own by me. I have tried to enable Google Drive API from the project but no luck. Not sure how I can give BigQuery access to Google Drive.
I suspect the problem you are hitting is one of OAuth Scopes. In order to talk to the Google Drive API to read data, you need to use credentials that were granted access to that API.
If you are using the BigQuery web UI and have not explicitly granted access to Drive, it won't work. For example, the first time I tried to "Save to Google Sheets", the BigQuery UI popped up an OAuth prompt asking me to grant access to my Google Drive. After this it could save the results. Try doing this to make sure your credentials have the Drive scope and then "Save View" again.
If you are using your own code to do this, you should request scope 'https://www.googleapis.com/auth/drive' in addition to the 'https://www.googleapis.com/auth/bigquery' scope you are already using to talk to BigQuery.
If you are using the bq client, it has been updated to request this scope, but you may need to re-initialize your authentication credentials. You can do this with bq init --delete_credentials to remove the credentials, then your next action we re-request credentials.
Using Google App Script this worked for me:
function saveQueryToTable() {
var projectId = '...yourprojectid goes here...';
var datasetId = '...yourdatesetid goes here...';
var sourceTable = '...your table or view goes here...';
var destTable = '...destination table goes here...';
var myQuery;
//just a random call to activate the Drive API scope
var test = Drive.Properties.list('...drive file id goes here...')
//list all tables for the particular dataset
var tableList = BigQuery.Tables.list(projectId, datasetId).getTables();
//if the table exist, delete it
for (var i = 0; i < tableList.length; i++) {
if (tableList[i].tableReference.tableId == destTable) {
BigQuery.Tables.remove(projectId, datasetId, destTable);
Logger.log("DELETED: " + destTable);
}
};
myQuery = 'SELECT * FROM [PROJECTID:DATASETID.TABLEID];'
.replace('PROJECTID',projectId)
.replace('DATASETID',datasetId)
.replace('TABLEID',sourceTable)
var job = {
configuration: {
query: {
query: myQuery,
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: destTable
}
}
}
};
var queryResults = BigQuery.Jobs.insert(job, projectId);
Logger.log(queryResults.status);
}
The 'trick' was a random call to the Drive API to ensure both the BigQuery and Drive scopes are included.
Google Apps Script Project Properties

trelloApp with Oauth as a library does not seem to work

I am trying to make a trelloApp library for Google Apps Script which works fine when I run it as the owner of the script. Now when adding it as a library to a script of another user I always get an error message about using the wrong token.
This would be the library MXATH_jOrClwhJxK58e3b7OPNgVSik-PP
To test would be
var API_KEY = "Your Api Key"; //https://trello.com/1/appKey/generate
function test() {
var app = trelloApp.openById(API_KEY)
var organizations = app.getMyOrganizations();
for (var i = 0; i < organizations.length; i++) {
var organization = organizations[i];
Logger.log(organization.getId()+ ' ' + organization.getDisplayName())
}
}
This would be the library in itselve (I removed the script properties with the keys)
And the error I am getting is: Response truncated by the server: expired token (use the option muteHttpExceptions to view the complete repsonse completa) (line 50, archieve "")
The oauth1 depreceation for Google apps Script does not seem to matter as it works fine with my own user.
Nice looking library - just what I was looking for after much head-scratching about the Trello API!
I took a copy and found that if I deployed the authorization web app as "user running app" my copy of the library seemed to work fine from another Google Account.

whar is the oauth service name for the google apps reseller api

I tried to use the google apps reseller api with google apps script. To use oauth I need the AuthServiceName. what is the right name? "apps" does not work.
AuthServiceName is defined in your application, its not dependent on the API that you are connecting to, i would suspect that you may not have completed all the steps necessary or that your oauth call is not properly structured.
Here is an example of a call that retrieves the details of domains.
function getCustomer() {
//set up oauth for Google Reseller API
var oAuthConfig1 = UrlFetchApp.addOAuthService("doesNotMatter");
oAuthConfig1.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://www.googleapis.com/auth/apps.order.readonly");
oAuthConfig1.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig1.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken?oauth_callback=https://script.google.com/a/macros");
oAuthConfig1.setConsumerKey(CONSUMER_KEY);
oAuthConfig1.setConsumerSecret(CONSUMER_SECRET);
var options1 = {oAuthServiceName:"doesNotMatter", oAuthUseToken:"always",
method:"GET", headers:{"GData-Version":"3.0"}, contentType:"application/x-www-form-urlencoded"};
//set up user profiles url
var theUrl = "https://www.googleapis.com/apps/reseller/v1/customers/somedomain.com";
//urlFetch for customer list
var customerInfo = "";
try {
var response = UrlFetchApp.fetch(theUrl,options1);
customerInfo = response.getContentText();
} catch(problem) {
Logger.log(problem.message);
}
Logger.log(customerInfo);
}
This will work if
You have a reseller account (I guess i.e. I did not test on my non reseller account)
You have create a project in the API console, and enabled the Reseller API
You know your SECRET and KEY lifted form the console
I have use a read.only scope which is safe, if not you need to set up your tests in the sand box
Let me know if you need any more clarifications

Get user followers in meteorjs

I'm trying to get the followers for a user that has authenticated through my meteorjs app. I have used the {{loginButtons}} template and have found where the users tokens are. However I now have to create my authorized request by hand and I was hoping this'd be easy. But it's really hard and I feel like I'm wasting time with trying to figure out a way to create the oauth_signature..
Any help is welcome!
Supposing it is Twitter you're talking about I might be able to help you out.
I just managed to do the same thing as you want to do.
This nice piece of code provides a client to the Twitter API: https://github.com/mynetx/codebird-js
Personally I have placed it in the server-folder in my app to avoid exposure of keys etc.
As the codebird-js code take use of XMLHttpRequests and node.js do not come with such functionality by default - at least in a meteor.js context - you have to add the XHR-functionality yourself.
This NPM did it for me: https://npmjs.org/package/xmlhttprequest
However, as you can not deploy your meteor app with additional npm packages I found this solution How can I deploy node modules in a Meteor app on meteor.com? that suggests placing it in the public folder.
Finally I added those lines of code in the codebird-js just below the line that says
var Codebird = function () {
var require = __meteor_bootstrap__.require;
var path = require('path');
var fs = require('fs');
var base = path.resolve('.');
var isBundle = fs.existsSync(base + '/bundle');
var modulePath = base + (isBundle ? '/bundle/static' : '/public') + '/node_modules';
var XMLHttpRequest = require(modulePath + '/xmlhttprequest').XMLHttpRequest;
Finally you have to provide your tokens generated at dev.twitter.com and find your user's tokens stored in the Users collection.
EDIT:
Whenenver you have the above you make a new Codebird object: var bird = new Codebird();
Then you set tokens:
bird.setToken(USER_ACCESS_TOKEN, USER_ACCESS_TOKEN_SECRET);
And makes the call:
bird.__call('friends/ids', {
screen_name': SCREEN_NAME,
user_id: TWITTER_ID
},
function(reply){
console.log(reply);
});
Note that USER_ACCESS_TOKEN, USER_ACCESS_TOKEN_SECRET, USER_NAME & TWITTER_ID in the above example are placeholders. They are all found in the Meteor Users collection.

Resources