मुख्य कंटेंट तक स्किप करें

स्क्रिप्ट के उदाहरण

आम कार्यों के लिए तैयार कोड अंश। इनमें से किसी को भी एडिटर में कॉपी करें, सीमाएँ अपने हिसाब से बदलें और ▶ अभी चलाएँ बटन से जाँचें। 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 होस्ट allowlist फ़ील्ड में जोड़ें।

विज्ञापन सेट की टार्गेटिंग — एक बैच में, जो रिपोर्ट में नहीं है​

विज्ञापन सेट के पहचानकर्ता आपके आँकड़ों से एक 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)
}
ध्यान दें

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 केवल रन के अंत में सहेजा जाता है, इसलिए बीच में रुका रन कमांड खोने के बजाय उन्हें फिर से पढ़ता है। अनुमत प्रेषकों की सूची और भी ज़्यादा मायने रखती है: कोई भी बॉट ढूँढकर उसे लिख सकता है, और इस जाँच के बिना कोई अजनबी आपके कैंपेन रोक रहा होता।

उत्तरों में «अनुरोध किया गया» लिखा है, «रोका गया» नहीं: pause() और activate() रन समाप्त होने के बाद ही निष्पादित होते हैं, जबकि उत्तर रन के दौरान ही चला जाता है — देखें पॉज़ और वापसी कब प्रभावी होते हैं। कैंपेन name से नहीं, campaign_name से खोजा जाता है — क्यों, देखें withCondition में शर्तें।

आगे क्या​

On this page