Replies and files
Answer a customer's message with a text or a file, repeat a reply without sending it twice, and download the files customers send.
When a customer writes, your server gets a message.received event. Its ids are all you need to answer the customer and to download what they sent.
| To | Use | Scope |
|---|---|---|
| Answer with a text | Reply in a conversation | messages:reply |
| Answer with a file | The same route | messages:reply |
| Read files | List a message's files | messages:read |
This works on WhatsApp, Instagram and Messenger. On Website Chat a reply is refused with UNSUPPORTED_ON_CHANNEL, and no files are listed.
Create the key with both scopes. The person who creates it must stay an admin or owner of the workspace, or its replies are refused.
1. Receive the message
Set up an endpoint for message.received and verify what it gets. These are the parts of the event you need:
{
"id": "evt_01JE2Z3QK4T8M6N2R5S7V9W1X3",
"type": "message.received",
"data": {
"message": {
"id": "5678",
"conversationId": "1234",
"text": "Is this available in blue?",
"sentAt": "2026-11-12T09:25:36.000Z",
"attachments": []
}
}
}- Answer
message.receivedonly. Each reply of yours makes amessage.sentevent, as every message from the workspace does. A program that answers those answers itself. - Others answer too. Someone in the dashboard or a native app, a flow, an AI client or another tool may have replied already. If that matters, read the conversation's messages first.
- An automatic answer is a message too. A customer's own program can answer yours, and so on until a limit stops them. Don't answer every message without a limit of your own.
- On Messenger, not every text is the customer's. If the customer wrote nothing,
textis the title and address of what they shared that Chatwise has no file of, such as a link. Without those it is empty for a message with files,Attachment sent in Messengerfor one with anything else attached, andMessage sent in Messengerfor one with nothing. - An event can be late. After an outage of your endpoint it can come days later, when the customer can't be answered any more. Compare
data.message.sentAtwith the time.
2. Reply
curl -X POST 'https://api.chatwise.so/v1/conversations/1234/messages' \
-H "Authorization: Bearer $CHATWISE_API_KEY" \
-H 'Idempotency-Key: reply-evt_01JE2Z3QK4T8M6N2R5S7V9W1X3' \
-H 'Content-Type: application/json' \
-d '{ "text": "Yes, it is available in blue." }'201 means that the channel accepted the message, not that it was delivered. data.id is the message's id. message.delivered, message.read and message.failed events have the same id, on the channels that report them.
- A text has at most 4,096 characters on WhatsApp, 2,000 on Messenger, and 1,000 bytes of UTF-8 on Instagram. A character takes 1 to 4 bytes there.
- Or send a file instead. A request sends one message: a text or a file.
- Within 24 hours of the customer's latest message. Later, or when the customer hasn't written yet, the answer is a 409 with the code
REPLY_WINDOW_CLOSED. On WhatsApp, send an approved template then, which needsmessages:send. A template has no protection against being sent twice, so note the event first. On Instagram and Messenger, wait until the customer writes again. It is 24 hours through the API also where people can reply for longer on Instagram. - From the conversation's account, when the workspace has several.
- The conversation stays as it was. A reply doesn't mark it read, so the team still sees it as unread and the customer gets no read receipt. It doesn't assign, resolve or reopen it either.
- There are limits: how many replies a key, a workspace and a conversation can send.
3. Repeat it safely
Idempotency-Key is required: 8 to 128 letters, digits, dots, underscores, hyphens or colons. One key stands for one message. Make it from the event's id, as above, and an event that arrives twice is answered once, as long as the API key is the same.
To repeat a request, send the same body with the same Idempotency-Key and the same API key:
| Answer | Was it sent? | What to do |
|---|---|---|
| 201 | Yes. | Nothing. |
| 200 | Yes, by an earlier request. This one sent nothing. | Nothing. data is the first message. |
409 SEND_IN_PROGRESS | It is still being sent, by an earlier request or, for a video on Messenger, by this one. Or an earlier one was interrupted. | Wait as Retry-After says, then repeat. It answers this for at most 5 minutes after it began to be sent. |
409 MEDIA_PROCESSING | Not yet. Its file is still being prepared. | Wait as Retry-After says, then repeat. |
503 MEDIA_BUSY | Not by this request. Its file can't be prepared now. | Wait as Retry-After says, then repeat. |
| 429 | Not by this request. | Wait as Retry-After says, then repeat. |
| No answer, a 500 or another 5xx | Maybe. | Repeat. |
502 SEND_OUTCOME_UNKNOWN | Maybe. | A repeat sends nothing. See below. |
401 Invalid API key | Not by this request. | Repeat: Chatwise couldn't check the key. |
| Any other 4xx | Not by this request. | Fix what the answer names: see errors and, for a file, below. |
- An answer is about its own request. If you repeat a request that got no answer, a 401, 403, 404 or 429 doesn't say whether the first one was sent. While a first request with a file is still running, no error does: it can send the file after a repeat got
MEDIA_PROCESSINGor was refused. So give it a minute and repeat once more, before you go on with another key or a template. - Another text needs another key. Once a key was tried with the channel, another text with it, or another conversation, is refused with
IDEMPOTENCY_KEY_REUSED, also when the channel had refused the message. So if a program writes the text, keep it until the reply is sent. - To send it again after
message.failed, use a new key. The channel had accepted it, so a repeat answers 200. - Another API key doesn't know it. An
Idempotency-Keybelongs to the API key it was used with: with another one, the same request sends another message, also for an event you answered before. So when you change API keys, skip thewebhook-ids you already handled. - It lasts 30 days from the first request that tried to send with it. After that, the same request sends another message.
When it isn't clear
SEND_OUTCOME_UNKNOWN means that the channel didn't answer or had trouble of its own, that Chatwise was interrupted, or that it couldn't save a message the channel had accepted. The message may have been sent, and repeats send nothing.
Read the conversation's messages before you send it again with a new Idempotency-Key:
curl 'https://api.chatwise.so/v1/conversations/1234/messages?direction=outbound&limit=10' \
-H "Authorization: Bearer $CHATWISE_API_KEY"- If it is there, with the same text (or, for a file, the same type and caption) and a
sentAtafter your first request, it was sent, unless someone else sent the same text. Messages don't say who sent them. - If it isn't there, it may still have been sent. Chatwise saves a WhatsApp message only once WhatsApp says that it accepted it. If that answer got lost or couldn't be saved, the message doesn't appear, even when the customer has it. Instagram and Messenger report the messages sent from an account, so there it can appear a little later.
So send it again only if it is better that the customer gets it twice than not at all. Otherwise let a person decide.
4. Read the files
The event says what was attached, in data.message.attachments, but has no files. When it isn't empty, list the message's files:
curl 'https://api.chatwise.so/v1/conversations/1234/messages/5678/files' \
-H "Authorization: Bearer $CHATWISE_API_KEY"{
"data": [
{
"id": "3f1c9a5be07d42a68c1e9b70",
"type": "document",
"status": "available",
"name": "invoice.pdf",
"mimeType": "application/pdf",
"size": 48213,
"url": "https://files.example.com/5f0e7a52-1c1b-4c0e-9a53-6a7d1c2b3e4f.pdf?X-Amz-Expires=300&X-Amz-Signature=0a1b2c",
"urlExpiresAt": "2026-11-12T09:30:36.000Z"
}
]
}- An
availablefile has a link that works for 5 minutes, untilurlExpiresAt, for anyone who has it. Download the file, or list the files again when you need them. Don't store links. - The link needs no API key, so don't send yours with it. The file comes as a download. Types a browser could run, such as HTML and SVG, come as
application/octet-stream, whatevermimeTypesays. pendingmeans that Chatwise is still copying the file, which happens for a moment on Instagram and Messenger. List the files again a few seconds later. If Facebook has trouble, copying can take minutes. On Messenger thetypecan change when a file is copied: a shared post is animageuntil then, and what was sent as a document is adocument. A file of imported Instagram history can staypendingfor long, so don't wait for it.unavailablemeans that it couldn't be copied, or is gone. A new file that isn't copied 15 minutes after Chatwise stored the message is listed as this too, until it is.- A story isn't listed until it is copied. For a reply to a story, or a mention in one, the list is empty for a moment instead of
pending. Ifattachmentshas a type withstoryin it and the list is empty, list the files again a few seconds later, but only a few times: a story that can't be copied is never listed. nameis what the sender called it, and can benull. On Messenger only what was sent as a document has one. If the customer sent it, it has none until it is copied. Don't use it as a path. Theidis safe, and stays the same, with one exception.- The list is empty for a message without files. It is also empty on Website Chat, for Messenger messages from before Chatwise kept their files, in December 2026, for the media in a WhatsApp template's header, for WhatsApp authentication templates, for a post, reel or story shared on Instagram that Chatwise didn't copy, and for a post or reel on Messenger of which Facebook gave only the page's address. A message can have attachments and no files, or two attachments for one file, so don't match or count them.
- A deleted or hidden message answers 404. A link you already have works until it expires.
At most 20 files are listed, in the order they were sent. On WhatsApp and Instagram those Chatwise has copied come first.
5. Send a file
Send media instead of text, with the address your file can be downloaded from:
curl -X POST 'https://api.chatwise.so/v1/conversations/1234/messages' \
-H "Authorization: Bearer $CHATWISE_API_KEY" \
-H 'Idempotency-Key: invoice-1042' \
-H 'Content-Type: application/json' \
-d '{
"media": {
"url": "https://example.com/files/invoice-1042.pdf",
"fileName": "Invoice 1042.pdf",
"caption": "Here is your invoice."
}
}'Chatwise downloads the file, prepares it for the channel and sends it. The 24 hours, the answers and the Idempotency-Key are as above. In the answer, data.type is image, video or audio. For a document it is document on WhatsApp, and file on Instagram and Messenger.
- The address must be public, start with
https://, use port 443 and answer 200 with the file. A redirect, or any other status, is refused withMEDIA_DOWNLOAD_FAILED. The file can have up to 100 MB. Its download can take 2 minutes, without a pause of 20 seconds, also before it begins. - What the address answers is what is sent. A sign-in or error page with the status 200 is taken for the file. Usually it is refused with
MEDIA_REJECTED, but if its server calls ittext/plain, or its name ends in.txt, the customer gets it. - The address is part of the request. If it is signed, sign it once and repeat the request with the same one: a newly signed address is another file, and is refused with
IDEMPOTENCY_KEY_REUSED. So is anotherfileNameor conversation. fileNameis the name a document has on WhatsApp. Give it with its ending, and without slashes: only what follows the last one is used, and<>:"|?*become spaces. WithoutfileName, the document has the name its server gives, or the last part of the address.- On Messenger a document's name is changed. The customer sees one like
Invoice-1042-19b0162e0a7f.pdfforInvoice 1042.pdf. It has up to 80 characters of the name, then 12 of Chatwise's own. Accents are dropped, and anything but the letters A to Z and digits becomes a hyphen or is left out. A name with none of them, such as one in Hindi or Chinese, becomesdocument. The message's files have the name you gave. captionis a text shown with an image, a video or a document on WhatsApp, of at most 1,024 characters. Instagram and Messenger have none, and neither has WhatsApp audio: there a caption is refused with a 400 once the file is prepared, and nothing is sent. Send the text as a message of its own, with a key of its own.- Use a key once. A file that was sent isn't downloaded again: after the 30 days, the same request sends the copy Chatwise has, and another file with the key is still refused. A file that was never tried with the channel is forgotten after 7 days, or a day if it couldn't be prepared.
What can be sent
Chatwise looks at the file itself to see what it is. Most files are converted to what the channel takes, and made smaller if they are too large for it.
| What | From | Sent as | Up to |
|---|---|---|---|
| Images | JPEG, PNG, WebP, GIF, TIFF, AVIF | Sent as JPEG or PNG | 5 MB on WhatsApp, 8 MB on Instagram and Messenger |
| Videos | MP4, MOV, 3GP, WebM, MKV, AVI, OGG | Sent as MP4 | 16 MB on WhatsApp, 25 MB on Instagram and Messenger |
| Audio | MP3, M4A, AAC, AMR, OGG, WAV, FLAC | Sent as M4A. AAC stays, and so do MP3 on WhatsApp and Messenger and 16-bit WAV on Instagram | 16 MB on WhatsApp, 25 MB on Instagram and Messenger |
| Documents | PDF, and on WhatsApp and Messenger also Word, Excel, PowerPoint and plain text | Sent as they are | 100 MB on WhatsApp, 25 MB on Instagram and Messenger |
- Images can have 50 megapixels as JPEG (24 if it is progressive), 40 as PNG, 5 as AVIF and 16 otherwise. They are sent with at most 4,096 pixels on the longer side, 2,560 if they have more than 16 megapixels, and 2,048 for a GIF or a transparent WebP, TIFF or AVIF. An animation is sent as a still, except an AVIF, which is refused. HEIC isn't taken.
- Videos can have pictures of up to 4096 × 2304. One that has to be converted gets at most 1,280 pixels on the longer side, and converting it can take 4 minutes. If that isn't enough, it is refused with
MEDIA_REJECTED. One with H.264 (Main or Baseline profile, without B-frames) and AAC that fits is copied as it is. Export long videos like that. - Audio can be about an hour long.
- Plain text is UTF-8, and is told by its name: one that ends in
.txt, or a server that calls ittext/plain. So a CSV file is sent only if one of these is true, and as a text file. - Word, Excel and PowerPoint files from before 2007 look the same inside. Their name, or the type their server gives, has to say which they are.
When it takes longer
A request waits up to 25 seconds for its file. After that it answers:
HTTP/1.1 409 Conflict
Retry-After: 10
{"code":"MEDIA_PROCESSING","message":"The file is still being prepared, and the message hasn't been sent. Repeat the request in a moment with the same Idempotency-Key"}Chatwise goes on preparing the file, but a request that got this answer sends nothing. Wait as Retry-After says, then make the same request, with the same key and body, until the answer is another one. A prepared file is kept for 7 days. It is still sent only within 24 hours of the customer's latest message.
A request that got no answer is another matter. If your program stopped waiting for it, or its connection broke, Chatwise still waits for the rest of the 25 seconds, and sends the file if it is ready by then. Until then, a repeat can get MEDIA_PROCESSING. If it isn't ready, nothing is sent until you repeat the request. So repeat it, don't send the file with another key, and give a request a minute before you stop waiting for it.
The sample does that for about ten minutes:
import { reply } from "./answer.mjs";
const media = {
url: "https://example.com/files/invoice-1042.pdf",
fileName: "Invoice 1042.pdf",
caption: "Here is your invoice.",
};
const { id, type } = await reply("1234", { media }, "invoice-1042");
console.log(`${type} ${id}`);When Messenger takes long
Facebook fetches a video itself, which can take over a minute. A request on Messenger waits 30 seconds for that, besides the 25 for its file. After that it answers:
HTTP/1.1 409 Conflict
Retry-After: 10
{"code":"SEND_IN_PROGRESS","message":"This message is still being sent. Repeat the request in a moment with the same Idempotency-Key"}Unlike after MEDIA_PROCESSING, Chatwise goes on sending it. Wait as Retry-After says, then make the same request, with the same key and body, until the answer is another one: 200 if it was sent, a refusal of Facebook's such as MEDIA_REJECTED, or SEND_OUTCOME_UNKNOWN if it isn't clear, for example because Facebook didn't answer. The sample does this too, for ten minutes together with preparing the file. If it throws SEND_IN_PROGRESS then, the video can still be on its way.
A refusal is answered for a minute. Repeats in the minute after Facebook refused the video get that answer and send nothing. A later one sends the video again, and can get SEND_IN_PROGRESS again. So don't wait longer than that between repeats, or you never learn of it. This is so for every refusal of a video on Messenger, also one that comes within the 30 seconds.
When it can't be sent
A request that gets one of these sent nothing itself. message says more.
| Answer | What happened | What to do |
|---|---|---|
422 MEDIA_DOWNLOAD_FAILED | The file couldn't be downloaded from its address, or has more than 100 MB. | Repeat the request after a minute, and it is downloaded again. Until then the answer stays the same. For another address, use a new key. |
422 MEDIA_REJECTED | The file isn't one the channel takes, is too large, can't be read, or takes too long to convert. | Send another file, with a new key, and stop repeating this one. |
503 MEDIA_BUSY | Too many files are being prepared, for the workspace or at all, or something failed in Chatwise or at the channel. | Wait as Retry-After says, then repeat. |
429 RATE_LIMITED | Too many files, or too many replies. | Wait as Retry-After says, then repeat. |
- A file Chatwise refuses stays refused. It isn't looked at again with the same key for at least a day, also when you replace it at its address. Two can be repeated: one that took too long to convert, after a minute, and one that the channel itself refused, at once, or for a video on Messenger after a minute.
All of it
Save this next to the server and have the server call this handle instead of its own.
It repeats a request while that is safe, and throws when it can't finish. The server has answered the webhook by then, so Chatwise won't send the event again: keep the event, and run handle with it again later. A reply that was already sent isn't sent again. Running it again doesn't help after SEND_OUTCOME_UNKNOWN or a refusal, which come again: do what the answer needs, and call files yourself. Files that are still pending after about ten seconds are skipped, so list them again later if you need them.
import { setTimeout as wait } from "node:timers/promises";
const API = "https://api.chatwise.so/v1";
const DAY = 24 * 60 * 60 * 1000;
// How long to wait for a message that is being prepared or sent.
const PATIENCE = 10 * 60 * 1000;
// Makes a request, and repeats it while that is safe. A reply keeps its Idempotency-Key.
async function call(path, options = {}) {
const until = Date.now() + PATIENCE;
for (let attempt = 1; ; attempt++) {
let response, body;
try {
response = await fetch(API + path, {
...options,
headers: { ...options.headers, Authorization: `Bearer ${process.env.CHATWISE_API_KEY}` },
signal: AbortSignal.timeout(60_000),
});
body = await response.json();
} catch (error) {
// No answer. A reply may have been sent, or still be.
if (attempt === 5) throw error;
await wait(attempt * 1000);
continue;
}
if (response.ok) return body.data;
const { status } = response;
const waiting = ["MEDIA_PROCESSING", "MEDIA_BUSY", "SEND_IN_PROGRESS"].includes(body.code) && Date.now() < until;
const repeat = waiting || status === 429
|| (status === 401 && body.message === "Invalid API key")
|| (status >= 500 && body.code !== "SEND_OUTCOME_UNKNOWN");
const seconds = Number(response.headers.get("retry-after") ?? attempt);
// Don't wait for long here. Run it again later, with the same key and content.
if (!repeat || (attempt === 5 && !waiting) || seconds > 60) {
throw Object.assign(new Error(`${status}: ${body.message}`), { code: body.code, retryAfter: seconds });
}
await wait(seconds * 1000);
// That isn't a failed attempt.
if (waiting) attempt = 0;
}
}
// The content is { text }, or { media } for a file.
export function reply(conversationId, content, idempotencyKey) {
return call(`/conversations/${conversationId}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
body: JSON.stringify(content),
});
}
// A message's files. Waits a little for those Chatwise is still copying.
export async function files({ id, conversationId, attachments }) {
const story = attachments.some(({ type }) => type.includes("story"));
for (let attempt = 1; ; attempt++) {
const found = await call(`/conversations/${conversationId}/messages/${id}/files`);
const copying = found.some(({ status }) => status === "pending") || (story && found.length === 0);
if (!copying || attempt === 5) return found;
await wait(attempt * 1000);
}
}
// The link needs no API key.
export async function download({ url }) {
const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
if (!response.ok) throw new Error(`${response.status} for a file`);
return Buffer.from(await response.arrayBuffer());
}
export async function handle(event) {
// Not message.sent: your own replies make those.
if (event.type !== "message.received") return;
const { message } = event.data;
// Too late to answer.
if (Date.now() - Date.parse(message.sentAt) > DAY) return;
// Before the files, so that one that can't be read doesn't stop it.
await reply(message.conversationId, { text: "Thanks, we have your message." }, `reply-${event.id}`);
if (message.attachments.length > 0) {
for (const file of await files(message)) {
if (file.status === "available") console.log(`${file.type}: ${(await download(file)).length} bytes`);
}
}
}