Receitas rápidas da API: copiar, colar, executar
Oito receitas completas para os trabalhos que as agências automatizam primeiro. Cada uma está pronta para copiar, em cURL e em JavaScript (Node 20 ou superior, sem biblioteca). Defina seu token uma vez, como no quick start, e cada bloco roda como está.
export LANACHAT_TOKEN="lc_live_8f2c1d0e9b7a4c6f"
As receitas em JavaScript usam este pequeno helper. Cole-o uma vez no topo do seu arquivo:
const API = 'https://api.lanachat.ai/v1';
async function lanachat(method, path, body) {
const res = await fetch(API + path, {
method,
headers: {
Authorization: `Bearer ${process.env.LANACHAT_TOKEN}`,
'Content-Type': 'application/json',
...(method === 'POST' ? { 'Idempotency-Key': crypto.randomUUID() } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json();
if (!res.ok) throw new Error(`${res.status} ${data.error.code}: ${data.error.message}`);
return data;
}
1. Adicione uma criadora e conecte a conta dela no Telegram #
Requer can_setup e um token de owner para a licença (passo 4). Crie a criadora, preencha a identidade dela, adicione a conta com seu token de bot e depois dê uma licença para a conta poder responder.
# 1. the creator
curl -X POST https://api.lanachat.ai/v1/creators \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
-d '{"name": "Lea", "timezone": "Europe/Paris"}'
# 2. her identity (she must be 18 or older)
curl -X PUT https://api.lanachat.ai/v1/creators/cr_lea/identity \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Content-Type: application/json" \
-d '{"first_name": "Lea", "date_of_birth": "2001-04-12", "nationality": "FR", "languages": ["fr", "en"]}'
# 3. her Telegram account
curl -X POST https://api.lanachat.ai/v1/accounts \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
-d '{"creator_id": "cr_lea", "bot_token": "<bot token>", "market": "fr", "traffic": "instagram"}'
# 4. a licence from your stock
curl -X POST https://api.lanachat.ai/v1/billing/licences/assign \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
-d '{"account_id": "acc_1001"}'
const creator = await lanachat('POST', '/creators', { name: 'Lea', timezone: 'Europe/Paris' });
await lanachat('PUT', `/creators/${creator.id}/identity`, {
first_name: 'Lea', date_of_birth: '2001-04-12', nationality: 'FR', languages: ['fr', 'en'],
});
const account = await lanachat('POST', '/accounts', {
creator_id: creator.id, bot_token: process.env.BOT_TOKEN, market: 'fr', traffic: 'instagram',
});
await lanachat('POST', '/billing/licences/assign', { account_id: account.id });
console.log(account.id, account.health); // "pending" until she confirms in Telegram
A conta fica pending até a criadora confirmar a conexão comercial nas configurações do Telegram. Um webhook avisa quando ela muda para connected: o evento account.health_changed. Veja Telegram accounts e Billing.
2. Leia as vendas de hoje #
Requer can_sales_read. /stats fornece os totais de um dia, por link e por origem; Stars contam $0,013 cada nas vendas líquidas.
TODAY=$(date -u +%F)
curl "https://api.lanachat.ai/v1/stats?from=$TODAY&to=$TODAY" \
-H "Authorization: Bearer $LANACHAT_TOKEN"
const today = new Date().toISOString().slice(0, 10);
const stats = await lanachat('GET', `/stats?from=${today}&to=${today}`);
const stars = stats.days.reduce((sum, d) => sum + d.revenue_stars, 0);
console.log(`${stars} Stars today, about $${(stars * 0.013).toFixed(2)}`);
for (const l of stats.links) console.log(l.link_id, l.buyers, 'buyers', l.revenue_stars, 'Stars');
Adicione creator_id=cr_lea para uma criadora. Os dias são dias UTC. Para receber cada venda no momento em que acontece, use a receita 6.
3. Envie uma mensagem para um fã #
Requer can_chat. Encontre a conversa, depois envie. Uma mensagem enviada pela API conta como enviada por uma pessoa e assume a conversa até que você a devolva (receita 4).
# conversations of Lea with unread messages
curl "https://api.lanachat.ai/v1/conversations?creator_id=cr_lea&unread=true" \
-H "Authorization: Bearer $LANACHAT_TOKEN"
# send a text and a paid photo
curl -X POST https://api.lanachat.ai/v1/conversations/conv_1001_88231/messages \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
-d '{"text": "Only for you, tonight", "media": [{"id": "med_5522", "stars": 250}]}'
const { data: convs } = await lanachat('GET', '/conversations?creator_id=cr_lea&unread=true');
const conv = convs[0];
const msg = await lanachat('POST', `/conversations/${conv.id}/messages`, {
text: 'Only for you, tonight',
media: [{ id: 'med_5522', stars: 250 }],
});
console.log(msg.status); // "queued", then "sent" and "read"
Adicione "send_at" (ISO 8601, até 7 dias à frente) para agendar. Veja Conversations.
4. Assuma uma conversa, depois devolva para a IA #
Requer can_chat. Enquanto uma pessoa segura a conversa, a IA não responde a esse fã.
curl -X POST https://api.lanachat.ai/v1/conversations/conv_1001_88231/takeover \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)"
# ... your team replies ...
curl -X POST https://api.lanachat.ai/v1/conversations/conv_1001_88231/release \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)"
const id = 'conv_1001_88231';
await lanachat('POST', `/conversations/${id}/takeover`); // state: "human"
// ... your team replies ...
await lanachat('POST', `/conversations/${id}/release`); // back to the AI
Uma conversa parada por motivo de segurança não pode ser devolvida para a IA: a API responde 409.
5. Crie um link de rastreamento #
Requer can_tracking. Um link por anúncio ou bio, para saber qual vende.
curl -X POST https://api.lanachat.ai/v1/links \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
-d '{"name": "Insta bio · Lea", "slug": "lea-bio", "creator_id": "cr_lea", "source": "instagram", "destination": "pool"}'
const link = await lanachat('POST', '/links', {
name: 'Insta bio · Lea', slug: 'lea-bio', creator_id: 'cr_lea', source: 'instagram', destination: 'pool',
});
console.log(link.public_url); // put this URL in her bio
Adicione "domain" para usar um dos seus domínios verificados. Leia os cliques, conversas e compradores com GET /links/{id} ou /stats. Veja Tracking.
6. Receba cada venda no seu servidor, assim que acontecer #
Requer um token de owner para adicionar o endpoint. LanaChat envia um POST assinado para cada venda verificada e cada reembolso.
curl -X POST https://api.lanachat.ai/v1/webhooks \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
-d '{"url": "https://hooks.mia-agency.com/lanachat/webhook", "events": ["sale.completed", "sale.refunded"]}'
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';
// once: add the endpoint (keep the secret of the answer as LANACHAT_WEBHOOK_SECRET)
// await lanachat('POST', '/webhooks', { url: 'https://hooks.mia-agency.com/lanachat/webhook', events: ['sale.completed', 'sale.refunded'] });
// the receiver: check the signature, answer 200 fast, then work
function verify(raw, header, secret) {
const parts = (header || '').split(',').map((p) => p.trim().split('='));
const t = parts.find(([k]) => k === 't')?.[1];
if (!t || !(Math.abs(Date.now() / 1000 - Number(t)) < 300)) return false;
const want = createHmac('sha256', secret).update(t + '.').update(raw).digest('hex');
return parts.some(([k, v]) => k === 'v1' && v.length === want.length && timingSafeEqual(Buffer.from(v), Buffer.from(want)));
}
const app = express();
app.post('/lanachat/webhook', express.raw({ type: 'application/json' }), (req, res) => {
if (!verify(req.body, req.get('LanaChat-Signature'), process.env.LANACHAT_WEBHOOK_SECRET)) return res.sendStatus(400);
res.sendStatus(200);
const event = JSON.parse(req.body);
if (event.type === 'sale.completed') console.log('Sale:', event.data.stars, 'Stars,', event.data.creator_id, event.data.sent_by);
if (event.type === 'sale.refunded') console.log('Refund of', event.data.sale_id);
});
app.listen(3000);
O segredo de assinatura vem uma vez, na resposta da primeira chamada: armazene como LANACHAT_WEBHOOK_SECRET. Pressione Test (POST /webhooks/{id}/test) para receber um ping. Python, tentativas e todos os eventos estão em Webhooks.
7. Faça upload de uma foto no Vault e defina o preço #
Requer can_setup. Peça uma URL de upload, envie o arquivo lá, confirme, depois defina o preço.
# 1. upload URL
curl -X POST https://api.lanachat.ai/v1/media/uploads \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
-d '{"creator_id": "cr_lea", "file_name": "beach-01.jpg", "content_type": "image/jpeg", "size_bytes": 2483201}'
# 2. the file, to the "url" of the answer (no Authorization header there)
curl -X PUT "<url from step 1>" -H "Content-Type: image/jpeg" --data-binary @beach-01.jpg
# 3. confirm, 4. price it
curl -X POST https://api.lanachat.ai/v1/media/uploads/up_7781/complete \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)"
curl -X PATCH https://api.lanachat.ai/v1/media/med_5521 \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Content-Type: application/json" \
-d '{"access": "paid", "stars": 300, "description": "Beach, golden hour, white bikini"}'
import { readFile, stat } from 'node:fs/promises';
const file = 'beach-01.jpg';
const up = await lanachat('POST', '/media/uploads', {
creator_id: 'cr_lea', file_name: file, content_type: 'image/jpeg', size_bytes: (await stat(file)).size,
});
const put = await fetch(up.url, { method: up.method, headers: up.headers, body: await readFile(file) });
if (!put.ok) throw new Error('Upload failed: ' + put.status);
const media = await lanachat('POST', `/media/uploads/${up.upload_id}/complete`);
await lanachat('PATCH', `/media/${media.id}`, { access: 'paid', stars: 300, description: 'Beach, golden hour, white bikini' });
O media fica processing, depois ready: o webhook media.ready avisa quando. Veja Vault.
8. Altere um brain, teste, publique #
Requer can_engine e can_publish para o último passo. O brain ao vivo só muda na publicação.
curl -X PATCH https://api.lanachat.ai/v1/brains/br_lea_main/draft \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Content-Type: application/json" \
-d '{"settings": {"first_offer_after_messages": 6}}'
curl -X POST https://api.lanachat.ai/v1/playground/br_lea_main/message \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
-d '{"text": "hey, are you real?", "fan": {"language": "en", "is_new": true}}'
curl -X POST https://api.lanachat.ai/v1/brains/br_lea_main/publish \
-H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)"
await lanachat('PATCH', '/brains/br_lea_main/draft', { settings: { first_offer_after_messages: 6 } });
const test = await lanachat('POST', '/playground/br_lea_main/message', {
text: 'hey, are you real?', fan: { language: 'en', is_new: true },
});
console.log(test.reply.text, '|', test.explain);
// happy with the answer? publish
const live = await lanachat('POST', '/brains/br_lea_main/publish');
console.log('Live version', live.version);
O Playground nunca escreve para um fã e nunca vende. Veja AI Brains.