LunaDocs

Loading search...

PortuguêsSign in to the console
On this page

AI agent: the complete loop

Use with AI

An AI agent that answers on WhatsApp always does the same loop: it receives an event, checks that it came from Luna, answers fast, thinks and sends the reply. This guide brings the whole loop in code that runs when pasted, in Python (only the standard library) and in Node (only fetch), and explains each step. The intelligence is yours: the code calls an answer function, which you swap for your model.

Each route’s contract, field by field, is in the API reference. The small-print terms (24-hour window, template, idempotency) are in the glossary.

The loop, in eight steps#

  1. Receive Luna’s POST at your address and verify the signature of the bytes that arrived. Invalid signature: 401 and stop. See Receive events.
  2. Answer 200 right away. Luna waits 10 seconds, and a call to an AI model easily goes past that.
  3. Drop the repeat: delivery is at least once, and the same event_id can arrive twice.
  4. Put the event on a queue and handle it outside the request, one at a time, to keep the conversation’s order.
  5. Mark as read (POST /v1/messages/{id}/read) and show “typing” (POST /v1/messages/{id}/typing).
  6. Think: call your model with the received text.
  7. Reply with POST /v1/messages, with an Idempotency-Key that comes from the received message: resp-<id>.
  8. If the 24-hour window is closed (409 window_closed), fall back to an approved template.

Before you run it#

  • A connected number and a registered webhook endpoint, as in Quickstart. The secret the registration returns is the LUNA_WEBHOOK_SECRET.
  • An API key with the agent profile (profile: "agent" in POST /v1/api-keys, or the “Agente de atendimento” (service agent) profile in the console). It grants messages:write, messages:read, numbers:read and templates:read: what the loop uses, and no configuration.
  • A public HTTPS address for the server. In development, an HTTPS tunnel to your machine works (see Receive events).
VariableWhat it is
LUNA_API_KEYThe API key (hlsn_...).
LUNA_WEBHOOK_SECRETThe endpoint’s secret (whsec_...).
LUNA_NUMBER_IDThe origin number: the metaPhoneNumberId or the id from GET /v1/numbers.
LUNA_TEMPLATEOptional. The name of an approved template, for step 8.
LUNA_API_URLOptional. Only to point at another base, such as a local stack.
PORTOptional. The server’s port (3000 by default).

The code#

Save as agente.py or agente.mjs. It is a single file, with no pip install or npm install. answer is the function you swap for your model; here it returns a fixed text.

import crypto from 'node:crypto';
import http from 'node:http';

const API = process.env.LUNA_API_URL ?? 'https://api.lunahia.com.br'; // LUNA_API_URL is optional: it exists to point at a local stack
const KEY = process.env.LUNA_API_KEY;
const SECRET = process.env.LUNA_WEBHOOK_SECRET;
const NUMBER = process.env.LUNA_NUMBER_ID;
const TEMPLATE = process.env.LUNA_TEMPLATE; // optional: the name of an approved template, for when the window is closed

const TOLERANCE_SECONDS = 300;

// rawBody: the exact bytes received (a Buffer), never re-serialized JSON.
export function verifyLunaSignature(rawBody, header, secret, nowMs = Date.now()) {
  if (typeof header !== 'string' || !secret) return false;

  // 1. The header carries the instant t and the signature v1.
  const m = /^t=(\d{1,15}),/.exec(header);
  if (!m) return false;
  const t = Number(m[1]);

  // 2. Refuse what is too old (a recorded delivery replayed later).
  if (Math.abs(Math.floor(nowMs / 1000) - t) > TOLERANCE_SECONDS) return false;

  // 3. Redo the calculation with your secret and compare it with v1.
  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${t}.`)
    .update(rawBody)
    .digest();

  // During a secret rotation the header carries two v1 values: check them all.
  let ok = false;
  for (const [, hex] of header.matchAll(/v1=([0-9a-fA-F]{64})/g)) {
    if (crypto.timingSafeEqual(Buffer.from(hex, 'hex'), expected)) ok = true;
  }
  return ok;
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Calls the API. Returns the status and the JSON body.
async function luna(method, path, body, idempotencyKey, tries = 3) {
  const headers = { Authorization: 'Bearer ' + KEY };
  if (body !== undefined) headers['Content-Type'] = 'application/json';
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;

  for (let attempt = 1; ; attempt++) {
    const res = await fetch(API + path, {
      method,
      headers,
      body: body === undefined ? undefined : JSON.stringify(body),
      signal: AbortSignal.timeout(15000),
    });
    if ((res.status === 429 || res.status === 503) && attempt < tries) {
      // On 429/503 wait what the API says and try again, with the SAME Idempotency-Key
      await sleep(Number(res.headers.get('retry-after') ?? 2 ** attempt) * 1000);
      continue;
    }
    const text = await res.text();
    return { status: res.status, body: text ? JSON.parse(text) : null };
  }
}

// Replace this function with your agent (the LLM call goes here).
function answer(text) {
  return text ? 'Recebi: ' + text + '. Já te ajudo.' : 'Recebi a sua mensagem.';
}

async function handle(event) {
  if (event.event_type !== 'message.received') return;
  const msg = event.message;
  const destination = msg.wa_id ? { to: msg.wa_id } : { recipient: msg.user_id }; // wa_id is null when the contact wrote without a phone number: then answer to the user_id

  await luna('POST', '/v1/messages/' + msg.id + '/read'); // mark as read (the double blue check)
  await luna('POST', '/v1/messages/' + msg.id + '/typing'); // show "typing..." (it also marks the message as read, and goes away when you reply)

  const reply = answer(msg.text); // only text is handled here
  let sent = await luna(
    'POST',
    '/v1/messages',
    { from: NUMBER, ...destination, text: { body: reply } },
    'resp-' + msg.id, // the key comes from the received message: the same event twice never produces two replies
  );
  console.log('reply', sent.status, sent.body);

  if (sent.status === 409 && sent.body?.error === 'window_closed' && TEMPLATE) {
    // the 24-hour window is closed: only a template goes out
    sent = await luna(
      'POST',
      '/v1/messages',
      {
        from: NUMBER,
        ...destination,
        type: 'template',
        template: { name: TEMPLATE, language: { code: 'pt_BR' } },
      },
      'resp-' + msg.id + '-template',
    );
    console.log('template', sent.status, sent.body);
  }
}

const seen = new Set(); // in production: a database or Redis, with an expiry
let queue = Promise.resolve(); // ONE worker keeps the order of the events. For many conversations at once, one worker per wa_id.

http
  .createServer((req, res) => {
    const chunks = [];
    req.on('data', (chunk) => chunks.push(chunk));
    req.on('end', () => {
      const raw = Buffer.concat(chunks);
      if (!verifyLunaSignature(raw, req.headers['x-luna-signature'], SECRET)) {
        res.writeHead(401).end();
        return;
      }
      res.writeHead(200).end(); // answer 200 first, work after
      const event = JSON.parse(raw.toString('utf8'));
      if (seen.has(event.event_id)) return;
      seen.add(event.event_id);
      // the work goes to a queue: the request only verifies and answers
      queue = queue.then(() => handle(event)).catch((err) => console.error('handler failed', err)); // a failure in one event must not stop the worker
    });
  })
  .listen(Number(process.env.PORT ?? 3000));
import hashlib
import hmac
import json
import os
import queue
import re
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

API = os.environ.get("LUNA_API_URL", "https://api.lunahia.com.br")  # LUNA_API_URL is optional: it exists to point at a local stack
KEY = os.environ["LUNA_API_KEY"]
SECRET = os.environ["LUNA_WEBHOOK_SECRET"]
NUMBER = os.environ["LUNA_NUMBER_ID"]
TEMPLATE = os.environ.get("LUNA_TEMPLATE")  # optional: the name of an approved template, for when the window is closed

TOLERANCE_SECONDS = 300


def verify_luna_signature(raw_body, header, secret, now=None):
    # raw_body: the exact bytes received, never re-serialized JSON.
    if not header or not secret:
        return False

    # 1. The header carries the instant t and the signature v1.
    m = re.match(r"^t=(\d{1,15}),", header)
    if not m:
        return False
    t = int(m.group(1))

    # 2. Refuse what is too old (a recorded delivery replayed later).
    now = time.time() if now is None else now
    if abs(int(now) - t) > TOLERANCE_SECONDS:
        return False

    # 3. Redo the calculation with your secret and compare it with v1.
    expected = hmac.new(
        secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256
    ).hexdigest()

    # During a secret rotation the header carries two v1 values: check them all.
    ok = False
    for sig in re.findall(r"v1=([0-9a-fA-F]{64})", header):
        if hmac.compare_digest(sig.lower(), expected):
            ok = True
    return ok


def luna(method, path, body=None, idempotency_key=None, tries=3):
    # Calls the API. Returns the status and the JSON body.
    headers = {"Authorization": f"Bearer {KEY}"}
    data = None
    if body is not None:
        data = json.dumps(body).encode()
        headers["Content-Type"] = "application/json"
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    for attempt in range(1, tries + 1):
        req = urllib.request.Request(API + path, data=data, headers=headers, method=method)
        try:
            with urllib.request.urlopen(req, timeout=15) as res:
                raw = res.read()
                return res.status, (json.loads(raw) if raw else None)
        except urllib.error.HTTPError as err:
            raw = err.read()
            payload = json.loads(raw) if raw else None
            if err.code in (429, 503) and attempt < tries:
                # On 429/503 wait what the API says and try again, with the SAME Idempotency-Key
                time.sleep(float(err.headers.get("Retry-After") or 2**attempt))
                continue
            return err.code, payload


def answer(text):
    # Replace this function with your agent (the LLM call goes here).
    return f"Recebi: {text}. Já te ajudo." if text else "Recebi a sua mensagem."


def handle(event):
    if event["event_type"] != "message.received":
        return
    msg = event["message"]
    destination = {"to": msg["wa_id"]} if msg["wa_id"] else {"recipient": msg["user_id"]}  # wa_id is null when the contact wrote without a phone number: then answer to the user_id

    luna("POST", f"/v1/messages/{msg['id']}/read")  # mark as read (the double blue check)
    luna("POST", f"/v1/messages/{msg['id']}/typing")  # show "typing..." (it also marks the message as read, and goes away when you reply)

    reply = answer(msg.get("text"))  # only text is handled here
    status, body = luna(
        "POST",
        "/v1/messages",
        {"from": NUMBER, **destination, "text": {"body": reply}},
        idempotency_key=f"resp-{msg['id']}",  # the key comes from the received message: the same event twice never produces two replies
    )
    print("reply", status, body)

    if status == 409 and body and body.get("error") == "window_closed" and TEMPLATE:
        # the 24-hour window is closed: only a template goes out
        status, body = luna(
            "POST",
            "/v1/messages",
            {
                "from": NUMBER,
                **destination,
                "type": "template",
                "template": {"name": TEMPLATE, "language": {"code": "pt_BR"}},
            },
            idempotency_key=f"resp-{msg['id']}-template",
        )
        print("template", status, body)


events = queue.Queue()  # the work goes to a queue: the request only verifies and answers
seen = set()  # in production: a database or Redis, with an expiry
seen_lock = threading.Lock()


def worker():
    # ONE worker keeps the order of the events. For many conversations at once, one worker per wa_id.
    while True:
        event = events.get()
        try:
            handle(event)
        except Exception as err:  # a failure in one event must not stop the worker
            print("handler failed", repr(err))


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        if not verify_luna_signature(raw, self.headers.get("X-Luna-Signature"), SECRET):
            self.send_response(401)
            self.send_header("Content-Length", "0")
            self.end_headers()
            return
        self.send_response(200)  # answer 200 first, work after
        self.send_header("Content-Length", "0")
        self.end_headers()
        event = json.loads(raw)
        with seen_lock:
            repeated = event["event_id"] in seen
            seen.add(event["event_id"])
        if not repeated:
            events.put(event)

    def log_message(self, *args):
        pass


threading.Thread(target=worker, daemon=True).start()
ThreadingHTTPServer(("", int(os.environ.get("PORT", "3000"))), Handler).serve_forever()
JavaScript
export LUNA_API_KEY="hlsn_..."
export LUNA_WEBHOOK_SECRET="whsec_..."
export LUNA_NUMBER_ID="123456789012345"

python3 agente.py     # ou: node agente.mjs

Write from your phone to the connected number: the agent prints reply 202 and the reply reaches your phone. If nothing arrives, follow “If nothing arrived” in Quickstart.

Why each step is the way it is#

Answer `200` first

Luna counts as delivered only a 2xx answer within 10 seconds. If the server called the model before answering, a slow reply would turn into a failure and Luna would resend the event, and the agent would reply twice. That is why the request only verifies, answers and puts the event on the queue; the worker does the thinking. The delivery guarantees are in Receive events.

Drop the repeated `event_id`

The event_id is stable: the same delivery, repeated, carries the same value. The example’s in-memory set disappears when the process restarts; in production keep the processed ones in a database or Redis, with an expiry. Note: the replay you ask for with POST /v1/messages/{id}/replay also carries the same event_id as the original, so it falls into this drop. To recover a message the agent lost, take its event_id out of the seen list before asking for the replay.

One worker keeps the order

Luna delivers a conversation’s events in order. If several workers took events of the same conversation, the reply to the second message could go out before the reply to the first. The example uses a single worker, which is enough for a few conversations at once; for many, keep one worker (or one queue) per wa_id, and several conversations move in parallel without getting mixed up.

Read and “typing”

Both routes take the received message’s id at Luna (the event’s message.id), not the wamid. Calling /typing also marks the message as read; the example calls both to make the step explicit. The indicator goes away on its own when you reply. There is a shortcut: typingMs in POST /v1/messages turns the indicator on and waits that long before sending, with no separate call. Both are in Send messages.

The agent’s idempotency key#

For an agent, the key is not a new UUID on each attempt: it is a deterministic key, which comes from the message it is answering, such as resp-<id>. The reason: webhook delivery is at least once, and your handling can run twice for the same event (a restart in the middle, a replay, a retry after a 429). With the same key, both attempts become one reply: the second returns the original message, with the same id, and nothing is sent again. A new UUID on each attempt protects from nothing.

  • One reply per received message: resp-<id>. A second reply to the same message (the template fallback, for example) takes another suffix: resp-<id>-template. The same key with a different body answers 409 idempotency_key_reused.
  • The key is 1 to 255 visible characters, no space. The full format is in Send messages.

When the window has closed#

Right after the contact writes, the 24-hour window is open, and the reply goes out. 409 window_closed shows up when the agent answers an old event (a delayed queue, a replay from yesterday) or when it is the one starting the conversation. It carries fechadaEm (when the window closed, or null if there never was one) and acaoRecomendada. Free-form messages are not accepted again with time: only when the contact writes again. What goes out is an approved template, which the code above sends if LUNA_TEMPLATE is set. How to create one and wait for approval, and how to test before having one, is in Templates.

Received media#

When the customer sends an image, audio, document or video, the event carries message.media (with the mime_type and the url) and message.type. The url is a Luna link that downloads the file without an API key: make a GET on it and follow the redirect. If Luna is still downloading the file from Meta, the answer is 409 media_not_ready with Retry-After: wait and try again. Treat the link as sensitive data and do not log it. GET /v1/messages/{id}/media (messages:read scope), with a key, remains valid. Details in Send messages.

import { writeFile } from 'node:fs/promises';

const EXTENSIONS = { 'image/jpeg': '.jpg', 'image/png': '.png', 'audio/ogg': '.ogg', 'application/pdf': '.pdf' };

// Downloads the file from the media.url of a message.received notice.
async function downloadFromLink(link, name, attempts = 6) {
  for (let i = 0; i < attempts; i++) {
    const res = await fetch(link); // no Authorization header: the token inside the link is the credential. Never log the link.
    if (res.status === 409) {
      // 409 media_not_ready: Luna is still downloading from Meta, wait what Retry-After says and try again
      const seconds = Math.min(Number(res.headers.get('retry-after') ?? 5), 30);
      await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
      continue;
    }
    if (res.status === 404) return null; // 404: the link expired (30 days) or never existed. GET /v1/messages/{id}/media still works, with a key.
    if (!res.ok) throw new Error('media link answered ' + res.status);
    const type = (res.headers.get('content-type') ?? '').split(';')[0];
    const file = name + (EXTENSIONS[type] ?? '');
    await writeFile(file, Buffer.from(await res.arrayBuffer()));
    return file;
  }
  return null;
}

console.log(await downloadFromLink(process.env.LUNA_MEDIA_URL, 'arquivo'));
import os
import time
import urllib.error
import urllib.request

EXTENSIONS = {"image/jpeg": ".jpg", "image/png": ".png", "audio/ogg": ".ogg", "application/pdf": ".pdf"}


def download_from_link(link, name, attempts=6):
    # Downloads the file from the media.url of a message.received notice.
    for _ in range(attempts):
        try:
            # no Authorization header: the token inside the link is the credential. Never log the link.
            with urllib.request.urlopen(link, timeout=60) as file:
                data = file.read()
                extension = EXTENSIONS.get(file.headers.get_content_type(), "")
        except urllib.error.HTTPError as err:
            if err.code == 409:
                # 409 media_not_ready: Luna is still downloading from Meta, wait what Retry-After says and try again
                time.sleep(min(int(err.headers.get("Retry-After", "5")), 30))
                continue
            if err.code == 404:
                return None  # 404: the link expired (30 days) or never existed. GET /v1/messages/{id}/media still works, with a key.
            raise
        with open(name + extension, "wb") as out:
            out.write(data)
        return name + extension
    return None


print(download_from_link(os.environ["LUNA_MEDIA_URL"], "arquivo"))

Before going to production#

  • After the 200, a failure is yours. If your handling fails, Luna does not retry: it already got the 200. In production, write the event to a database before answering (a quick INSERT) and handle from there, so a restart does not lose the message.
  • The pace. Replies in bursts need no waiting on your side: Luna queues them. See Limits and pacing.
  • Test without a real number. The test key simulates sending and the states, without touching Meta: Test mode.
  • The errors the loop can see and what to do about each: Errors.
  • n8n instead of code? The path with the standard nodes is in SDK and n8n.