スクリプトの例
よくある作業のためのすぐに使えるコード例です。どれでもエディターにコピーし、しきい値を自分の条件に合わせて調整し、▶ 実行 ボタンでテストしてください。SDK のコマンドとスケジュールの仕組みは スクリプトの作成 セクションで説明しています。
例には実際のアクション(pause)が含まれています。スクリプトをスケジュールで有効にする前に、実データでテストしてください。必要に応じて pause() の行を一時的にコメントアウトし、console.log だけを残してください。
ROAS が低い場合の停止
1 日で 20 ドルを超えて消化したのに、ROAS が 0.5 を下回る広告を停止します。
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 の条件 をご覧ください。もう少し厳しい条件の例:
// 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)')
消化額が大きいのにデポジットがない場合の停止
1 日でデポジットが 1 件もないのに、消化額がその地域の平均ペイアウトをすでに超えている広告を停止します。つまり、お金は出ていくのに成果がない状態です。
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 に記憶し、以降の実行ではスキップして、同じ広告に再び手を加えないようにします。
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)
}
選択の並べ替えと件数制限
1 日の消化額が最も大きい広告を 5 件取得し、コンソールに出力するだけです。レポートやチェックの土台になります。
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())でも使えます。キャンペーンからは、その中の広告セットと広告を取得できます。
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 へのリクエスト
以下の例は、スクリプトの 3 つの機能を組み合わせています。sql — 自分の統計に対する ClickHouse への直接クエリ(集計、GROUP BY、HAVING など、どんな切り口でも)、fb — ブラウザプロファイル経由で Facebook に送る独自のリクエスト、fb.batch — そうしたリクエストを 1 回のやり取りにまとめたバッチです。ブリッジの仕組み(呼び出し方、実行プロファイルの選択、応答の形、制限)は Facebook Qubix Bridge で説明しています。
すべてのレシピは応答を解析するヘルパー関数を使います。3 行なので、main() の隣に宣言してください:
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 から 1 回のやり取りで読み取り、各キャンペーンの予算を 1 段階ずつ上げます。増加が自己増幅したり Facebook の学習を壊したりしないよう、上限とクールダウンを設けています。
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 は読み取り結果を遅れて返すので、次回の実行で確認してください。
赤字のキャンペーンの予算を下げる — 同じ手法
逆向きのクエリです。消化は続いているのに、ファネルは沈黙しています。予算は 1 段階ずつ下げますが、下限より下には決して下げません。キャンペーンは生き残り、回復する可能性があります。すべての候補の現在の予算は、引き上げのレシピと同じく 1 回のやり取りで読み取ります。
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 による正確な重複排除を行う時間別テーブルへの直接クエリです。直近数時間でクリックが 1 件もないままお金を使ったものを探します。見つかったものについては、Facebook 自身の診断をバッチで取得します。
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 だけで行います。3 日間で消化があるのに収益性が 1 を下回る国を、総消化額に占める各地域の割合とともに表示します。
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)
}
}
アカウントのお金:消化額、上限、請求しきい値
最初のアクティブなキャンペーンの生きているプロファイルを取り、その各広告アカウントについて総消化額、1 日の上限、請求しきい値を出力します。
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 ホスト許可リスト フィールドに追加してください。
広告セットのターゲティング — バッチで、レポートにない情報を
広告セットの ID は自分の統計から 1 回の SQL クエリで取得し、その設定は Facebook との 1 回のやり取りで取得します。
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 を問い合わせます。無効になったセッションを、キャンペーンに影響が出る前に発見できます。あえてバッチではなく 1 つずつ行います。各チェックは確認対象のプロファイル自身を通る必要があり、バッチでは 1 つの実行プロファイルからしか送られないためです。
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))
}
}
}
}
ページ投稿のコメント:仕込まれたリンクを見つける
プロファイルのファンページを順に回り、最新の投稿を取得して、リンクを含むコメントを出力します。読み取りは段階ごとにバッチで行います。削除の行はコメントアウトしてあるので、選択に確信が持てたら有効にしてください。
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 の仲介なしに、そのまま自分のデータベースに書き込めます。1 日のデポジットを国別に 1 回の挿入で書き込むスクリプトの完成例と、Qubix.db コマンドの完全な解説は、ご自身のデータベース: Qubix.db の記事にあります。
Telegram での日次サマリー
自分の数字を好きな形でまとめ、チームがいつも見ている場所に届けます。
クエリの country 列をイベントテーブルの他の列(たとえば offer_id や pwa_id)に置き換えれば、
同じスクリプトが別の切り口でレポートします。列名はクエリ文の中に直接書きます。${…} で埋め込んだ値は
パラメーターとして渡されるため、列名にはできません。
デポジットはパネルのレポートと同じ方法で数えます。dep イベントは、収益がデポジットのしきい値を
上回る場合にのみカウントされます。
campaign_id(トラッカーのキャンペーン)と sub_id_1 … sub_id_16 の列は訪問時に記録されます。デポジットはこれらの列を持たない
ポストバックで届き、登録もほとんどが同様です。そのため、これらの列で切り分けるとデポジットと収益は空になり、登録は一部しか数えられません。
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)
}
api.telegram.org を Qubix設定 → JavaScript の許可アドレスに追加してください。追加しないとリクエストは拒否されます。
Telegram からキャンペーンを操作する
メッセージ 1 つでキャンペーンを停止・再開し、パネルを開かずに過去24時間の数字を確認できます。 スクリプトは 1 分に 1 回ボットの新着メッセージを読み、認識したコマンドを実行します。
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)
}
便利なだけでなく安全にしているのは、2 つの工夫です。offset は、コマンドをちょうど 1 回だけ 実行させる仕組みです。Telegram は確認されるまでメッセージを返し続け、offset は 実行の最後にだけ保存されるので、途中で止まった実行はコマンドを失うのではなく読み直します。 許可された送信者のリスト はさらに重要です。ボットは誰でも見つけて書き込めるので、 このチェックがなければ見知らぬ人があなたのキャンペーンを停止できてしまいます。
返信には、「一時停止しました」ではなく「一時停止を要求しました」と書かれています。pause() と activate() は
実行が終わった後にだけ行われる一方、返信は実行の最中に送られるためです。詳しくは
一時停止と再開が反映されるタイミング を参照してください。
キャンペーンは name ではなく campaign_name で検索します。その理由は
withCondition の条件 を参照してください。