How to get all Video ads which are associated with campaigns which have started this year - google-ads-api

I'm not sure what to put in the withCondition to get all such videoAds.
var videoAds = AdsApp
.videoAds()
.withCondition('????')
.get();
while (videoAds.hasNext()) {
var videoAd = videoAds.next();
data.push([
videoAd.getVideoCampaign().getId(),
videoAd.getVideoCampaign().getName(),
videoAd.getVideoAdGroup().getId(),
videoAd.getVideoAdGroup().getName(),
videoAd.getId(),
videoAd.getName(),
]);
}

Related

GAQL running on an MCC doesn't show a campaign

I've tried to run this GAQL on an MCC, but didn't get any rows.
ads-script:
campaignIds query =SELECT customer.id, campaign.resource_name, campaign.name FROM campaign WHERE campaign.id IN ("123456");
_rowsToMap(accountToCampaignsMap, AdsApp.report(query, REPORTING_OPTIONS));
}
function _rowsToMap(map, response) {
rows = response.rows();
while (rows.hasNext()) {
var row = rows.next();
Logger.log(JSON.stringify(row));
...
}
Even though I see it in the UI under this MCC
What am I missing?
it's because you don't have campaigns on this account, but in managed accounts you do. Try first get list of managed accounts then query every one, lige this:
const query = 'selsct ... from ...'
const accounts = AdsManagerApp.accounts().get()
const campaignsData = []
while (accounts.hasNext()) {
var account = accounts.next();
AdsManagerApp.select(account)
const search = AdsApp.search(query)
while (search.hasNext()) {
const searchRow = search.next();
campaignsData.push({
accountName: account.getName(),
accointId: account.getCustomerId(),
...,
})
}
}

Google Sheets - A pull data function doesn't want to play nice with a history storing function

I found a couple of functions that met my needs, but they don't want to play nice together. The goal is to pull data once a day, then add it to a new column. The history function is fine, and I've got a trigger setup to run it once a day, but it's erroring when attempting to run automatically, and sending me an email with the following.
6/18/18 5:29 PM loadRegionAggregates TypeError: Cannot find function
forEach in object [object Object]. (line 19, file
"Code") time-based 6/18/18 5:29 PM
here's the full code.gs (I bolded the section with line 19, first line of the function)
// Requires a list of typeids, so something like Types!A:A
// https://docs.google.com/spreadsheets/d/1IixV0eNqg19FE6cLzb83G1Ucb0Otl-Jnvm6csAlPKwo/edit?usp=sharing for an example
function loadRegionAggregates(priceIDs,regionID){
if (typeof regionID == 'undefined'){
regionID=10000002;
}
if (typeof priceIDs == 'undefined'){
throw 'Need a list of typeids';
}
var prices = new Array();
var dirtyTypeIds = new Array();
var cleanTypeIds = new Array();
var url="https://market.fuzzwork.co.uk/aggregates/?station=60003760&types=34,35,36,37,38,39,40"
**priceIDs.forEach(function (row) {
row.forEach(function (cell) {
if (typeof(cell) === 'number' ) {
dirtyTypeIds.push(cell);
}**
});
});
cleanTypeIds = dirtyTypeIds.filter(function(v,i,a) {
return a.indexOf(v)===i;
});
prices.push(['TypeID','Buy volume','Buy Weighted Average','Max Buy','Min Buy','Buy Std Dev','Median Buy','Percentile Buy Price','Sell volume','Sell Weighted Average','Max sell','Min Sell','Sell Std Dev','Median Sell','Percentile Sell Price'])
var parameters = {method : "get", payload : ""};
var o,j,temparray,chunk = 100;
for (o=0,j=cleanTypeIds.length; o < j; o+=chunk) {
temparray = cleanTypeIds.slice(o,o+chunk);
Utilities.sleep(100);
var types=temparray.join(",").replace(/,$/,'')
var jsonFeed = UrlFetchApp.fetch(url+types, parameters).getContentText();
var json = JSON.parse(jsonFeed);
if(json) {
for(i in json) {
var price=[parseInt(i),
parseInt(json[i].buy.volume),
parseInt(json[i].buy.weightedAverage),
parseFloat(json[i].buy.max),
parseFloat(json[i].buy.min),
parseFloat(json[i].buy.stddev),
parseFloat(json[i].buy.median),
parseFloat(json[i].buy.percentile),
parseInt(json[i].sell.volume),
parseFloat(json[i].sell.weightedAverage),
parseFloat(json[i].sell.max),
parseFloat(json[i].sell.min),
parseFloat(json[i].sell.stddev),
parseFloat(json[i].sell.median),
parseFloat(json[i].sell.percentile)];
prices.push(price);
}
}
}
return prices;
}
function storeData() {
var sheet = SpreadsheetApp.getActiveSheet();
var datarange = sheet.getDataRange();
var numRows = datarange.getNumRows();
var numColumns = datarange.getNumColumns();
sheet.getRange(1,numColumns + 1).setValue(new Date());
for (var i=2; i <= numRows; i++) {
var prices = sheet.getRange(i, 8).getValue();
sheet.getRange(i, numColumns + 1).setValue(prices);
}
}
I found this link:
TypeError: Cannot find function forEach in object
Which explains some of it, but when the code runs in debug mode, I don't have a range defined, and then the live sheet bugs with:
ReferenceError: "row" is not defined (line 21).
Note: My original code works fine when I run the script locally, just not when the daily timer goes off. I'm assuming the issues listed on the linked query regarding no forEach class on the nested object are applying to whatever runs the triggered .gs
Edit: Ok so i've been working on this all day. I've learned how to set an array var (since I didn't need to change the array, static works) and i've been trying to get the rest of the code adjusted ever since. Here's where I am so far:
// Requires a list of typeids, so something like Types!A:A
// https://docs.google.com/spreadsheets/d/1IixV0eNqg19FE6cLzb83G1Ucb0Otl-Jnvm6csAlPKwo/edit?usp=sharing for an example
function loadRegionAggregates(priceIDs,regionID){
if (typeof regionID == 'undefined'){
regionID=10000002;
}
if (typeof priceIDs == 'undefined'){
priceIDs = [34,35,36,37,38,39,40,11399];
}
var prices = new Array();
var dirtyTypeIds = new Array();
var cleanTypeIds = new Array();
var url="https://market.fuzzwork.co.uk/aggregates/?station=60003760&types=34,35,36,37,38,39,40"
// for (var priceIDs) {
// if (row.hasOwnProperty(column)) {
// var cell = row[column];
// if (typeof cell == "number") {
priceIDs.push(priceIDs);
// }
// }
// }
cleanTypeIds = dirtyTypeIds.filter(function(v,i,a) {
return a.indexOf(v)===i;
});
prices.push(['TypeID','Buy volume','Buy Weighted Average','Max Buy','Min Buy','Buy Std Dev','Median Buy','Percentile Buy Price','Sell volume','Sell Weighted Average','Max sell','Min Sell','Sell Std Dev','Median Sell','Percentile Sell Price'])
var parameters = {method : "get", payload : ""};
var o,j,temparray,chunk = 100;
for (o=0,j=cleanTypeIds.length; o < j; o+=chunk) {
temparray = cleanTypeIds.slice(o,o+chunk);
Utilities.sleep(100);
var types=temparray.join(",").replace(/,$/,'')
var jsonFeed = UrlFetchApp.fetch(url+types, parameters).getContentText();
var json = JSON.parse(jsonFeed);
if(json) {
for(i in json) {
var price=[parseInt(i),
parseInt(json[i].buy.volume),
parseInt(json[i].buy.weightedAverage),
parseFloat(json[i].buy.max),
parseFloat(json[i].buy.min),
parseFloat(json[i].buy.stddev),
parseFloat(json[i].buy.median),
parseFloat(json[i].buy.percentile),
parseInt(json[i].sell.volume),
parseFloat(json[i].sell.weightedAverage),
parseFloat(json[i].sell.max),
parseFloat(json[i].sell.min),
parseFloat(json[i].sell.stddev),
parseFloat(json[i].sell.median),
parseFloat(json[i].sell.percentile)];
prices.push(price);
}
}
}
return prices;
}
function storeData() {
var sheet = SpreadsheetApp.getActiveSheet();
var datarange = sheet.getDataRange();
var numRows = datarange.getNumRows();
var numColumns = datarange.getNumColumns();
sheet.getRange(1,numColumns + 1).setValue(new Date());
for (var i=2; i <= numRows; i++) {
var prices = sheet.getRange(i, 8).getValue();
sheet.getRange(i, numColumns + 1).setValue(prices);
}
}
So far, so good. It's not throwing any more errors on debug, and the column headers are coming in, but it's not bringing in the data anymore from the push.
Help!

Pulling a feed of youtube videos with statistics and duration data

I'm currently trying to use the Youtube V3 API to generate a feed of the most recently uploaded videos in a channel. Currently I've got this mostly working, however I can't for the life of me get two important bits of data pulled through - video views and video duration. I understand that these bits of data belong to the "videos" endpoint, but i'm not sure how to integrate this into the Javascript API example that was provided on Google's Youtube API website. Here is my code below - any help would be greatly appreciated:
// Define some variables used to remember state.
var playlistId, nextPageToken, prevPageToken;
// After the API loads, call a function to get the uploads playlist ID.
function handleAPILoaded() {
requestUserUploadsPlaylistId();
}
// Call the Data API to retrieve the playlist ID that uniquely identifies the
// list of videos uploaded to the currently authenticated user's channel.
function requestUserUploadsPlaylistId() {
// See https://developers.google.com/youtube/v3/docs/channels/list
var request = gapi.client.youtube.channels.list({
mine: true,
part: 'contentDetails, statistics'
});
request.execute(function(response) {
playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
requestVideoPlaylist(playlistId);
});
}
// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
$('#video-container').html('');
var requestOptions = {
playlistId: playlistId,
part: 'snippet, contentDetails',
maxResults: 10
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function(response) {
// Only show pagination buttons if there is a pagination token for the
// next or previous page of results.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('#next-button').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('#prev-button').css('visibility', prevVis);
var playlistItems = response.result.items;
if (playlistItems) {
$.each(playlistItems, function(index, item) {
displayResult(item.snippet);
displayContentDetails(item.contentDetails);
displayStats(item.statistics);
});
} else {
$('#video-container').html('Sorry you have no uploaded videos');
}
});
}
// Create a listing for a video.
function displayResult(videoSnippet) {
var title = videoSnippet.title;
var videoId = videoSnippet.resourceId.videoId;
var publishedAt = videoSnippet.publishedAt;
var videoThumbURL = videoSnippet.thumbnails.high.url;
var publishedUTC = new Date(publishedAt);
var publishedDay = publishedUTC.getUTCDay();
var publishedMonth = publishedUTC.getUTCMonth();
var publishedYear = publishedUTC.getUTCFullYear();
var a = moment(publishedUTC);
var b = moment(Date.now());
var timeFrom = a.from(b);
$('#video-container').append('<li><img src='+videoThumbURL+'><br><p>' + title + ' - ' + timeFrom + '</p></li>');
}
// Create a listing for a video.
function displayContentDetails(stuff) {
var videoEndsAt = stuff.duration;
$('#video-container li').append('<span class="endsAt">'+ videoEndsAt +'</span>');
}
function displayStats(vidStats) {
var videoStats = vidStats.viewCount;
$('#video-container li').append('<span class="videoStats">'+ videoStats +'</span>');
}
// Retrieve the next page of videos in the playlist.
function nextPage() {
requestVideoPlaylist(playlistId, nextPageToken);
}
// Retrieve the previous page of videos in the playlist.
function previousPage() {
requestVideoPlaylist(playlistId, prevPageToken);
}
Although you said channel the code shows you pulling from a playlist, which does not have the data you want.
For each video from the playlist, you'll need to save the videoID, then make call(s) to the Videos: list endpoint (up to 50 ids at a time) with the 'parts' parameter of 'snippet,contentDetails,statistics'. Those API results will have the data you want.
Thanks #Johnh10, you were right, this is what I ended up doing.
var videoStatsEndpoint = "https://www.googleapis.com/youtube/v3/videos?part=statistics";
var videoToQuery = "&id="+videoId+"&key=";
var apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var videoViews = 0;
jQuery.get(videoStatsEndpoint + videoToQuery + apiKey, function(data){
videoViews = data.items[0].statistics.viewCount;
console.log(videoViews);
});

CommentThreads amount changes by order

CommentThreads amount changes by order
Hi I'm trying to fetch all comments of a video. For testing purpose I'm using this video Id U55NGD9Jm7M.
When I order by time I get 1538 comments the last wrote on the 02.05.2015.
If I’m using the relevance I only receive 1353 comment and the last was wrote on the 29.04.2015
This doesn’t seem right to me. I expected to receive the same comments but in a different order and not different comments.
I also tried this on a different video and the results were the same.
My code cut down to minimum
Thank you for your help
public class foo
{
public void bar(string videoId)
{
var allTopLevelComments = new List<CommentThread>();
var searchListResponse = getThread(videoId);
allTopLevelComments.AddRange(searchListResponse.Items);
string nextPage = searchListResponse.NextPageToken;
while (!String.IsNullOrEmpty(nextPage))
{
searchListResponse = getThread(videoId, searchListResponse.NextPageToken);
nextPage = searchListResponse.NextPageToken;
allTopLevelComments.AddRange(searchListResponse.Items);
}
var first = allTopLevelComments.OrderBy(c => c.Snippet.TopLevelComment.Snippet.PublishedAt).First();
}
private CommentThreadListResponse getThread(string videoId, string nextPageToken = "")
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer
{
ApiKey = "my key",
ApplicationName = "my app"
});
var searchListRequest = youtubeService.CommentThreads.List("id, replies, snippet");
searchListRequest.VideoId = videoId;
searchListRequest.MaxResults = 100;
searchListRequest.Order = CommentThreadsResource.ListRequest.OrderEnum.Time;
searchListRequest.TextFormat = CommentThreadsResource.ListRequest.TextFormatEnum.PlainText;
if (!String.IsNullOrEmpty(nextPageToken))
{
searchListRequest.PageToken = nextPageToken;
}
return searchListRequest.Execute();
}
}

Can't access to event posted values

i'm writing a little google apps script which allow to select several names among a list of developpers. But in my doPost(e) method, i can't access to the array of posted values (it's undefinded), event if i check all the checkboxes...
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// add the new menu
var menuEntries = [];
menuEntries.push({name: "Edit page", functionName: "start"})
ss.addMenu("My tools", menuEntries);
}
function start() {
var app = UiApp.createApplication();
app.setTitle("Edit page");
var formPanel = app.createFormPanel();
var mainPanel = app.createVerticalPanel();
var gridPanel = app.createGrid(1, 2);
// developpers
var developperPanel = app.createVerticalPanel()
var developpers = [];
developpers.push( "John", "Peter", "Max", "Johnny" );
for (var i = 1; i < developpers.length; ++i) {
var checkbox = app.createCheckBox(developpers[i]).setName("dev"+i);
developperPanel.add(checkbox);
}
gridPanel.setWidget(0,0,app.createLabel("Developpers : "));
gridPanel.setWidget(0,1,developperPanel);
// submit button
mainPanel.add(gridPanel);
mainPanel.add(app.createSubmitButton().setText("OK"));
formPanel.add(mainPanel);
app.add(formPanel);
var ss = SpreadsheetApp.getActive();
ss.show(app);
}
function doPost(e) {
var app = UiApp.getActiveApplication();
app.add(app.createLabel(e.values[0])); // Here is the error.
return app;
}
In the exemple, the list is fixed but in my real script, i create the list thanks to the Spreadsheet.
Thanks
Max
The correct way to see the checkboxes values is using e.parameter[name], like you said yourself on a comment. Here is some code example:
function start() {
//...
var developpers = ["John", "Peter", "Max", "Johnny"];
//you were skiping the first developer
for (var i = 0; i < developpers.length; ++i) { //array starts on zero, not one
var checkbox = app.createCheckBox(developpers[i]).setName("dev"+i);
developperPanel.add(checkbox);
}
//...
}
function doPost(e) {
var app = UiApp.getActiveApplication();
var developpers = ["John", "Peter", "Max", "Johnny"]; //repeat it here or make it global, if it's static like this
var checked = [];
for( var i in developpers )
if( e.parameter['dev'+i] == 'true' )
checked.push(developpers[i]);
app.add(app.createLabel(checked));
return app;
}
You should use e.parameter.yourCheckBoxName
for example:
function doPost(e) {
var app = UiApp.getActiveApplication();
app.add(app.createLabel(e.parameter.dev1); // Access checkbox by its name
return app;
}
This would show status of check box "Peter", when it is checked. You can modify based on your need.

Resources