Skip to main content

ตัวอย่างสคริปต์

โค้ดสำเร็จรูปสำหรับงานที่พบบ่อย คัดลอกตัวอย่างใดก็ได้ไปยังตัวแก้ไข ปรับเกณฑ์ให้เหมาะกับคุณ แล้วทดสอบด้วยปุ่ม ▶ รันเลย วิธีการทำงานของคำสั่ง 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)')

หยุดเมื่อไม่มียอดฝากทั้งที่ใช้จ่ายสูง​

หยุดโฆษณาที่ไม่มียอดฝากแม้แต่ครั้งเดียวในหนึ่งวัน ขณะที่ยอดใช้จ่ายเกินค่าตอบแทนเฉลี่ยของ geo นั้นไปแล้ว — กล่าวคือเงินออกไปแต่ไม่มีผลลัพธ์

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

มุมมองตาม geo จากฐานข้อมูลของคุณเอง → รายงานในคอนโซล​

ไม่ใช้ Facebook เลย — ใช้ ClickHouse ล้วน: ประเทศที่มียอดใช้จ่ายในสามวันแต่ความสามารถในการทำกำไรต่ำกว่าหนึ่ง พร้อมสัดส่วนของแต่ละ geo ในยอดใช้จ่ายรวม

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 — เพิ่มที่อยู่นั้นลงในช่อง รายการโฮสต์ที่อนุญาตสำหรับ fetch บนแท็บ JavaScript

การกำหนดกลุ่มเป้าหมายของชุดโฆษณา — ในแบตช์เดียว ข้อมูลที่รายงานไม่มี​

รหัสชุดโฆษณามาจากสถิติของคุณด้วยคิวรี 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 (แคมเปญของ tracker) และ sub_id_1 … sub_id_16 ถูกเติมตอนเข้าชม: ยอดฝากเข้ามาทาง postback โดยไม่มีคอลัมน์เหล่านี้ การลงทะเบียนส่วนใหญ่ก็เช่นกัน ดังนั้นเมื่อแบ่งตามคอลัมน์เหล่านี้ ยอดฝากและรายได้จะว่างเปล่า และการลงทะเบียนจะไม่ครบ

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)
}
ข้อควรระวัง

เพิ่ม api.telegram.org ลงในที่อยู่ที่อนุญาตใน การตั้งค่า Qubix → JavaScript มิฉะนั้นคำขอจะถูกปฏิเสธ

ควบคุมแคมเปญจาก 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

ขั้นตอนถัดไป​

On this page