Example: a DM bot
A complete Node.js server that answers Instagram and Facebook DMs with product cards from a shop's catalog.
This example puts the pages of this section together. It is one file for Node 18 or newer with no dependencies: an HTTP server that receives message.received, searches the shop's catalog, and answers with up to 10 product cards, or with text when nothing matches or the platform has no cards.
Before you run it
Create an editor key
On the API & MCP page of the workspace, create a key with the editor role. Replying to DMs needs nothing more.
Expose your machine
eksis only calls public HTTPS addresses. Start a tunnel such as cloudflared or ngrok to port 3000 and note its address.
Add a webhook endpoint
On the same page, add an endpoint at https://<your tunnel>/eksis/webhooks with the message.received event, and copy the signing secret. You can also create it with Create a webhook endpoint and an admin key.
Set the environment
export EKSIS_API_KEY="eksis_sk_..."
export EKSIS_WEBHOOK_SECRET="whsec_..."
node bot.mjsThe code
// Node 18 or newer. No dependencies.
import { createServer } from 'node:http';
import { createHmac, timingSafeEqual } from 'node:crypto';
const API = 'https://api.eksis.io/v1';
const API_KEY = process.env.EKSIS_API_KEY; // an editor key of the workspace
const WEBHOOK_SECRET = process.env.EKSIS_WEBHOOK_SECRET; // whsec_..., shown once
const CARD_PLATFORMS = new Set(['instagram', 'facebook']);
const TOLERANCE_SECONDS = 5 * 60;
const DAY_MS = 24 * 60 * 60 * 1000;
// YOUR OWN CODE. Search the catalog of the shop that owns this channel.
// Return up to 10 products shaped like { name, price, imageUrl, url },
// all strings, with https links.
async function searchCatalog(text, channelId) {
return [];
}
// The same check as on the Webhooks page.
function verifyEksisWebhook(rawBody, headers, secret) {
const id = headers['webhook-id'];
const timestamp = headers['webhook-timestamp'];
const signatures = headers['webhook-signature'];
if (!id || !timestamp || !signatures) return false;
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) return false;
const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const expected = createHmac('sha256', key).update(`${id}.${timestamp}.${rawBody}`).digest();
return signatures.split(' ').some((entry) => {
const [version, value] = entry.split(',');
if (version !== 'v1' || !value) return false;
const received = Buffer.from(value, 'base64');
return received.length === expected.length && timingSafeEqual(received, expected);
});
}
// Events already handled, by webhook-id. Retries can come for about 23 hours,
// so remember ids for a day. Use your database in production.
const handled = new Map();
function firstTime(id) {
const now = Date.now();
for (const [key, at] of handled) if (now - at > DAY_MS) handled.delete(key);
if (handled.has(id)) return false;
handled.set(id, now);
return true;
}
function buildReply(platform, products) {
if (products.length === 0) {
return { text: 'Thanks for your message. We could not find that product, so someone from the shop will answer you here soon.' };
}
if (CARD_PLATFORMS.has(platform)) {
return {
text: 'Here is what we found:',
cards: products.slice(0, 10).map((product) => ({
title: product.name.slice(0, 80),
subtitle: product.price.slice(0, 80),
imageUrl: product.imageUrl,
url: product.url,
buttons: [{ label: 'View product', url: product.url }],
})),
};
}
// Cards work only on Instagram and Facebook. Elsewhere, send the links as text.
const lines = products.slice(0, 5).map((product) => `${product.name}, ${product.price}: ${product.url}`);
return { text: `Here is what we found:\n${lines.join('\n')}`.slice(0, 1000) };
}
async function sendReply(conversationId, body) {
const res = await fetch(`${API}/conversations/${conversationId}/messages`, {
method: 'POST',
headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (res.ok) return { sent: true };
const { error } = await res.json().catch(() => ({ error: {} }));
return {
sent: false,
status: res.status,
code: error?.code,
message: error?.message,
retryAfter: Number(res.headers.get('retry-after')) || 0,
};
}
async function handleMessage({ conversation, message }) {
const text = message.text?.trim();
if (!text) return; // a photo or a sticker without text: leave it for a person
const products = await searchCatalog(text, conversation.channelId);
const body = buildReply(conversation.platform, products);
for (let attempt = 1; attempt <= 3; attempt++) {
const result = await sendReply(conversation.id, body);
if (result.sent) return;
if (result.code === 'dm.window_closed') {
// The platform no longer accepts replies here. Only a person can follow up.
console.info(`Reply window closed for ${conversation.id}`);
return;
}
if (result.code === 'dm.conversation_too_many_replies') {
// 20 replies in an hour into one conversation usually means a loop. Stop.
console.warn(`Stopped replying to ${conversation.id}: ${result.message}`);
return;
}
const retryable = result.status === 429 || result.status === 503;
const wait = result.retryAfter || 5 * attempt;
if (!retryable || wait > 60 || attempt === 3) {
// dm.too_many_replies can ask for most of an hour. Do not wait that long
// inside a request: put the conversation in your job queue or alert someone.
console.error(`Reply to ${conversation.id} failed: ${result.status} ${result.code} ${result.message}`);
return;
}
await new Promise((resolve) => setTimeout(resolve, wait * 1000));
}
}
createServer(async (req, res) => {
if (req.method !== 'POST' || req.url !== '/eksis/webhooks') {
res.writeHead(404).end();
return;
}
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const rawBody = Buffer.concat(chunks).toString('utf8'); // the exact bytes eksis signed
if (!verifyEksisWebhook(rawBody, req.headers, WEBHOOK_SECRET)) {
res.writeHead(401).end();
return;
}
// Answer within 10 seconds, before the catalog search and the reply.
res.writeHead(204).end();
if (!firstTime(req.headers['webhook-id'])) return;
const event = JSON.parse(rawBody);
if (event.type !== 'message.received') return; // webhook.test and any other event
handleMessage(event.data).catch((err) => console.error('Handling the message failed', err));
}).listen(Number(process.env.PORT ?? 3000));How it works
- The raw body is verified first. The signature covers the exact bytes eksis sent, so the body is read in full and checked before
JSON.parse. A request that fails the check gets401and nothing else happens. The check is the one from Webhooks. - The answer comes before the work. eksis waits 10 seconds for a
2xx. Searching a catalog and calling the reply endpoint can take longer, so the server answers204first and handles the message afterwards. - Repeats are skipped. Delivery is at least once. The same
webhook-idcan come again after a timeout or a retry, andfirstTimedrops it. - The reply fits the platform. Instagram and Facebook get cards. Other platforms get the links as text, because cards there are refused with
dm.cards_unsupported. - Story replies are answered too.
message.kindisstory_replywhen someone answered a story. Check it if your bot should treat those differently. - Errors end in a clear place. A closed reply window and the per-conversation cap stop at once, a short
retry-afteris waited out up to three attempts, and anything longer is logged for your job queue.
Try it
- Choose Send test on the endpoint in the app. The bot answers
204and ignores thewebhook.testevent. - From a second account you own, send a DM to a channel connected to the workspace. With
searchCatalogstill returning nothing, the bot answers with the text fallback. - Make
searchCatalogreturn two products with realhttpsimages and send another DM. On Instagram or Facebook, the reply arrives as a text message followed by a carousel of two cards.
Before you put it in production
- Keep handled ids and pending replies in a database or a queue, not in memory, so a restart or a second server neither drops nor repeats an event. Store the event before answering
204, so a crash between the answer and the reply does not lose it. - Map the channel to the shop.
conversation.channelIdtellssearchCatalogwhose catalog to search, from the table described in Workspaces and limits. - Hand off to people. Mark conversations the bot could not answer, and let the shop's team reply in the eksis inbox or in your product.
- Watch the limits. Each reply counts against the workspace's hourly DM replies and daily requests. See Limits and errors.