Ana içeriğe geç

Script örnekleri

Yaygın görevler için hazır kod parçaları. Herhangi birini düzenleyiciye kopyalayın, eşikleri kendinize göre ayarlayın ve ▶ Çalıştır düğmesiyle test edin. SDK komutlarının ve zamanlamanın nasıl çalıştığı Bir script yazmak bölümünde anlatılmıştır.

Dikkat

Örnekler gerçek eylemler içerir (pause). Bir scripti zamanlamaya göre etkinleştirmeden önce canlı veriler üzerinde test edin — gerekirse pause() içeren satırları geçici olarak yorum satırına alın ve yalnızca console.log bırakın.

Düşük ROAS'ta duraklatma​

Gün içinde 20 dolardan fazla harcayan ancak 0,5'in altında ROAS veren reklamları durdurur.

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

Koşul, reklamın tüm metrikleri üzerinde SQL düzeyinde bir ifadedir: karşılaştırmalar, AND/OR/NOT, parantezler, aritmetik ve alanın alanla karşılaştırılması; koşulun başka neler içerebileceği — withCondition içindeki koşullar. Birkaç daha zorlu koşul:

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

Yüksek harcamada depozito yoksa duraklatma​

Gün içinde tek bir depozitosu olmayan, ancak harcaması geo için ortalama ödemeyi çoktan aşmış reklamları durdurur — yani para gidiyor ama sonuç yok.

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

Çalıştırmalar arasında bellek​

İşlenen reklamları ctx.state içinde hatırlar ve sonraki çalıştırmalarda atlar; böylece aynı reklamlara yeniden dokunulmaz.

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

Seçimi sıralama ve sınırlama​

Gün içinde en yüksek harcamaya sahip beş reklamı alır ve yalnızca konsola yazdırır — raporlar ve kontroller için bir temel.

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

Kampanya düzeyinde çalışma​

Komutlar yalnızca reklamlar için değil, reklam setleri (QubApp.adsets()) ve kampanyalar (QubApp.campaigns()) için de kullanılabilir. Bir kampanyadan, içindeki reklam setlerini ve reklamları alabilirsiniz.

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 istekleri​

Aşağıdaki örnekler bir scriptin üç yeteneğini birleştirir: sql — kendi istatistiklerinize doğrudan bir ClickHouse sorgusu (toplamalar, GROUP BY, HAVING — her türlü kesit), fb — tarayıcı profiliniz üzerinden Facebook'a kendi isteğiniz, fb.batch — bu tür isteklerden oluşan ve tek bir gidiş-dönüşte giden bir paket. Köprünün nasıl çalıştığı — çağrı biçimi, yürütücü profil seçimi, yanıtın yapısı, sınırlar — Facebook Qubix Bridge bölümünde anlatılmıştır.

Tüm tarifler yanıtı ayrıştıran bir yardımcı fonksiyon kullanır — üç satır, bunu main() fonksiyonunun yanında tanımlayın:

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

fb istekleri gerçek Facebook'a gider. GET yalnızca okur, POST ise çalışan kampanyaları değiştirir — önce okumaları test edin, değişiklik yapan satırları ise seçimden emin olduğunuzda ekleyin.

Kârlı kampanyaların bütçesini artırmak — kendi hunize göre​

Kârlılık, kendi istatistiklerinize doğrudan bir sorguyla hesaplanır — yalnızca reklam hesabının rakamları değil, huniden gelen depozitolar ve gelir. Ardından bir fb.batch, tüm adayların güncel bütçelerini Facebook'tan tek bir gidiş-dönüşte okur ve her kampanyanın bütçesi bir adım artırılır — büyüme kendi kendini beslemesin ve Facebook'un öğrenmesini bozmasın diye bir üst sınır ve bekleme süresiyle.

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

Artırma işareti yalnızca Facebook değişikliği kabul ettikten sonra konur — başarısız bir deneme bekleme süresini harcamaz. Yazmadan hemen sonra bütçeyi yeniden okumaya gerek yoktur: Facebook okumaları gecikmeli verir, bir sonraki çalıştırmada kontrol edin.

Zarar eden kampanyaların bütçesini düşürmek — aynı teknik​

Tersine sorgu: harcama sürüyor, huni sessiz. Bütçe bir adım düşürülür, ancak asla alt sınırın altına inmez — kampanya ayakta kalır ve toparlanabilir. Tüm adayların güncel bütçeleri, artırma tarifindeki gibi tek bir gidiş-dönüşte okunur.

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

Saatlik kontrol: harcama artıyor, hiçbir şey geri gelmiyor​

argMax ile dürüst tekilleştirme yapan, saatlik tabloya doğrudan bir sorgu: son saatlerde tek bir tıklama bile almadan para harcayanlar. Bulunanlar için — Facebook'un kendisinden, toplu bir teşhis.

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

Kendi veritabanınızdan geo kesiti → konsolda rapor​

Hiç Facebook yok — saf ClickHouse: üç gün içinde harcama olan ama kârlılığın birin altında olduğu ülkeler, her geo'nun toplam harcamadaki payıyla.

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

Hesabın parası: harcama, limit, fatura eşiği​

İlk aktif kampanyanın canlı bir profilini alır ve her reklam hesabı için toplam harcamayı, günlük limiti ve fatura eşiğini yazdırır.

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 tutarları hesap para biriminin en küçük biriminde döndürür; fatura eşiği ayrıca 100'e bölünür. Sonucu ctx.fetch ile mesajlaşma uygulamanıza göndermek kolaydır — adresi JavaScript sekmesindeki Fetch ana bilgisayar izin listesi alanına ekleyin.

Reklam seti hedeflemesi — toplu olarak, raporlarda olmayanlar​

Reklam seti kimlikleri kendi istatistiklerinizden tek bir SQL sorgusuyla, ayarları ise Facebook ile tek bir gidiş-dönüşte gelir.

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

Oturum sağlığını zamanlamaya göre kontrol etmek​

Aktif kampanyalarınızın profillerini dolaşır ve Facebook'a me sorar — artık geçerli olmayan bir oturum, kampanyalarınız bunu hissetmeden önce ortaya çıkar. Bilerek tek tek, toplu değil: her kontrol tam da kontrol edilen profilden geçmelidir, toplu paket ise tek bir yürütücü üzerinden çıkardı.

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

Profilin hayran sayfalarını dolaşır, yeni gönderileri alır ve bağlantı içeren yorumları yazdırır. Okumalar aşama aşama toplu olarak gider; silme satırı yorum satırı olarak bırakılmıştır — seçimden emin olduğunuzda etkinleştirin.

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
}
}
}
}
İpucu

Çok sayıda sayfada script yine de çalışma süresi sınırına takılabilir — dolaşmayı daraltın (sayfa başına daha az gönderi) ya da sayfaları ctx.state üzerinden çalıştırmalara dağıtın. Günlük kaydıyla birlikte yerleşik yorum temizleme, Yorum temizleme bölümündedir.

Dönüşümleri trafik kaynağınıza bildirmek​

Sonuçlar için ödeme yapan bir kaynağın bunlardan haberdar olması gerekir, her birinin de kendi biçiminde. Bunun için hazır bir scriptle birlikte ayrı bir makale var: Olayları kaynağınıza göndermek.

Kendi veritabanınıza yazmak​

İstatistiklerinizden çıkan bir özet, HTTP aracısı olmadan doğrudan kendi veritabanınıza yazılabilir. Günün depozitolarını ülkelere göre tek bir ekleme sorgusuyla yazan hazır bir script ve Qubix.db komutunun eksiksiz bir anlatımı Kendi veritabanlarınız: Qubix.db makalesinde yer alır.

Telegram'da günlük özet​

Kendi rakamlarınız, istediğiniz gibi gruplanmış, ekibin zaten baktığı yere teslim edilir. Sorgudaki country sütununu olay tablosunun başka bir sütunuyla değiştirin — örneğin offer_id veya pwa_id — ve aynı script farklı bir kesiti raporlar. Sütun doğrudan sorgu metnine yazılır: ${…} ile yerleştirilen değer parametre olarak gider ve sütun adı olamaz. Depozitolar panel raporlarındaki gibi sayılır: bir dep olayı yalnızca geliri depozito eşiğinin üzerindeyse sayılır. campaign_id (izleyici kampanyası) ve sub_id_1 … sub_id_16 sütunları ziyaretlerde doldurulur: depozito bu sütunlar olmadan postback ile gelir, kayıtların çoğu da öyle; bu yüzden bu sütunlara göre bir kesitte depozitolar ve gelir boş, kayıtlar ise eksik kalır.

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

api.telegram.org adresini Qubix ayarları → JavaScript içindeki izin verilen adreslere ekleyin; aksi takdirde istek reddedilir.

Kampanyaları Telegram'dan yönetmek​

Kampanyaları bir mesajla duraklatın ve yeniden başlatın, paneli açmadan son 24 saatin rakamlarını isteyin. Script, botunun yeni mesajlarını dakikada bir okur ve tanıdığı komutları yürütür.

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

İki ayrıntı bunu yalnızca kullanışlı değil, güvenli de kılar. Bir komutun tam olarak bir kez çalışmasını sağlayan şey offset'tir: Telegram, siz onaylayana kadar bir mesajı döndürmeye devam eder ve offset yalnızca çalıştırmanın sonunda kaydedilir; böylece yarıda kesilen bir çalıştırma komutları kaybetmek yerine yeniden okur. İzin verilen gönderenler listesi daha da önemlidir: herkes bir botu bulup ona yazabilir ve bu kontrol olmadan bir yabancı kampanyalarınızı duraklatıyor olurdu.

Yanıtlarda «paused» değil, «requested» yazar: pause() ve activate() yalnızca çalıştırma bittikten sonra yürütülür, yanıt ise çalıştırma sırasında gider — bkz. Duraklatma ve devam ettirme ne zaman devreye girer. Kampanya name ile değil, campaign_name ile aranır — nedeni için bkz. withCondition içindeki koşullar.

Sırada ne var​