Google Ads CPC Spike Slack Alert Script: Full Setup

Deploy a Google Ads script that detects midday CPC surges over 40% and sends instant Slack webhook alerts. Full code, step-by-step setup, and benchmarks.

By AdTurbo Team · 2026-10-12

A midday surge in cost-per-click (CPC) can drain your daily budget by 1:00 PM before you have even noticed the shift. When broad match keywords drift, Smart Bidding aggressive auction modifiers trigger, or competitors ramp up aggressive midday blitzes, your standard $3.20 CPC can quickly spike to $8.50. Waiting for your morning dashboard review the next day means discovering spent cash on unprofitable auctions with zero recourse.

Setting up a google ads cpc spike slack alert script bridges the gap between passive reporting and active triage. By pairing Google Ads Scripts with an incoming Slack webhook, you can monitor auction pricing throughout the day, calculate rolling baseline variances, and receive actionable alerts the minute costs diverge from your historical average.

Here is a complete, production-ready framework to detect midday anomalies, configure webhooks, write the script, and automate your defenses.

---

Why Real-Time CPC Spikes Occur Midday

Google Ads operates on dynamic second-price auction mechanics driven by live quality scores, competitor bid shifts, and machine learning adjustments. Understanding why midday spikes occur helps distinguish between healthy volume and destructive budget leakage.

1. Smart Bidding Hyper-Aggression

Automated bidding strategies like Target CPA (tCPA) and Target ROAS (tROAS) do not bid a static dollar value. They adjust bids auction by auction based on thousands of real-time signals: user device, operating system, geolocation, browser history, and historical conversion propensity by hour. If an algorithm detects high intent signals early in the day, it may bid 150% above your average baseline to capture perceived conversion momentum.

If conversion tracking experiences an outage, or if post-click user actions fail to fire, Smart Bidding can artificially chase phantom high-intent auctions, causing CPC to skyrocket without delivering actual revenue.

2. Sudden Competitor Bid Shifts and Dayparting Moves

Competitors often adjust their automated bid rules or manual dayparting multipliers to hit peaks during typical business hours (such as 10:00 AM to 3:00 PM). In competitive B2B or emergency services spaces, multiple accounts running simultaneous aggressive dayparting strategies force every participant in the Ad Rank formula to bid higher to secure the same absolute top-of-page placements.

3. Broad Match Semantic Expansion

Broad match keywords match queries based on search intent rather than literal keyword strings. During midday news cycles, trending topics, or related viral searches, broad match algorithms can suddenly match high-volume, expensive commercial queries that sit adjacent to your service offerings. Regularly reviewing your account using a comprehensive search terms report guide reveals how unmanaged intent drift escalates costs.

4. Limited Budget Bottlenecks

When campaigns enter "Limited by Budget" status early in the afternoon, Google's system attempts to pace delivery. Paradoxically, this can trigger Smart Bidding algorithms to focus exclusively on ultra-high-intent auctions that command exorbitant price premiums, leading to an aggressive mid-afternoon CPC surge right before the campaign pauses completely.

---

Anatomy of an Hourly CPC Anomaly Detection Google Ads Script

Building an effective alert requires more than simply dividing total spend by total clicks at 1:00 PM. A rudimentary script that measures a flat midday metric creates constant false alarms due to low statistical volume.

An enterprise-grade hourly cpc anomaly detection google ads script operates on five logical pillars:

| Component | Operational Role | Engineering Consideration |

| :--- | :--- | :--- |

| Baseline Window | Evaluates historical CPC for comparable days | Uses a 7-day to 14-day rolling historical window, excluding the current day. |

| Current Day Aggregator | Pulls intraday performance metrics | Queries TODAY metrics via the Google Ads Query Language (GAQL). |

| Minimum Click Threshold | Eliminates statistical noise | Suppresses alerts if a campaign has fewer than 15–20 clicks on the day. |

| Variance Engine | Calculates delta against tolerance thresholds | Triggers an alert only if: (Current CPC - Baseline CPC) / Baseline CPC = 0.40. |

| Notification Payload | Formats and dispatches the alert | Sends structured JSON containing raw metrics to an incoming Slack webhook. |

+-------------------------------------------------------------+

| Google Ads Script Scheduler (Runs Hourly: 9 AM - 6 PM) |

+-------------------------------------------------------------+

|

v

+-------------------------------------------------------------+

| GAQL Query: Pull 'TODAY' Clicks, Cost, CPC per Campaign |

+-------------------------------------------------------------+

|

v

+-------------------------------------------------------------+

| GAQL Query: Pull 'LAST14DAYS' Historical Baseline CPC |

+-------------------------------------------------------------+

|

v

[Clicks Today = Min Clicks (e.g., 20)?]

|

+---------+---------+

| |

YES NO --- [Exit: No Action]

|

v

[Today's CPC = Baseline CPC 1.40 (+40% Surge)?]

|

+---------+---------+

| |

YES NO --- [Exit: No Action]

|

v

+-------------------------------------------------------------+

| Construct JSON Payload & POST to Slack Webhook URL |

+-------------------------------------------------------------+

By comparing today's intraday performance against a rolling 14-day average of identical campaigns, this architecture flags statistical anomalies rather than standard daily fluctuations.

---

Setting Up the Incoming Slack Webhook

Before deploying script code inside Google Ads, you must establish an incoming webhook endpoint inside your target Slack workspace.

Step 1: Create a Slack App

1. Navigate to the Slack API portal (api.slack.com/apps).

2. Click Create New App and select From scratch.

3. Assign an App Name (e.g., Google Ads Monitor) and pick your corporate workspace.

4. Click Create App.

Step 2: Enable Incoming Webhooks

1. In the sidebar under Features, select Incoming Webhooks.

2. Toggle the switch to activate Incoming Webhooks from Off to On.

3. Click the button at the bottom of the page titled Add New Webhook to Workspace.

Step 3: Choose a Dedicated Slack Channel

1. Select a designated channel for alerting (e.g., google-ads-alerts or ppc-monitoring). Avoid generic channels like general to prevent critical financial pings from becoming background noise.

2. Click Authorize.

3. Copy the generated Webhook URL. It will follow this structure:

https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX

4. Keep this URL secure. Anyone with access to this endpoint can publish messages to your Slack channel.

---

Complete Script Code: Google Ads CPC Spike Detector

Below is the complete slack webhook alert google ads script. It uses the modern Google Ads Scripts API (AdsApp.search) with GAQL to deliver performance, replacing deprecated v1 selectors.

Paste this code directly into your Google Ads Script editor:

javascript

/

• Google Ads CPC Spike Slack Alert Script

• Monitored Metric: Midday CPC vs. 14-Day Baseline

• Triggers when CPC surges by = 40% with minimum click thresholds.

/

const CONFIG = {

SLACKWEBHOOKURL: 'PASTEYOURSLACKWEBHOOKURLHERE',

SURGETHRESHOLD: 0.40, // 0.40 equals a 40% increase

MINCLICKSTODAY: 15, // Prevents false positives from tiny sample sizes

ACCOUNTNAME: AdsApp.currentAccount().getName(),

CURRENCYSYMBOL: '

};

function main() {

if (CONFIG.SLACKWEBHOOKURL.indexOf('PASTEYOURSLACKWEBHOOKURLHERE') !== -1) {

Logger.log('Error: You must paste your Slack Webhook URL into CONFIG.SLACKWEBHOOKURL.');

return;

}

const baselineData = getBaselineMetrics();

const todayData = getTodayMetrics();

const anomalies = [];

for (const campaignId in todayData) {

const current = todayData[campaignId];

const baseline = baselineData[campaignId];

// Verify campaign baseline exists and clicks meet minimum threshold

if (baseline && current.clicks = CONFIG.MINCLICKSTODAY) {

if (baseline.cpc 0) {

const cpcDelta = (current.cpc - baseline.cpc) / baseline.cpc;

if (cpcDelta = CONFIG.SURGETHRESHOLD) {

anomalies.push({

name: current.name,

id: campaignId,

clicksToday: current.clicks,

costToday: current.cost,

cpcToday: current.cpc,

cpcBaseline: baseline.cpc,

percentageIncrease: (cpcDelta 100).toFixed(1)

});

}

}

}

}

if (anomalies.length 0) {

sendSlackAlert(anomalies);

Logger.log('Alert sent for ' + anomalies.length + ' campaign anomalies.');

} else {

Logger.log('All campaigns running within normal CPC ranges.');

}

}

function getTodayMetrics() {

const metrics = {};

const query =

SELECT

campaign.id,

campaign.name,

metrics.clicks,

metrics.costmicros

FROM

campaign

WHERE

campaign.status = 'ENABLED'

AND segments.date = TODAY

;

const response = AdsApp.search(query);

while (response.hasNext()) {

const row = response.next();

const id = row.campaign.id;

const clicks = parseInt(row.metrics.clicks, 10) || 0;

const cost = (parseFloat(row.metrics.costMicros) || 0) / 1000000;

const cpc = clicks 0 ? cost / clicks : 0;

metrics[id] = {

name: row.campaign.name,

clicks: clicks,

cost: cost,

cpc: cpc

};

}

return metrics;

}

function getBaselineMetrics() {

const metrics = {};

// Pull trailing 14 full days excluding today for a stable average

const query =

SELECT

campaign.id,

metrics.clicks,

metrics.costmicros

FROM

campaign

WHERE

campaign.status = 'ENABLED'

AND segments.date DURING LAST14DAYS

;

const response = AdsApp.search(query);

while (response.hasNext()) {

const row = response.next();

const id = row.campaign.id;

const clicks = parseInt(row.metrics.clicks, 10) || 0;

const cost = (parseFloat(row.metrics.costMicros) || 0) / 1000000;

if (!metrics[id]) {

metrics[id] = { clicks: 0, cost: 0 };

}

metrics[id].clicks += clicks;

metrics[id].cost += cost;

}

// Calculate weighted average CPC across the historical window

for (const campaignId in metrics) {

const item = metrics[campaignId];

item.cpc = item.clicks 0 ? item.cost / item.clicks : 0;

}

return metrics;

}

function sendSlackAlert(anomalies) {

let blocks = [

{

"type": "header",

"text": {

"type": "plaintext",

"text": "⚠️ Google Ads Alert: Midday CPC Surge Detected",

"emoji": true

}

},

{

"type": "section",

"text": {

"type": "mrkdwn",

"text": Account: ${CONFIG.ACCOUNTNAME}\nThreshold: +${(CONFIG.SURGETHRESHOLD 100).toFixed(0)}% vs. 14-Day Baseline

}

},

{ "type": "divider" }

];

anomalies.forEach(function(item) {

blocks.push({

"type": "section",

"text": {

"type": "mrkdwn",

"text": Campaign: ${item.name}\n +

• Today\'s CPC: ${CONFIG.CURRENCYSYMBOL}${item.cpcToday.toFixed(2)} +

(Baseline: ${CONFIG.CURRENCYSYMBOL}${item.cpcBaseline.toFixed(2)})\n +

• Surge: +${item.percentageIncrease}%\n +

• Today\'s Volume: ${item.clicksToday} clicks | ${CONFIG.CURRENCYSYMBOL}${item.costToday.toFixed(2)} spent

}

});

});

blocks.push({

"type": "context",

"elements": [

{

"type": "mrkdwn",

"text": "Check search query matching, Smart Bidding targets, or competitors in the Auction Insights report."

}

]

});

const payload = { blocks: blocks };

const options = {

method: 'post',

contentType: 'application/json',

payload: JSON.stringify(payload),

muteHttpExceptions: true

};

UrlFetchApp.fetch(CONFIG.SLACKWEBHOOKURL, options);

}

---

Step-by-Step Installation & Scheduling Guide

Deploying and testing the script inside your Google Ads interface takes roughly five minutes.

Step 1: Open the Google Ads Scripts Console

1. Sign in to your Google Ads account.

2. In the navigation menu, click Tools (represented by the wrench or gear icon).

3. Under Bulk Actions, click Scripts.

4. Click the blue + button to create a new script.

Step 2: Paste and Authorize the Script

1. Clear any default boilerplate code in the script editor.

2. Paste the script provided above into the workspace.

3. Replace 'PASTEYOURSLACKWEBHOOKURLHERE' with your actual Slack webhook URL.

4. Modify the SURGETHRESHOLD (e.g., set to 0.40 for 40%) or MINCLICKSTODAY according to your typical account volume.

5. Click Authorize at the bottom of the screen. Google Ads will ask for permissions to read campaign data and make external URL requests (UrlFetchApp). Grant all requested permissions.

Step 3: Run a Preview Test

1. Click Preview in the bottom right corner.

2. Check the Logs tab below the editor. If none of your campaigns have surged by 40% today with at least 15 clicks, you should see:

All campaigns running within normal CPC ranges.

3. Optional dry run: Temporarily adjust SURGETHRESHOLD to -0.50 (negative 50%) and MINCLICKSTODAY to 1 in preview mode. Click Preview again. Confirm that an alert arrives inside your designated Slack channel, then revert the settings back to 0.40 and 15.

+--------------------------------------------------------------+

| ⚠️ Google Ads Alert: Midday CPC Surge Detected |

| Account: US - eCommerce - Primary |

| Threshold: +40% vs. 14-Day Baseline |

| ------------------------------------------------------------ |

| Campaign: Search - Brand Core |

| • Today's CPC: $4.85 (Baseline: $3.10) |

| • Surge: +56.5% |

| • Today's Volume: 38 clicks | $184.30 spent |

+--------------------------------------------------------------+

Step 4: Schedule Hourly Execution

1. Click Save in the script editor.

2. Return to the main Scripts overview page.

3. Find your script in the list, hover over the Frequency column, and click the pencil edit icon.

4. Select Hourly from the dropdown menu.

5. Save the schedule. The script will now run in the background every 60 minutes, analyzing intraday changes automatically.

---

Triage Playbook: What to Do When an Alert Fires

Receiving an alert provides early notice, but fixing the underlying problem protects your bottom line. When an alert arrives in your Slack channel, follow this five-step sequence within 30 minutes to halt unprofitable spend:

[Slack Alert Received: Campaign CPC +40%]

|

v

[Step 1: Check Auction Insights]

-- Did an aggressive competitor enter or increase impression share?

|

v

[Step 2: Inspect Search Terms Report (Past 24 Hours)]

-- Did a broad match query match high-cost, unqualified terms?

Action: Add immediate Exact Match Negative Keywords.

|

v

[Step 3: Review Smart Bidding Targets]

-- Did someone lower the Target ROAS or raise the Target CPA?

Action: Revert to previous target or implement Max CPC caps.

|

v

[Step 4: Check Conversion Tracking]

-- Are purchase/lead tags failing to fire?

Action: Check Google Tag Manager preview mode to verify tags.

|

v

[Step 5: Safety Valve Action]

-- If budget is running out with 0 conversions: Drop daily budget by 30-50%.

1. Identify Search Query Matches

Run an intraday search terms report filtered to today. Sort queries by cost descending. Frequently, a broad match keyword matches an irrelevant, ultra-competitive inquiry with significant click volume. Add the off-target search term as an exact or phrase negative keyword immediately. If you need inspiration for comprehensive negative libraries, refer to our list of negative keywords examples.

2. Audit Competitor Auction Activity

Open the Auction Insights report for that campaign and isolate the past 7 days against today. Look for new competitors or existing rivals whose Top of Page Rate or Impression Share has surged. If a well-capitalized competitor is running an aggressive promotional push, temporarily lowering your target impression share can preserve your budget until their burst spend settles.

3. Check Conversion Tracking Health

If an automated bidding strategy sees conversion rates fall to zero mid-session because a checkout tag or landing page form broke, it may inflate bids to compensate. Run a test transaction on your site to ensure conversion tags fire properly in Google Tag Manager.

4. Implement Emergency Max CPC Guardrails

If the campaign runs on Maximize Clicks or Maximize Conversions without limits, the engine will pay whatever the auction demands. In response, establish a temporary portfolio bid strategy with a hard Maximum Bid Limit (Bid Cap) to prevent single clicks from exhausting the budget while you troubleshoot.

---

Customizing the Script: Edge Cases, Thresholds, and Exclusions

Every Google Ads account exhibits unique seasonality and volume patterns. Here is how to modify the base script code to match complex account architectures.

Filtering Specific Campaign Names

If you manage mixed brand and non-brand campaigns, brand campaigns should not be evaluated against generic non-brand thresholds. You can modify the GAQL WHERE clause to target specific naming conventions:

javascript

// Only evaluate Non-Brand Search campaigns

const query =

SELECT campaign.id, campaign.name, metrics.clicks, metrics.costmicros

FROM campaign

WHERE campaign.status = 'ENABLED'

AND campaign.advertisingchanneltype = 'SEARCH'

AND campaign.name LIKE '%Non-Brand%'

AND segments.date = TODAY

;

Modifying Time-of-Day Windowing

Running anomaly checks at 6:00 AM frequently generates false positives due to low click volume (e.g., 2 clicks costing $6 total). You can add a time gate so alerts only fire during peak business hours:

javascript

function main() {

const currentHour = new Date().getHours(); // 0 to 23 (matches account timezone)

// Only run between 10:00 AM and 6:00 PM

if (currentHour < 10 || currentHour 18) {

Logger.log('Outside alerting window (10 AM - 6 PM). Skipping execution.');

return;

}

// ... rest of script logic

}

Calculating Separate Desktop vs. Mobile Baselines

Mobile and desktop auctions frequently clear at radically divergent CPCs. If your intraday mix swings heavily toward mobile traffic, average CPC will look artificially high or low. When deeper granularity is necessary, you can split reporting metrics by adding segments.device into your GAQL query and calculating independent device baselines.

---

Custom Scripts vs. Dedicated PPC Management Software

While Google Ads Scripts offer a free way to automate anomaly detection, relying exclusively on custom code across multiple accounts presents clear operational trade-offs.

| Feature / Capability | Custom Google Ads Script | Dedicated PPC Management Software |

| :--- | :--- | :--- |

| Setup Cost | Free ($0) | Subscription fee (typically $100–$500/mo) |

| Maintenance Requirement | High (Breaks when Google updates API/GAQL) | Zero (Handled by the platform engineering team) |

| Multi-Account / MCC Scale | Complex (Requires MCC script architecture) | Native multi-account dashboard support |

| Actionable Interactivity | Read-only alert (Requires manual account login) | Interactive alerts (One-click fixes via Slack/app) |

| Bid Adjustment Execution | Requires secondary scripts with write access | Autonomous algorithmic bid management |

| False Positive Suppression | Basic rule thresholds (click counts) | Machine-learning seasonality smoothing |

| Audit Trail & Logging | Basic Google Apps Script execution logs | Complete enterprise change history logs |

For solo operators or teams managing a single account, custom scripts are a reliable first line of defense. However, growing agencies and high-volume advertisers managing dozens of client accounts often outgrow homemade JavaScript scripts. Managing API updates, updating auth credentials across MCCs, and troubleshooting script timeouts can quickly eat into your team's time.

Modern automated platforms like AdTurbo bridge this gap. Rather than simply alerting you that CPC surged after spend has already left your account, AdTurbo’s AI-driven system monitors accounts around the clock, detects abnormal auction spikes across broad and exact match sets, and autonomously adjusts bid caps in real time to stop budget bleed.

---

Advanced Troubleshooting: Script Errors & Slack Failures

When managing custom scripts, errors inevitably arise. Here are the root causes and remedies for the most frequent script failures.

1. Exception: Request failed for https://hooks.slack.com returned code 403

• The Cause: The Slack webhook URL has been revoked, or the Slack app was removed from the channel.

• The Fix: Go to api.slack.com/apps, select your app, open Incoming Webhooks, and verify that the target channel is still active. Generate a new webhook URL if necessary, update your CONFIG.SLACKWEBHOOKURL, and click Save.

2. Cannot read property 'cpc' of undefined

• The Cause: The script discovered a campaign that gathered clicks today, but had zero impressions or spend over the previous 14 days (e.g., a newly launched campaign).

• The Fix: Ensure your comparison loop includes a validation check: if (baseline && baseline.cpc 0). The complete code block provided in this guide already includes this check.

3. Script Timeout: Exceeded maximum execution time

• The Cause: Google Ads limits single-account script runs to 30 minutes, and multi-account MCC scripts to 60 minutes. If your account contains hundreds of thousands of active ad groups, iterating through raw campaign entities can time out.

• The Fix: Refine your GAQL query by adding strict filters, such as excluding campaigns with zero spend today (AND metrics.costmicros 0) or filtering strictly for campaign.status = 'ENABLED'.

4. Continuous False Positives on High-CPC Keywords

• The Cause: A campaign with a $50 average baseline CPC fluctuates to $71 on a single conversion query, tripping a strict 40% threshold despite standard variance.

• The Fix: Add a dual-threshold condition. Require both a percentage surge (e.g., +40%) AND an absolute dollar surge (e.g., (current.cpc - baseline.cpc) 5.00) before triggering an alert.

---

Related Guides

• How to Manage Google Ads (Without Becoming a PPC Expert)

• Why Is Google Ads So Expensive? 7 Reasons (And How to Pay Less)

• Google Ads Optimization Checklist: 15 Things to Check Every Week

---

Frequently Asked Questions

What does CPC mean in Google Ads?

CPC stands for Cost-Per-Click, which is the actual financial amount you pay each time a searcher clicks your advertisement. In Google Ads auctions, your final CPC is determined dynamically based on your bid, quality score, ad formats, and the competitive bids of rivals competing for the same search intent.

Why is my CPC so high on Google Ads?

High CPCs typically stem from intense competitor bidding, low Quality Scores, overly broad keyword matching that enters expensive auctions, or automated Smart Bidding strategies operating without target caps. Reviewing your search terms report and applying portfolio bid limits can help reduce excessive click costs.

Does Slack integrate with Google Ads natively?

Google Ads does not have an out-of-the-box native integration to post real-time auction performance alerts directly into Slack channels without third-party tooling. Advertisers must use Google Ads Scripts with incoming webhooks, connect via workflow automation tools like Zapier, or deploy dedicated PPC management software that includes built-in Slack alerts.

How much CPC is considered good for Google Ads?

A "good" CPC depends heavily on your industry, customer lifetime value, and profit margins. While consumer retail campaigns might target CPCs between $0.80 and $2.50, competitive B2B software, legal, and financial services regularly see viable, profitable CPCs ranging from $15.00 to over $80.00.

Google Verified Fully Automated

Get More Leads & Sales From Google Ads — On Autopilot

AdTurbo is your AI Google Ads agent, built by top Google Ads agency owners. AdTurbo works tirelessly in the background managing your Google Ads to get more leads and sales, while you focus on running your business.

Sign up with Google

7-day free trial. No contracts. Cancel anytime.