Sending messages from a website
SenlerWidget.ask(options) sends a visitor message and returns a Promise for that exact request. It does not run an automation message. Wait for a compatible widget version to become ready before calling it.
Prepare a message
try {
const result = await SenlerWidget.ask({
text: "Help me choose a suitable option.",
newDialog: true,
onStatus({ status }) {
console.log(status);
},
});
for (const answer of result.answers) console.log(answer.text);
if (result.status !== "completed") console.warn(result.status);
SenlerWidget.selectDialog(result.dialogId);
SenlerWidget.open();
} catch (error) {
console.error(error.code, error.message);
}
Without dialogId or newDialog, the question goes to the current chat, creating a dialog if needed. dialogId targets a specific dialog; newDialog: true creates a separate one. These options cannot be combined. Neither switches the visible chat by itself: use selectDialog and open explicitly.
A question can include text, attachments: [{ id: fileId }], replyToEventId, and contextItems. Attachments must already be uploaded and confirmed for the current visitor; the limit is 10. Use text: "" for an attachment-only message. Context alone cannot be sent as an empty message. The draft, attachments, and UI chips, including setPageContext and the selected element, are not automatically included in ask. Pass the required contextItems explicitly; set shared JSON context through setContext.
Fill the composer
To let the visitor review and send prepared text, fill the current chat's composer:
await SenlerWidget.setDraft({ text: "I would like to check the delivery terms." });
SenlerWidget.open();
setDraft changes only the text: it sends no message, creates no dialog, and leaves attachments unchanged. If the widget is closed, the text appears when opened. If the visitor has already entered different text, the call rejects with code: "draft_not_empty". For an intentional replacement, pass replace: true; to clear it, use { text: "", replace: true }. While a message is being sent or an existing message is being edited, the method returns composer_busy, even with replace: true.
Upload a file
Pass a browser File to SenlerWidget.uploadFile(file, options). Set options.dialogId to an existing dialog belonging to the current visitor. The method returns a confirmed attachment but sends no message.
const dialogId = await SenlerWidget.startNewDialog();
const file = document.querySelector("#attachment").files[0];
const attachment = await SenlerWidget.uploadFile(file, {
dialogId,
onProgress(percent) {
console.log(percent);
},
});
const result = await SenlerWidget.ask({
dialogId,
text: "Please review this file.",
attachments: [attachment],
});
onProgress receives a percentage from 0 to 100; 100 means the server has confirmed the upload. signal and timeoutMs are available. The result contains id, url, name, mimeType, size in bytes, and optional durationSeconds. Pass the confirmed file ID to ask, not an arbitrary URL.
Track sending and the response
onStatus receives requestId, the known dialogId, and queued, sending, or waiting. The optional reason explains why the request is waiting. This is request progress, not confirmation of a successful answer.
onAnswer(answer) runs for each completed agent answer. It includes text, eventId, agentId, answersReceived, respondersTotal, and hasMore. The answer also includes text format, attachments, and buttons. The final result contains answers and responders arrays and may include errorCode on failure:
completed: processing finished; an agent can intentionally remain silent, with responder statusno_answer;partial: some agents answered and others did not finish successfully; successful answers remain inanswers;failed,cancelled,superseded: the request did not finish with an ordinary answer or was replaced by a newer one.
Background agents that cannot reply to the user are excluded from the expected answer count. A resolved Promise alone does not mean the required text was returned: check status and answers.
onChunk(chunk) receives text fragments when streaming is enabled for the agent. It does not enable streaming itself. Separate fragments by requestId, agentId, streamId, and iterationId; index starts at zero within an iteration, and text contains only the new fragment. Some fragments may be missing after reconnection. The complete onAnswer replaces the provisional text.
Queue and cancellation
Parallel calls have independent results but do not bypass the agent's message queue. With the queue enabled, questions follow its rules; without it, a newer message can replace a waiting question with status superseded. An instance supports up to 4 executing requests and 64 pending calls.
const controller = new AbortController();
const pending = SenlerWidget.ask({
text: "Prepare a short description.",
signal: controller.signal,
timeoutMs: 60_000,
});
// Your site's cancel button calls controller.abort().
try {
const result = await pending;
console.log(result.status, result.answers);
} catch (error) {
if (error.name !== "AbortError") console.error(error);
}
The default timeoutMs is 120,000 ms, with a maximum of 300,000 ms, including queue time. Cancellation and timeouts stop the SDK from waiting; work already accepted by the server can continue, including tools and charges. Other requests in the instance are unaffected.
Invalid parameters produce TypeError; cancellation produces AbortError; request errors use SenlerWidgetRequestError with code, requestId, and the known dialogId. Sending is unavailable in button_only mode.
Retry after a connection failure
Errors contain retryable and, when the server specifies a delay, retryAfterMs. A temporary failure does not necessarily mean that the server rejected the message: processing may continue after the response connection is lost. For a safe retry, choose requestId in advance and resend the same request with that ID:
const request = {
requestId: crypto.randomUUID(),
text: "Prepare a short description.",
newDialog: true,
};
const send = () => SenlerWidget.ask(request);
const result = await send();
// After a connection failure, the Retry button calls send() with the same request.
The server retains the selected dialog and accepted submission. Within the same channel and lead, repeating requestId resumes waiting or returns saved answers, including requests in the agent's queue. It sends no second message and creates no additional dialog, even with newDialog: true. Multiple waiting calls receive their results independently; cancelling one does not cancel the others.
Keep the text, attachments, ref, context, and processing options unchanged: different content with the same ID returns request_conflict. A new ID means a new question. Without an explicit requestId, the SDK creates a new ID for each call. To restore a request after reload, the website must retain the request and its ID, and the authenticated lead must remain the same. IDs contain up to 128 characters: Latin letters, digits, ., _, :, -; the first character must be a letter or digit.
Reusing a dialog
SenlerWidget.getOrCreateDialog({ ref: "text-edit", showInWidgetHistory: false }) returns { id, ref, showInWidgetHistory }. The same visitor, channel, and ref reuse one dialog, including after a page reload. Configure a published agent keyword route for this value; an unknown or ambiguous route produces an error.
ref selects agents through a published assignment rule, respecting its channel scope. An ordinary keyword requires an exact value such as text-edit, not a phrase containing that word; a start-prefix route uses prefix matching. Default agent assignments are not added to or substituted for the explicit route. If different agents match the same role, the request returns an error instead of choosing arbitrarily.
showInWidgetHistory: false excludes a newly created dialog from the widget's list and search, but not from the cabinet. Resolving it again does not change an existing dialog's visibility. Messages are stored.
With ask({ dialogId, includeHistory: false, includeActions: false, text }), earlier messages are omitted from model input and registered site actions are not offered to the agent. History is not deleted; other agent tools are configured separately. Both flags default to enabled for ordinary ask calls. A request's ref can choose a route for that message without reassigning the current chat.
For field edits, use the text controller. To open an empty discussion without sending, call await SenlerWidget.startNewDialog({ contextItems: [], focusInput: true }), then SenlerWidget.open().