Skip to content

Instantly share code, notes, and snippets.

@quangquy87
Last active August 23, 2022 07:57
Show Gist options
  • Save quangquy87/fc8efbb38b5b398cd717e55d3117afef to your computer and use it in GitHub Desktop.
Save quangquy87/fc8efbb38b5b398cd717e55d3117afef to your computer and use it in GitHub Desktop.
TẮT VIDEO CÓ HIỆU SUẤT KÉM
/****************************
* TẠM DỪNG VIDEO CÓ HIỆU SUẤT KÉM
* Version 1.0 (21/07/2022)
*
* Created By: Quý Ngô
****************************/
var CONFIG = {
LAST_N_DAYS: 7, // thời gian quét từ ngày quét trở về trước đó
MAX_COST: 150000, // chi tiêu từ số này trở lên mới bắt đầu tính theo điều kiện dưới là CPA
MAX_CPA: 150000, // CPA tối đa có thể chịu được
EMAIL: '', //Email để nhận thông báo, nhiều email cách nhau bởi dấu ",".VD:'[email protected], [email protected]'
SHEET_URL:
'https://docs.google.com/spreadsheets/d/1mMCUvlM4Dq6fIevsZ_uvcwPwiZewoxLpe6GWgSYKgmQ/edit?usp=sharing',
//Tạo 1 bản sao của sheet này https://docs.google.com/spreadsheets/d/1mMCUvlM4Dq6fIevsZ_uvcwPwiZewoxLpe6GWgSYKgmQ/copy
//Sau đó chia sẻ sheet vừa tạo thêm quyền chỉnh sửa và lấy đường liên kết dán vào SHEET_URL
SHEET_TAB_NAME: 'Video ads',
};
function main() {
const ss = SpreadsheetApp.openByUrl(CONFIG.SHEET_URL);
const fromDate = `${getAdWordsFormattedDate(CONFIG.LAST_N_DAYS, 'yyyyMMdd')}`;
const toDate = `${getAdWordsFormattedDate(0, 'yyyyMMdd')}`;
// CONFIG.MAX_COST = CONFIG.MAX_COST * 1000000;
// CONFIG.MAX_CPA = CONFIG.MAX_CPA * 1000000;
let appendRows = [];
var videoAdGroupIds = [];
const videoAdSelector = AdsApp.videoAds()
.withCondition(`metrics.cost_micros >= ${CONFIG.MAX_COST}`)
.withCondition('campaign.status = ENABLED')
.withCondition('ad_group_ad.status = ENABLED')
.forDateRange(fromDate, toDate)
.orderBy('metrics.cost_micros DESC');
const videoAdIterator = videoAdSelector.get();
while (videoAdIterator.hasNext()) {
const videoAd = videoAdIterator.next();
const stats = videoAd.getStatsFor(fromDate, toDate);
const adGroup = videoAd.getVideoAdGroup();
const compaign = videoAd.getVideoCampaign();
const impressions = stats.getImpressions();
const ctr = stats.getCtr();
const conversions = stats.getConversions();
const cost = stats.getCost();
const cpa = conversions === 0 ? cost : cost / conversions;
if (
(conversions === 0 && cost >= CONFIG.MAX_COST) ||
cpa >= CONFIG.MAX_CPA
) {
videoAdGroupIds.push(adGroup.getId());
if (videoAd.isEnabled()) videoAd.pause();
appendRows.push([
convertDateToShortDay(new Date()),
`${AdsApp.currentAccount().getCustomerId()} ${AdsApp.currentAccount().getName()}`,
compaign.getId(),
compaign.getName(),
adGroup.getId(),
adGroup.getName(),
videoAd.getId(),
videoAd.getName(),
videoAd.getVideoId(),
impressions,
ctr,
cost,
conversions,
cpa,
]);
}
}
// stop ad group nếu không có video nào đang chạy
if (videoAdGroupIds.length > 0) {
const ids = [...new Set(videoAdGroupIds)];
const videoAdGroupIterator = AdsApp.videoAdGroups().withIds(ids).get();
while (videoAdGroupIterator.hasNext()) {
const videoAdGroup = videoAdGroupIterator.next();
var videoAdsIterator = videoAdGroup
.videoAds()
.withCondition("ad_group_ad.status = 'ENABLED'")
.get();
if (videoAdsIterator.totalNumEntities() === 0) {
if (videoAdGroup.isEnabled()) videoAdGroup.pause();
}
}
}
// append to sheet
if (appendRows.length > 0) {
var sheet = ss.getSheetByName(CONFIG.SHEET_TAB_NAME);
if (sheet === null) {
console.log(
'Vui lòng copy tên của sheet tab vào biến SHEET_TAB_NAME trên cấu hình'
);
} else {
const allRow = sheet.getDataRange().getValues();
let excludedRow = [];
if (allRow.length > 0) excludedRow = allRow.slice(1);
for (const item of appendRows) {
const existIndex = excludedRow.findIndex((o) => {
return `${o[4]}` === `${item[4]}` && `${o[8]}` === `${item[8]}`;
});
if (existIndex === -1) {
sheet.appendRow(item);
}
}
}
}
// sent email
if (CONFIG.EMAIL != '') {
var SUB = `${AdsApp.currentAccount().getName()} - Dừng video có hiệu suất thấp`;
var BODY = `Hi\n\nVui lòng xem link dưới đây:\n ${ss.getUrl()}\n\nThanks`;
MailApp.sendEmail(CONFIG.EMAIL, SUB, BODY);
}
}
function convertDateToShortDay(date) {
const dd = String(date.getDate()).padStart(2, '0');
const mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
const yyyy = date.getFullYear();
return dd + '/' + mm + '/' + yyyy;
}
function getAdWordsFormattedDate(d, format) {
var date = new Date();
date.setDate(date.getDate() - d);
return Utilities.formatDate(
date,
AdsApp.currentAccount().getTimeZone(),
format
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment