跳到主要内容

脚本示例

常见任务的现成代码片段。把任意一段复制到编辑器,按自己的需要调整阈值,然后用 ▶ 立即运行 按钮测试。SDK 命令和计划任务的工作方式见 编写脚本 一节。

注意

示例中包含真实操作(pause)。在让脚本按计划任务运行之前,请先在实时数据上测试——必要时暂时注释掉含 pause() 的行,只保留 console.log。

ROAS 过低时暂停​

暂停当天花费超过 $20、但 ROAS 低于 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' })
}
}

条件是作用于广告全部指标的 SQL 级表达式:比较、AND/OR/NOT、括号、算术运算以及字段与字段的比较;条件里还能写什么——见 withCondition 中的条件。再看几个更严格的条件:

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)')

花费很高却没有充值时暂停​

暂停当天一笔充值都没有、而花费已超过该地区平均佣金的广告——也就是钱在流出,却没有结果。

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' })
}
}

多次运行之间的记忆​

把已处理的广告记在 ctx.state 中,并在之后的运行中跳过它们,避免重复处理同一批广告。

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)
}

对选择结果排序并限制数量​

取当天花费最高的五个广告,直接输出到控制台——可作为报告和检查的基础。

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)
}
}

在广告系列层级操作​

这些命令不仅适用于广告,也适用于广告组(QubApp.adsets())和广告系列(QubApp.campaigns())。从一个广告系列可以取得其中的广告组和广告。

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 请求​

下面的示例结合了脚本的三种能力:sql —— 直接对自己的统计数据执行 ClickHouse 查询(聚合、GROUP BY、HAVING——任意维度),fb —— 通过您的浏览器配置文件向 Facebook 发送您自己的请求,fb.batch —— 在一次往返中发送一批这样的请求。桥接的工作方式——调用形式、执行配置文件的选择、应答结构、限制——见 Facebook Qubix Bridge。

所有示例都使用一个解析应答的辅助函数——三行代码,请在 main() 旁边声明它:

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

fb 请求会发往真实的 Facebook。GET 只读取,而 POST 会修改正在投放的广告系列——请先测试读取部分,确认选择结果无误后再加入修改的代码行。

提高盈利广告系列的预算——依据您自己的漏斗​

盈利能力通过直接查询自己的统计数据来计算——使用漏斗中的充值和收入,而不只是广告账户里的数字。随后由一个 fb.batch 在一次往返中从 Facebook 读取所有符合条件的广告系列的当前预算,并将每个广告系列的预算提高一档——设有上限和冷却期,使增长不会自我放大,也不会破坏 Facebook 的学习。

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)
}

只有在 Facebook 接受更改之后才会记下提升标记——失败的尝试不会消耗冷却期。写入后无需立即重新读取预算:Facebook 返回的读取结果有延迟,请在下次运行时检查。

降低亏损广告系列的预算——同样的方法​

反向的查询:花费还在继续,漏斗却毫无动静。预算逐档降低,但绝不会低于下限——广告系列保持存活,仍有机会恢复。所有符合条件的广告系列的当前预算同样在一次往返中读取,与提升预算的示例相同。

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))
}
}
}

按小时监控:花费在增长,却没有任何回报​

对小时表的直接查询,并通过 argMax 做可靠的去重:找出最近几个小时里一次点击都没有却在花钱的对象。对找到的对象——批量获取 Facebook 本身给出的诊断。

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')
}
}

从自己的数据库按地区切分 → 控制台报告​

完全不用 Facebook——只用 ClickHouse:列出三天内有花费但盈利能力低于一的国家,并给出每个地区在总花费中的占比。

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)
}
}

账户的钱:花费、限额、账单阈值​

取第一个活跃广告系列的一个有效配置文件,并为其每个广告账户输出总花费、每日限额和账单阈值。

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 以账户币种的最小单位返回金额;账单阈值还需要再除以 100。结果可以方便地用 ctx.fetch 发送到您的即时通讯工具——请把该地址添加到 JavaScript 标签页的 fetch 主机允许列表 字段中。

广告组定位——一次批量拿到报告里没有的信息​

广告组的标识通过一条 SQL 查询从您的统计数据中取得,它们的设置则通过与 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))
}
}

按计划检查会话状态​

逐个检查活跃广告系列的配置文件,并向 Facebook 询问 me——不再有效的会话,会在您的广告系列受到影响之前就被发现。这里刻意逐个进行而不用批量:每次检查都必须经过被检查的那个配置文件本身,而批量请求只会从一个执行配置文件发出。

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))
}
}
}
}

逐个检查配置文件的粉丝主页,取最新的帖子,并输出含链接的评论。读取按阶段分批进行;删除那一行保持注释状态——确认选择结果无误后再启用。

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
}
}
}
}
提示

主页很多时,脚本仍可能触及运行时间上限——请缩小遍历范围(每个主页少取几条帖子),或通过 ctx.state 把主页分散到多次运行中。带日志的内置评论清理见 评论清理 一节。

向流量来源回传转化​

按结果付费的来源需要得知这些结果,而且每个来源都有自己的格式。为此有 一篇单独的文章,附带现成的脚本:向您的来源发送事件。

写入您自己的数据库​

您统计数据中的汇总可以直接写入您自己的数据库——无需 HTTP 中间环节。一个用一条插入语句写入当天各国充值的现成脚本,以及 Qubix.db 命令的完整指南,都在 您自己的数据库:Qubix.db 一文中。

Telegram 每日摘要​

您自己的数字,按您想要的方式分组,发送到团队本来就会看的地方。把查询中的 country 列换成事件表中的其他列——例如 offer_id 或 pwa_id—— 同一个脚本就会报告另一个维度。列名直接写在查询文本里:通过 ${…} 代入的值是作为参数发出的,不能充当列名。 充值的统计方式与面板报表相同:只有收入高于充值阈值的 dep 事件才会计入。 campaign_id(追踪器活动)和 sub_id_1 … sub_id_16 列在访问时填写:充值通过回传到达,不带这些列, 大多数注册也是如此,因此按这些列分组时,充值和收入为空,注册也不完整。

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)
}
注意

请在 Qubix 设置 → JavaScript 中把 api.telegram.org 添加到允许的地址,否则请求会被拒绝。

通过 Telegram 管理广告系列​

用一条消息暂停和恢复广告系列,不打开面板就能查看最近 24 小时的数字。 脚本每分钟读取一次其机器人的新消息,并执行它能识别的指令。

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)
}

有两个细节让这种做法不只是方便,而且安全。offset 让每条指令 恰好执行一次:在您确认之前,Telegram 会一直返回同一条消息,而 offset 只在运行结束时保存,因此中途中断的运行会重新读取指令,而不会丢失它们。 允许的发送者列表 更为重要:任何人都能找到机器人并给它发消息,如果没有 这项检查,陌生人就能暂停您的广告系列。

回复里写的是「requested」,而不是「paused」:pause() 和 activate() 只在运行结束之后才执行,而回复是在运行期间发出的——见 暂停与恢复何时生效。查找广告系列用的是 campaign_name,而不是 name——原因见 withCondition 中的条件。

下一步​