Skip to content

Instantly share code, notes, and snippets.

@OlenaTimchenko
Last active March 18, 2025 15:35
Show Gist options
  • Select an option

  • Save OlenaTimchenko/49f5e0849ac21685f390b0f605e63f7a to your computer and use it in GitHub Desktop.

Select an option

Save OlenaTimchenko/49f5e0849ac21685f390b0f605e63f7a to your computer and use it in GitHub Desktop.
GADS balance alert script

Guide to Setting Up the Google Ads Budget Monitoring Script

Step 1: Prepare Credentials

  1. Telegram Bot Token:
    • Create a bot via BotFather in Telegram.
    • Copy the provided bot token (e.g., 123456789:ABCDEF...).
  2. Telegram Chat ID:
    • Add your bot to a group or chat.
    • Send any message.
    • Visit https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates.
    • Extract chat.id from the response.
    Alternative way Find the bot @username_to_id_bot. Press "Start," then select "Chat" and choose the desired chat. The bot will provide the chat ID in response. IMPORTANT – the chat ID must be taken with a MINUS SIGN. for example CHAT_ID: '-1111111111'
  3. Email Addresses:
    • Add recipient emails to the EMAIL_RECIPIENTS array in the script.

Step 3: Paste and Configure

  1. Copy and paste the provided script into the Google Ads script editor.
  2. Replace placeholders:
    • YOUR_TELEGRAM_BOT_TOKEN with your bot token.
    • YOUR_TELEGRAM_CHAT_ID with your chat ID.
    • Add email addresses to EMAIL_RECIPIENTS.

Step 4: Customize Settings

  1. Set the MIN_REMAINING_DAYS variable to the minimum number of remaining budget days for a notification trigger.
  2. Edit the CUSTOM_NOTIFICATION_MESSAGE variable to customize your alert. Use placeholders:
    • {{budgetNow}} - Remaining budget.
    • {{last7DaysCostByDay}} - Average daily spend.
    • {{remainingDays}} - Estimated remaining days.
    • {{accountName}} - Account name.

Are you interested in the topic? Join my Telegram channel "Тут про рекламу" – all information is shared in Ukrainian. I write about AI solutions, their applications in advertising, and develop solutions designed to save time and streamline processes.

I have also developed a Google Ads text Writer ([https://chatgpt.com/g/g-67371845f78c8190af2e36b2e2c69a33-ppc-ads-writer]) for creating Google Ads texts while adhering to Google Ads policies. It's free to use, and you can access it here: Google Ads Text Writer. Use it to automate routine tasks efficiently and intelligently.

/**
* @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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment