|
/** |
|
* @author |
|
* Olena Timchenko - Telegram @Timchenko_elena |
|
* |
|
* === SETTINGS === |
|
* This script monitors the budget and spending trends in a Google Ads account. |
|
* It calculates how many days the remaining budget will last based on the average daily spend |
|
* and sends notifications to a specified Telegram chat or email if the remaining days fall below a defined threshold. |
|
* Enter the required information in the fields below before running the script. |
|
* @version 1.0 |
|
*/ |
|
|
|
// Telegram |
|
const TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"; // Enter your Telegram bot token |
|
const TELEGRAM_CHAT_ID = "YOUR_TELEGRAM_CHAT_ID"; // Enter the chat ID where messages will be sent |
|
|
|
// Email and Notification Settings |
|
const EMAIL_RECIPIENTS = ["[email protected]"]; // Add email recipients here |
|
const MIN_REMAINING_DAYS = 3; // Minimum number of days for a notification trigger |
|
|
|
/** |
|
* === CUSTOM MESSAGE TEMPLATE === |
|
* Notification message template for email and Telegram. |
|
* Use {{budgetNow}}, {{last7DaysCostByDay}}, {{remainingDays}}, and {{accountName}} as placeholders. |
|
*/ |
|
const CUSTOM_NOTIFICATION_MESSAGE = ` |
|
Вітаємо! Залишок коштів на вашому рекламному акаунті Google Ads становить лише {{budgetNow}} грн. |
|
Враховуючи поточні витрати ({{last7DaysCostByDay}} грн/день), коштів вистачить приблизно на {{remainingDays}} днів. |
|
Рекомендуємо поповнити рахунок найближчим часом, щоб уникнути зупинки рекламних кампаній. |
|
`; |
|
|
|
function main() { |
|
var accountName = AdWordsApp.currentAccount().getName(); |
|
var budgets = AdWordsApp.budgetOrders().withCondition('Status = ACTIVE').get(); |
|
|
|
try { |
|
var budget = budgets.next(); |
|
if (budget.getSpendingLimit() !== null) { |
|
var startDate = timeFormat(budget.getStartDateTime()); |
|
var cost = AdWordsApp.currentAccount().getStatsFor(startDate, today()).getCost(); |
|
var limit = budget.getSpendingLimit(); |
|
var last7DaysCostByDay = (AdWordsApp.currentAccount().getStatsFor("LAST_7_DAYS").getCost() / 7).toFixed(); |
|
var remainingDays = calculateRemainingDays(limit, cost, last7DaysCostByDay); |
|
var budgetNow = Math.max(0, (limit - cost).toFixed()); |
|
|
|
var message = CUSTOM_NOTIFICATION_MESSAGE |
|
.replace('{{accountName}}', accountName) |
|
.replace('{{budgetNow}}', budgetNow) |
|
.replace('{{last7DaysCostByDay}}', last7DaysCostByDay) |
|
.replace('{{remainingDays}}', remainingDays); |
|
|
|
if (remainingDays < MIN_REMAINING_DAYS) { |
|
EMAIL_RECIPIENTS.forEach(email => { |
|
MailApp.sendEmail(email, "Budget Alert", message); |
|
}); |
|
sendTelegramMessage(message); |
|
} |
|
} |
|
} catch (e) { |
|
var errorHeader = "Script Execution Error: Budget Monitoring"; |
|
var errorBody = `An error occurred while monitoring the account ${accountName}: ${e}`; |
|
EMAIL_RECIPIENTS.forEach(email => { |
|
MailApp.sendEmail(email, errorHeader, errorBody); |
|
}); |
|
sendTelegramMessage(`${errorHeader}\n\n${errorBody}`); |
|
} |
|
} |
|
|
|
function timeFormat(date) { |
|
var year = date.year.toString(); |
|
var month = date.month.toString().padStart(2, '0'); |
|
var day = date.day.toString().padStart(2, '0'); |
|
return [year, month, day].join(""); |
|
} |
|
|
|
function today() { |
|
var date = new Date(); |
|
var timeZone = AdWordsApp.currentAccount().getTimeZone(); |
|
var format = 'yyyyMMdd'; |
|
return Utilities.formatDate(date, timeZone, format); |
|
} |
|
|
|
function calculateRemainingDays(limit, cost, last7DaysCostByDay) { |
|
return last7DaysCostByDay > 0 ? Math.max(0, ((limit - cost) / last7DaysCostByDay).toFixed()) : 0; |
|
} |
|
|
|
function sendTelegramMessage(text) { |
|
var telegramUrl = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage?chat_id=${TELEGRAM_CHAT_ID}&text=${encodeURIComponent(text)}`; |
|
var options = { |
|
method: 'POST', |
|
contentType: 'application/json' |
|
}; |
|
UrlFetchApp.fetch(telegramUrl, options); |
|
} |