
Cosa succede se il tuo account Google Ads smette improvvisamente di mostrare annunci a causa di un problema con i pagamenti o con la bocciatura degli annunci? Se non te ne accorgi subito, rischi di perdere soldi.
Ecco perché uno script di monitoraggio che ti avverte subito quando l’account smette di deliverare impression è una gran bella cosa.
Ho sempre usato lo script del buon @Frederick Vallaeys, che ti avverte via mail se l’account ha smesso di fare impression nelle ultime X ore. In genere uso le ultime 12 ore e lo faccio girare di notte. In questo modo mi controlla che il giorno prima l’account abbia girato regolarmente e, se così non fosse, mi manda una mail.
Qualche giorno fa il buon @Nils Roijmans ha mandato una mail dove aveva creato uno script che ti avverte su WhatsApp se l’account è offline.
Perché allora non chiedere aiuto al mio amico GPT e fargli modificare lo script di Vallaeys facendogli inviare un messaggio su WhatsApp? Ho scoperto però che servivano delle API a pagamento. Allora ho chiesto di trovare una soluzione gratuita: Telegram.
Lo script manda un messaggio su Telegram tramite bot. Tra l’altro, potrebbe essere usato come alert per verificare che un account stia portando conversioni. Se, ad esempio, non porta conversioni nelle ultime 12/24/36 ore, mi viene mandato un messaggio. Basta solo cambiare la variabile da impression a conversioni.
Attenzione: per far funzionare questo script occorre creare un piccolo bot su Telegram. Qui sotto troverai sia lo script che le istruzioni per creare il bot. Se ci sono riuscito io, che sono una vera pippa a programmare, ci può riuscire chiunque.
Buon Alert.
– – – ENG VERSION – – –
Script with Telegram Notification if the Account Goes Offline
What happens if your Google Ads account suddenly stops showing ads due to a payment issue or ad disapproval? If you don’t notice right away, you risk losing money.
That’s why having a monitoring script that immediately notifies you when the account stops delivering impressions is a great idea.
I’ve always used the script by the great @Frederick Vallaeys, which sends you an email if the account hasn’t generated impressions in the last X hours. I usually set it to the last 12 hours and schedule it to run overnight. This way, it checks if the account ran properly the previous day, and if not, it sends me an email.
A few days ago, the brilliant @Nils Rooijmans sent an email showcasing a script that notifies you on WhatsApp if the account goes offline.
So, why not ask my friend GPT for help to modify Vallaeys’ script to send a message on WhatsApp? However, I found out it required paid APIs. So, I asked GPT to find a free solution: Telegram.
The script sends a message to Telegram via a bot. Plus, it could also be used as an alert to check if an account is generating conversions. For example, if it doesn’t generate conversions in the last 12/24/36 hours, I receive a message. You just need to change the variable from impressions to conversions.
Note: To make this script work, you need to create a small bot on Telegram. Below, you’ll find both the script and the instructions to create the bot. If I managed to do it—being terrible at coding—anyone can.
Happy Alerting.
SCRIPT
var TELEGRAM_BOT_TOKEN = "INSERT_YOUR_BOT_TOKEN"; // Insert your Telegram bot token
var TELEGRAM_CHAT_ID = "INSERT_YOUR_CHAT_ID"; // Insert your chat ID to receive notifications
var NUM_HOURS_TO_CHECK = 12;
var METRIC_TO_CHECK = "Impressions";
var DEBUG = 1; // Set to 1 to enable debug logs
Date.prototype.yyyymmdd = function () {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth() + 1).toString();
var dd = this.getDate().toString();
return yyyy + (mm[1] ? mm : "0" + mm[0]) + (dd[1] ? dd : "0" + dd[0]);
};
function getDateRangeYesterdayToToday() {
var currentDate = new Date();
var tempDate = new Date();
tempDate.setDate(tempDate.getDate() - 1);
var yesterdayDate = tempDate;
return yesterdayDate.yyyymmdd() + "," + currentDate.yyyymmdd();
}
function sendTelegramMessage(chatId, message) {
var url = "https://api.telegram.org/bot" + TELEGRAM_BOT_TOKEN + "/sendMessage";
var payload = {
chat_id: chatId,
text: message,
parse_mode: "HTML"
};
var options = {
method: "post",
contentType: "application/json",
payload: JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, options);
if (DEBUG) Logger.log("Telegram Response: " + response.getContentText());
}
function main() {
var dateRange = getDateRangeYesterdayToToday();
var currentDate = new Date();
Logger.log("Date Range: " + dateRange);
// Generate the query to fetch performance data
var queryText =
"SELECT " +
METRIC_TO_CHECK +
", DayOfWeek, HourOfDay FROM ACCOUNT_PERFORMANCE_REPORT DURING " +
dateRange;
Logger.log("Query Text: " + queryText);
var result = AdWordsApp.report(queryText);
var rows = result.rows();
var daysMapping = [];
daysMapping["Sunday"] = 0;
daysMapping["Monday"] = 1;
daysMapping["Tuesday"] = 2;
daysMapping["Wednesday"] = 3;
daysMapping["Thursday"] = 4;
daysMapping["Friday"] = 5;
daysMapping["Saturday"] = 6;
var impressionsByHour = {};
// Read data from the report
while (rows.hasNext()) {
var currentRow = rows.next();
var dayFactor = daysMapping[currentRow["DayOfWeek"]];
var hourFactor = parseInt(currentRow["HourOfDay"], 10);
var actualHour = dayFactor * 24 + hourFactor;
impressionsByHour[actualHour] = parseInt(currentRow[METRIC_TO_CHECK], 10) || 0;
if (DEBUG) {
Logger.log(
"Day: " +
currentRow["DayOfWeek"] +
", Hour: " +
currentRow["HourOfDay"] +
", " +
METRIC_TO_CHECK +
": " +
currentRow[METRIC_TO_CHECK]
);
}
}
Logger.log("ImpressionsByHour: " + JSON.stringify(impressionsByHour));
// Check activity in the last NUM_HOURS_TO_CHECK hours
var foundEntry = false;
var numHoursToCheck = NUM_HOURS_TO_CHECK + 1;
for (var i = 1; i < numHoursToCheck; i++) {
var tempDate = new Date(currentDate.getTime());
tempDate.setHours(tempDate.getHours() - i);
var hourIndexToCheck = tempDate.getDay() * 24 + tempDate.getHours();
var impressions = impressionsByHour[hourIndexToCheck] || 0;
if (DEBUG) {
Logger.log(
"Checking HourIndex: " +
hourIndexToCheck +
", Impressions: " +
impressions
);
}
if (impressions > 0) {
foundEntry = true;
break;
}
}
if (foundEntry) {
Logger.log(
"All good! The account seems to be active in the last " +
NUM_HOURS_TO_CHECK +
" hours."
);
} else {
var message =
"⚠️ <b>Warning</b>: The Google Ads account <b>" +
AdWordsApp.currentAccount().getName() +
"</b> (ID: " +
AdWordsApp.currentAccount().getCustomerId() +
") has not received any impressions in the last " +
NUM_HOURS_TO_CHECK +
" hours. Please check the payment methods!";
sendTelegramMessage(TELEGRAM_CHAT_ID, message);
Logger.log(
"WARNING: The account has been inactive for the last " +
NUM_HOURS_TO_CHECK +
" hours."
);
}
}
Obtain the BOT_TOKEN and CHAT_ID for using Telegram notifications in your script.
1. Obtain the BOT_TOKEN by creating a bot with BotFather
BotFather is Telegram’s official bot used to create and manage other bots.
Steps to create the bot and get the BOT_TOKEN:
- Open Telegram and search for BotFather in the search bar.
- Start a conversation with BotFather by clicking on Start.
- Send the command
/newbot
to BotFather. - Follow the instructions:
- Set a name for your bot: This will be the visible name of the bot.
- Choose a unique username for your bot: It must end with “bot” (e.g.,
MyBot123_bot
).
- After completing the setup, BotFather will send you a message with the BOT_TOKEN, which will look something like this:makefileCopyEdit
123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ123456
Save this token because you’ll use it in your script to authenticate with the Telegram API.
2. Retrieve the CHAT_ID by sending a message to the bot
The CHAT_ID
is a unique identifier for the recipient of Telegram messages (it can be a user or a group).
Steps to obtain the CHAT_ID:
- Send a message to your bot:
- Search for your bot (created in step 1) in Telegram and start a conversation by clicking on Start.
- Send a test message, for example: “Hello Bot!”.
- Retrieve the CHAT_ID using Telegram’s API:
- Open your browser and replace
<BOT_TOKEN>
with the token obtained in step 1 in the following URL:https://api.telegram.org/bot<BOT_TOKEN>/getUpdates
- Example: H
ttps://api.telegram.org/bot123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ123456/getUpdates
- Open your browser and replace
- Read the API response:
- You will receive a JSON response containing details about the message sent to your bot. Look for a section similar to this:
{ "ok": true, "result": [ { "update_id": 123456789, "message": { "message_id": 1, "from": { "id": 987654321, "is_bot": false, "first_name": "John", "username": "JohnDoe" }, "chat": { "id": 987654321, "first_name": "John", "username": "JohnDoe", "type": "private" }, "date": 1674567890, "text": "Hello Bot!" } } ] }
The "id"
value inside the "chat"
section is your CHAT_ID. For example:
CHAT_ID = 987654321
Note: If you want to send notifications to a group
- Create a group in Telegram and add your bot to the group.
- Send a message in the group.
- Use the
getUpdates
method (as described above) to retrieve the group ID (theCHAT_ID
will be a negative number, e.g.,-123456789
).
Final Step: Add BOT_TOKEN and CHAT_ID to your script
After obtaining the BOT_TOKEN and CHAT_ID, insert them into your script as shown below:
TELEGRAM_BOT_TOKEN = "123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ123456";
TELEGRAM_CHAT_ID = "987654321";