Skip to main content

Script examples

Ready-made snippets for common tasks. Copy any of them into the editor, adjust the thresholds for yourself and test with the ▶ Run now button. How the SDK commands and the schedule work is covered in the Writing a script section.

Attention

The examples contain real actions (pause). Before enabling a script on a schedule, test it on live data — if needed, temporarily comment out the lines with pause() and leave only console.log.

Pause by low ROAS​

Stops ads that spent more than $20 over the day but give a ROAS below 0.5.

JavaScript
function main() {
const ads = QubApp.ads()
.withCondition('spend_24h > 20 AND roas_24h < 0.5')
.get()

for (const ad of ads) {
console.log('pause', ad.name, 'roas24h=', ad.roas_24h)
ad.pause({ duration: '24h', reason: 'low roas' })
}
}

The condition is an SQL-level expression over all of the ad's metrics: comparisons, AND/OR/NOT, parentheses, arithmetic and field-to-field comparison; what else it may hold — Conditions in withCondition. A couple of tougher conditions:

JavaScript
// the day's spend is more than double the average geo payout, and there are no deposits
QubApp.ads().withCondition('deps_24h = 0 AND spend_24h > 2 * geo_avg_payout')

// profitability fell below half of the previous period's while the ad is still spending
QubApp.ads().withCondition('roas_24h < 0.5 * prev_roas_24h AND spend_24h > 20')

// either the three-day window paid off and the last day did not; or there are clicks but zero registrations
QubApp.ads().withCondition('(roas_72h > 1 AND roas_24h < 0.5) OR (clicks_24h > 100 AND regs_24h = 0)')

Pause with no deposits at high spend​

Stops ads that have not a single deposit over the day, while spend has already exceeded the average payout for the geo — that is, money is going out but there is no result.

JavaScript
function main() {
const ads = QubApp.ads()
.withCondition('deps_24h = 0 AND spend_24h > geo_avg_payout')
.get()

for (const ad of ads) {
console.log('pause (no deps)', ad.name, 'spend24h=', ad.spend_24h)
ad.pause({ duration: '24h', reason: 'no deposits' })
}
}

Memory between runs​

Remembers processed ads in ctx.state and skips them on subsequent runs, so as not to touch the same ones again.

JavaScript
function main() {
const seen = ctx.state.get('seen') || []

const ads = QubApp.ads()
.withCondition('roas_24h < 0.5 AND spend_24h > 20')
.get()

for (const ad of ads) {
if (seen.includes(ad.ad_id)) continue
ad.pause({ duration: '24h', reason: 'low roas' })
seen.push(ad.ad_id)
console.log('paused', ad.name)
}

ctx.state.set('seen', seen)
}

Sorting and limiting the selection​

Takes the five ads with the highest spend over the day and simply prints them to the console — a basis for reports and checks.

JavaScript
function main() {
const top = QubApp.ads()
.orderBy('spend_24h', 'desc')
.withLimit(5)
.get()

for (const ad of top) {
console.log(ad.name, 'spend24h=', ad.spend_24h, 'roas24h=', ad.roas_24h)
}
}

Working at the campaign level​

The commands are available not only for ads, but also for ad sets (QubApp.adsets()) and campaigns (QubApp.campaigns()). From a campaign you can get the nested ad sets and ads.

JavaScript
function main() {
const campaigns = QubApp.campaigns()
.withCondition('roas_24h < 0.3')
.get()

for (const c of campaigns) {
console.log('weak campaign', c.name)
for (const ad of c.getAds()) {
ad.pause({ duration: '12h', reason: 'weak campaign' })
}
}
}

Facebook requests​

The examples below combine three capabilities of a script: sql — a direct SQL query against your statistics (aggregates, GROUP BY, HAVING — any slice), fb — your own request to Facebook through your browser profile, fb.batch — a batch of such requests in one exchange. How the bridge works — the call form, the executor choice, the answer shape, the limits — is covered in Facebook Qubix Bridge.

All recipes use a response-parsing helper — three lines, declare it next to main():

JavaScript
function graph(res) {
if (res.status >= 400) throw new Error('Facebook refused: ' + res.status)
return res.text ? JSON.parse(res.text) : {}
}
Attention

fb requests go to the real Facebook. GET only reads, while POST changes live campaigns — test the reads first, and add the changing lines once you are sure of the selection.

Raising the budget of profitable campaigns — by your funnel​

Profitability is computed by a direct query against your statistics — deposits and revenue from the funnel, not just the ad account's numbers. Then an fb.batch reads the live budgets of all candidates from Facebook in one exchange, and each campaign's budget is raised by a step — with a ceiling and a cooldown, so the growth does not run away and does not break Facebook's learning.

JavaScript
function main() {
const ROAS_THRESHOLD = 1.5 // funnel profitability at which a campaign counts as profitable
const MIN_DEPS = 3 // deposits over the day; fewer — do not touch: too little data
const RAISE_STEP = 0.2 // the raise step: +20% to the current budget
const BUDGET_CEILING = 50000 // the daily budget ceiling, minor units of the account currency
const COOLDOWN_HOURS = 6 // the cooldown between raises of one campaign
function graph(res) {
if (res.status >= 400) throw new Error('Facebook refused: ' + res.status)
return res.text ? JSON.parse(res.text) : {}
}

// 1. Your own statistics: campaign profitability by FUNNEL revenue, not the ad account's numbers
const rows = sql`
SELECT campaign_id,
sum(spend_24h) AS spend,
sum(revenue_24h) AS revenue,
sum(deps_24h) AS deps
FROM v_ads_stats
GROUP BY campaign_id
HAVING spend > 0 AND deps >= ${MIN_DEPS} AND revenue / spend >= ${ROAS_THRESHOLD}
ORDER BY revenue / spend DESC`
if (!rows.length) { console.log('no profitable campaigns'); return }

const raisedAt = ctx.state.get('raisedAt') || {}
const due = rows.filter((r) => Date.now() - (raisedAt[r.campaign_id] || 0) >= COOLDOWN_HOURS * 3600 * 1000)
if (!due.length) { console.log('all candidates are cooling down'); return }

// 2. The live budgets of all candidates — in ONE exchange with Facebook
const ids = due.map((r) => r.campaign_id)
const budgets = fb.batch(fb.campaign(ids[0]), ids.map((id) => ({ method: 'GET', relativeUrl: `${id}?fields=name,daily_budget` })))

// 3. The raise — each campaign with its own thresholds
for (let i = 0; i < due.length; i++) {
const b = budgets[i]
if (b.code >= 400 || !b.data.daily_budget) continue // a refusal, or the budget is on the ad sets — do not touch

const current = Number(b.data.daily_budget)
const next = Math.min(Math.round(current * (1 + RAISE_STEP)), BUDGET_CEILING)
if (next <= current) continue // hit the ceiling

try {
const res = fb.campaign(due[i].campaign_id).request({
method: 'POST',
url: `https://graph.facebook.com/${due[i].campaign_id}`,
params: { daily_budget: String(next) },
})
graph(res)
raisedAt[due[i].campaign_id] = Date.now()
console.log('raised', b.data.name, current, '->', next,
'roas=', (due[i].revenue / due[i].spend).toFixed(2))
} catch (e) {
console.log('skip', b.data.name, String(e))
}
}

ctx.state.set('raisedAt', raisedAt)
}

The raise mark is set only after Facebook accepts the change — a failed attempt does not spend the cooldown. There is no need to re-read the budget right after the write: Facebook serves reads with a delay, check on the next run.

Cutting the budget of losing campaigns — the same technique​

The mirror query: spend is going, the funnel is silent. The budget is cut by a step but never below the floor — the campaign stays alive and can recover. The live budgets of all candidates are read in one exchange, the same way the raise recipe does it.

JavaScript
function main() {
const CUT_STEP = 0.2 // the cut step: −20%
const BUDGET_FLOOR = 1000 // the daily budget floor, minor units

const rows = sql`
SELECT campaign_id, sum(spend_24h) AS spend, sum(revenue_24h) AS revenue
FROM v_ads_stats
GROUP BY campaign_id
HAVING spend > 20 AND revenue / spend < 0.8
ORDER BY spend DESC`
if (!rows.length) return

// the live budgets of all candidates — in ONE exchange
const ids = rows.map((r) => r.campaign_id)
const budgets = fb.batch(fb.campaign(ids[0]), ids.map((id) => ({ method: 'GET', relativeUrl: `${id}?fields=name,daily_budget` })))

// the cut — a change stays a single request
for (let i = 0; i < rows.length; i++) {
const b = budgets[i]
if (b.code >= 400 || !b.data.daily_budget) continue // a refusal, or the budget is on the ad sets

const current = Number(b.data.daily_budget)
const next = Math.max(Math.round(current * (1 - CUT_STEP)), BUDGET_FLOOR)
if (next >= current) continue

try {
graph(fb.campaign(rows[i].campaign_id).request({
method: 'POST', url: `https://graph.facebook.com/${rows[i].campaign_id}`, params: { daily_budget: String(next) },
}))
console.log('cut', b.data.name, current, '->', next)
} catch (e) {
console.log('skip', rows[i].campaign_id, String(e))
}
}
}

Hourly control: spend grows, nothing comes back​

A direct query against the hourly table with honest deduplication via argMax: who spent money over the last hours without a single click. For those found — a diagnosis from Facebook itself, in a batch.

JavaScript
function main() {
const SPEND_MIN = 10 // account currency: the "already spent noticeably" threshold

const rows = sql`
SELECT ad_id, sum(spend) AS spend, sum(clicks) AS clicks
FROM (
SELECT ad_id, date, hour, traffic_source, website_id,
argMax(spend, parsed_at) AS spend,
argMax(clicks, parsed_at) AS clicks
FROM hourly_insights
WHERE date >= today() - 1
GROUP BY ad_id, date, hour, traffic_source, website_id
)
GROUP BY ad_id
HAVING spend > ${SPEND_MIN} AND clicks = 0
LIMIT 20`
if (!rows.length) { console.log('no such ads'); return }

const byId = {}
for (const ad of QubApp.ads().get()) byId[ad.ad_id] = ad

const ids = rows.map((r) => r.ad_id).filter((id) => byId[id])
if (!ids.length) return

const answers = fb.batch(fb.campaign(byId[ids[0]].campaign_id),
ids.map((id) => ({ method: 'GET', relativeUrl: `${id}?fields=effective_status,issues_info{error_summary,error_message,level}` })))

for (let i = 0; i < ids.length; i++) {
const a = answers[i]
if (a.code >= 400) { console.log(ids[i], 'code', a.code); continue }
console.log(byId[ids[i]].name, a.data.effective_status,
a.data.issues_info ? JSON.stringify(a.data.issues_info) : 'no issues')
}
}

A geo slice from your own database → a console report​

No Facebook at all — pure SQL: the countries with spend over the last three days but profitability below one, with each geo's share of the total spend.

JavaScript
function main() {
const rows = sql`
SELECT primary_country AS country,
sum(spend_72h) AS spend,
sum(revenue_72h) AS revenue,
round(revenue / spend, 2) AS roas,
round(100 * spend / sum(spend) OVER (), 1) AS spend_share
FROM v_ads_stats
WHERE spend_72h > 0
GROUP BY primary_country
HAVING roas < 1
ORDER BY spend DESC`

for (const r of rows) {
console.log(r.country, 'spend:', r.spend, 'revenue:', r.revenue, 'ROAS:', r.roas, 'spend share %:', r.spend_share)
}
}

Account money: spend, limit, billing threshold​

Takes a live profile of the first active campaign and prints, for each of its accounts, the total spend, the daily limit and the billing threshold.

JavaScript
function main() {
const c = QubApp.campaigns().withCondition('spend_24h > 0').first()
if (!c) { console.log('no active campaigns'); return }

const p = c.getProfiles().find((x) => x.tokenAlive && !x.onCheckpoint)
if (!p) { console.log('no live profile'); return }

const data = graph(fb.profile(p.id).request({
url: 'https://graph.facebook.com/me/adaccounts',
params: { limit: 50, fields: 'name,account_id,account_status,amount_spent,adtrust_dsl,adspaymentcycle,currency' },
}))

for (const acc of data.data || []) {
const cycle = acc.adspaymentcycle && acc.adspaymentcycle.data && acc.adspaymentcycle.data[0]
console.log(acc.name,
'spent:', acc.amount_spent, acc.currency,
'daily limit:', acc.adtrust_dsl || '-',
'billing threshold:', cycle ? cycle.threshold_amount / 100 : '-')
}
}

Facebook returns the amounts in minor units of the account currency; the billing threshold is additionally divided by 100. The result is handy to send to your messenger with ctx.fetch — add the address to Fetch host list on the JavaScript tab.

Ad set targeting — in a batch, what the reports do not have​

The ad set identifiers come from your statistics with one SQL query, and their settings — in one exchange with Facebook.

JavaScript
function main() {
const rows = sql`
SELECT DISTINCT adset_id, any(campaign_id) AS campaign_id
FROM v_ads_stats
WHERE spend_24h > 0 AND adset_id != ''
GROUP BY adset_id
LIMIT 25`
if (!rows.length) return

const answers = fb.batch(fb.campaign(rows[0].campaign_id),
rows.map((r) => ({ method: 'GET', relativeUrl: `${r.adset_id}?fields=name,optimization_goal,daily_budget,targeting` })))

for (const a of answers) {
if (a.code >= 400) continue
console.log(a.data.name, a.data.optimization_goal, JSON.stringify(a.data.targeting))
}
}

Checking session health on a schedule​

Walks the profiles of your active campaigns and asks Facebook me — a session that is no longer valid is discovered before your campaigns feel it. Deliberately one by one, not a batch: each check must travel through the very profile being checked, while a batch would leave through a single executor.

JavaScript
function main() {
const seen = {}
const campaigns = QubApp.campaigns().withCondition('spend_24h > 0').get()

for (const c of campaigns) {
for (const p of c.getProfiles()) {
if (seen[p.id]) continue
seen[p.id] = true

try {
const res = fb.profile(p.id).request({ url: 'https://graph.facebook.com/me', params: { fields: 'id,name' } })
if (res.status >= 400) {
let reason = res.status
try { reason = JSON.parse(res.text).error.message } catch (e) {} // a checkpoint page is not JSON
console.log('SESSION NOT VALID:', p.name, reason)
continue
}
console.log('ok:', p.name, '→', JSON.parse(res.text).name)
} catch (e) {
console.log('delivery failed:', p.name, String(e))
}
}
}
}

Walks the profile's fan pages, takes the fresh posts and prints the comments with links. The reads travel as batches, stage by stage; the deletion line is left commented out — enable it once you are sure of the selection.

JavaScript
function main() {
const c = QubApp.campaigns().first()
if (!c) return
const p = c.getProfiles().find((x) => x.tokenAlive && !x.onCheckpoint)
if (!p) { console.log('no live profile'); return }

const pages = graph(fb.profile(p.id).request({ url: 'https://graph.facebook.com/me/accounts', params: { limit: 25 } }))
const pageList = pages.data || []
if (!pageList.length) return

// the fresh posts of ALL pages — one batch
const postRows = fb.batch(fb.profile(p.id),
pageList.map((pg) => ({ method: 'GET', relativeUrl: `${pg.id}/published_posts?limit=5` })))
const posts = []
for (let i = 0; i < pageList.length; i++) {
if (postRows[i].code >= 400) continue
for (const po of postRows[i].data.data || []) posts.push({ page: pageList[i].name, id: po.id })
}
if (!posts.length) return

// the comments of ALL posts — one batch
const comRows = fb.batch(fb.profile(p.id),
posts.map((po) => ({ method: 'GET', relativeUrl: `${po.id}/comments?fields=id,message,from,created_time&limit=100` })))

for (let i = 0; i < posts.length; i++) {
if (comRows[i].code >= 400) continue
for (const cm of comRows[i].data.data || []) {
if ((cm.message || '').indexOf('http') !== -1) {
console.log('suspicious link:', posts[i].page, cm.created_time, cm.message)
// fb.profile(p.id).request({ method: 'DELETE', url: `https://graph.facebook.com/${cm.id}` }) // delete the comment
}
}
}
}
Tip

With many pages, the script can still hit the run time limit — narrow the walk (fewer posts per page) or spread the pages across runs via ctx.state. The built-in comment cleanup with a log is the Comment cleanup section.

Reporting conversions to your traffic source​

A source that pays for results has to hear about them, each in its own format. That is a whole article of its own, with a ready script: Sending events to your source.

Writing into your own database​

A summary from your statistics can go straight into your own database — with no HTTP middleman. A ready script that writes the day's deposits by country with a single insert, and a full walkthrough of the Qubix.db command, are in the Your own databases: Qubix.db article.

A daily digest in Telegram​

Your own numbers, grouped the way you want them, arrive where your team already looks. Replace the country column in the query with another column of the event table — for example offer_id or pwa_id — and the same script reports a different slice. The column is written right in the query text: a value substituted through ${…} goes out as a parameter and cannot be a column name. Deposits are counted the way the panel's reports count them: a dep event counts only when its revenue is above the deposit threshold. The campaign_id (the tracker campaign) and sub_id_1 … sub_id_16 columns are filled on visits: a deposit arrives by postback without them, and so do most registrations, so in a slice by these columns deposits and revenue come out empty and registrations incomplete.

daily-digest.jsJavaScript
function main() {
const options = {
telegram: {
botToken: '123456:AA...', // your bot token from @BotFather
chatId: '-1001234567890', // where the digest goes
},
days: 1,
top: 10,
}

// The slice is the country column in two places of the query below; change it in both.
const rows = sql`
WITH (SELECT threshold FROM v_deposits_min_revenue) AS dep_min,
if(edition = 'cancel', -1, 1) AS weight
SELECT country AS bucket,
countIf(event = 'campaign_visit') AS clicks,
countIf(event = 'installed') AS installs,
sumIf(weight, event = 'reg') AS regs,
sumIf(weight, event = 'dep' AND revenue_usd > dep_min) AS deps,
round(sumIf(revenue_usd * weight, event = 'dep' AND revenue_usd > dep_min), 2) AS revenue
FROM qubix_events
WHERE event_time > now() - INTERVAL ${options.days} DAY
AND country != ''
GROUP BY bucket
ORDER BY clicks DESC
LIMIT ${options.top}`

if (rows.length === 0) {
console.log('no data for the period')
return
}

const lines = ['*Last ' + options.days + 'd*', '']
for (const r of rows) {
lines.push(
r.bucket + ': ' + r.clicks + ' clicks, ' + r.installs + ' inst, ' +
r.regs + ' reg, ' + r.deps + ' dep, $' + r.revenue
)
}

const answer = ctx.fetch('https://api.telegram.org/bot' + options.telegram.botToken + '/sendMessage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: options.telegram.chatId,
text: lines.join('\n'),
parse_mode: 'Markdown',
}),
})

console.log(answer.ok ? 'digest sent' : 'telegram refused: ' + answer.status + ' ' + answer.body)
}
Attention

Add api.telegram.org to the allowed addresses: Qubix settings → JavaScript, otherwise the request is refused.

Running campaigns from Telegram​

Pause and resume campaigns with a message, and ask for the numbers of the last 24 hours without opening the panel. The script reads its bot's new messages once a minute and executes what it recognizes.

telegram-commands.jsJavaScript
function main() {
const options = {
telegram: {
botToken: '123456:AA...',
allowedFrom: [123456789], // your own Telegram user ids — nobody else is obeyed
},
pauseFor: '6h',
}
function handle(text) {
const [command, name] = text.split(/\s+/, 2)
if (command === '/stop' && name) {
const campaign = QubApp.campaigns().withCondition('campaign_name = ' + quote(name)).first()
if (!campaign) return 'campaign not found: ' + name
campaign.pause({ duration: options.pauseFor, reason: 'stopped from Telegram' })
return 'pause requested for ' + options.pauseFor + ': ' + name
}
if (command === '/start' && name) {
const campaign = QubApp.campaigns().withCondition('campaign_name = ' + quote(name)).first()
if (!campaign) return 'campaign not found: ' + name
campaign.activate({ reason: 'started from Telegram' })
return 'start requested: ' + name
}
if (command === '/stats') {
const row = sql`
WITH (SELECT threshold FROM v_deposits_min_revenue) AS dep_min,
if(edition = 'cancel', -1, 1) AS weight
SELECT sumIf(weight, event = 'reg') AS regs,
sumIf(weight, event = 'dep' AND revenue_usd > dep_min) AS deps,
round(sumIf(revenue_usd * weight, event = 'dep' AND revenue_usd > dep_min), 2) AS revenue
FROM qubix_events
WHERE event_time > now() - INTERVAL 1 DAY`[0]
return 'last 24h: ' + row.regs + ' reg, ' + row.deps + ' dep, $' + row.revenue
}
return 'commands: /stop <campaign>, /start <campaign>, /stats'
}
function quote(value) {
return "'" + String(value).replace(/'/g, "\\'") + "'"
}
function reply(chatId, text) {
ctx.fetch('https://api.telegram.org/bot' + options.telegram.botToken + '/sendMessage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId, text: text }),
})
}

// getUpdates returns messages newer than the offset we acknowledge, so the offset
// is what makes each command execute exactly once.
const offset = ctx.state.get('tg_offset') || 0

const answer = ctx.fetch(
'https://api.telegram.org/bot' + options.telegram.botToken + '/getUpdates?timeout=0&offset=' + offset,
{ method: 'GET', timeout_ms: 10000 }
)
if (!answer.ok) {
console.log('telegram refused:', answer.status)
return
}

const updates = JSON.parse(answer.body).result || []
let lastId = offset

for (const u of updates) {
lastId = u.update_id + 1
const msg = u.message
if (!msg || !msg.text) continue

// Anyone can write to a bot. Without this check a stranger would be pausing
// your campaigns.
if (options.telegram.allowedFrom.indexOf(msg.from.id) === -1) {
console.log('ignored a message from', msg.from.id)
continue
}

reply(msg.chat.id, handle(msg.text.trim()))
}

// Saved once at the end: if the run breaks off, the same commands are read again
// rather than silently skipped.
ctx.state.set('tg_offset', lastId)
}

Two details make this safe rather than merely convenient. The offset is what makes a command run exactly once: Telegram keeps returning a message until you acknowledge it, and the offset is saved only at the end of the run, so a run that breaks off re-reads the commands instead of losing them. The allowed-senders list matters even more: anyone can find a bot and write to it, and without that check a stranger would be pausing your campaigns.

The replies say "requested", not "paused": pause() and activate() are carried out only after the run ends, while the reply leaves during the run — see When pause and activate take effect. The campaign is looked up by campaign_name, not by name — why, see Conditions in withCondition.

What's next​