Skip to content
On this page

DeepdeskSDK Class

constructor

Create an instance of the DeepdeskSDK for each conversation.

ts
new DeepdeskSDK(config: SDKConfig);
ts
interface SDKConfig {
  /**
   * Base API URL for the Deepdesk backend,
   * e.g. https://acme.deepdesk.com
   */
  deepdeskUrl: string;

  /**
   * Optional base url for the Deepdesk broker backend
   * Only applicable if using autoflows or custom messages features.
   * e.g. https://acme.deepdesk.com/broker/api
   */
  brokerUrl?: string;

  /**
   * Set the language for all the UI labels.
   * Note: This has no effect on the language of the suggestions!
   * Default: en-US
   */
  locale?: "en-US" | "nl-NL";

  /**
   * Optional jwt token for Authorization: Bearer <...> header.
   * This is an alternative to the preferred SSO implementation.
   * Contact support@deepdesk.com for how to obtain a token.
   */
  token?: string;
}

conversationId

Get conversation id of current conversation. Throws an error if there is no conversation loaded yet.

ts
deepdeskSDK.conversationId(): number;

hasConversation

Check if a conversation is loaded.

ts
deepdeskSDK.hasConversation(): boolean;

isConversationSupported

Check if a conversation is supported by Deepdesk. The call does not require the user to be logged in.

ts
deepdeskSDK.isConversationSupported(sessionId: string, options: RetryOptions): Promise<boolean>;
ts
interface RetryOptions {
  /**
   * Number of attempts in the case the conversation is not created yet via the Deepdesk webhook.
   */
  attempts?: number;

  /**
   * Delay between attempts in miliseconds
   * Default: 1000(ms)
   */
  retryDelay?: number;
}

login

By default the DeepdeskSDK assumes that there is a valid access_token_cookie so it doesn't deal with authentication.

Since v7.1.0 handling authentication is opt-in by using the login() method.

  • First it tries to verify if there is a valid access_token_cookie.
  • If not, it tries to refresh the cookie, hoping for a refresh token.
  • If that also fails it will render a login button. And poll untill the user is authenticated.

Note 1: If you are using the login() method. Make sure to use mount() and/or renderWidget() before waiting on login-Promise to be resolved. Otherwise the login button can't be rendered!

Note 2: The login-Promise only resolves after successful authentication and never throws.

Note 3: The polling for authentication is silently killed when an instance is unmounted.

ts
deepdeskSDK.login(): Promise<void>;

isLoggedIn

Check if user is logged in.

ts
deepdeskSDK.isLoggedIn(): Promise<boolean>;

loginViaPopup

Since version v10.7.0.

Login a user via SSO flow in a window popup.

If a user is already logged in, the popup will briefly show and close automaticly.

If a user is not logged in, the popup will load the login screen of the identity profider.

ts
deepdeskSDK.loginViaPopup(): Promise<void>;

The promise resolves when the user is logged in successfully.

There are different cases where the promise is rejected:

  • When the popup is blocked by the browser: new Error('Popup blocked by browser). This often happens when the loginViaPopup is called outside a user triggered event handler.

  • When the popup is closed by the user before the user is logged in: new Error('Popup closed by user')

  • When the account's platform url is misconfigured, the popup will not be able to send messages to the DeepdeskSDK instance, resulting in a timeout: new Error('Timeout')

getConversationBySessionId

Get the current conversation created by the Deepdesk backend via the Deepdesk webhooks.

Optionally add polling options when you are not sure if the webhook received the message in time.

ts
deepdeskSDK.getConversationBySessionId(
    sessionId: string,
    options?: RetryOptions
): Promise<Conversation>
ts
interface RetryOptions {
  /**
   * Number of attempts in the case the conversation is not created yet via the Deepdesk webhook.
   */
  attempts?: number;

  /**
   * Delay between attempts in miliseconds
   * Default: 1000(ms)
   */
  retryDelay?: number;
}

upsertConversation

Create or get and update conversation based on unique sessionId/agentId/platform signature.

Note: Only use this method when there is no backend integration possible. The preferred route is to implement the Deepdesk backend webhooks for notifying Deepdesk of new messages (thus creating the conversation in the backend) and using getConversationBySessionId in the front end to get de correct conversation.

ts
deepdeskSDK.upsertConversation(options: UpsertConversationOptions): Promise<Conversation>;
ts
interface UpsertConversationOptions {
  /**
   * The platform's conversation/thread/case ID.
   */
  sessionId: string;

  /**
   * The messaging platform, e.g. 'liveengage'
   */
  platform: string;

  /**
   * Optional client profile code, e.g. 'b2b' or 'b2c'.
   * This option is seldom required as the profile code is typically determined by the provided tags.
   */
  profileCode?: string;

  /**
   * The platform's agent ID
   */
  agentId: string;

  /**
   * The platform's agent name
   */
  agentName?: string;

  /**
   * The platform's agent name used in the chat
   */
  agentNickname?: string;

  /**
   * The platform's agent email.
   * This is used for connecting platform user to Deepdesk user.
   */
  agentEmail?: string;

  /**
   * The conversation tags serve the purpose of distinguishing between different conversations types.
   * These tags, in turn, are utilized to determine the appropriate profile (code).
   * Tags could be agent skills, team id, chat source, channel (web chat / whatsapp / sms etc.).
   */
  tags?: Record<string, string> | null;
}

postMessages

Post visitor, agent or bot messages to Deepdesk.

Note: Only use this method when there is no backend integration possible. The preferred route is to implement the Deepdesk backend webhooks for notifying Deepdesk of new messages.

ts
deepdeskSDK.postMessages(messages: ConversationMessage[]): Promise<void>;
ts
interface ConversationMessage = {
  /**
   * The message ID.
   * This is used to deduplicate messages.
   * If a message with a provided ID already exists, the new message is ignored.
   */
  id: string;

  /**
   * The type of entity who wrote the message.
   */
  source: "agent" | "visitor" | "bot" | "system";

  /**
   * The message text.
   */
  text: string;

  /**
   * The message time stamp.
   * Eg: 2023-07-25T11:43:55.308+00:00
   * Caveat: using 'Z' at the end (2023-07-25T11:43:55.308Z) will throw an error.
   */
  time: string;

  /**
   * The platform's native author ID.
   * This could be a visitor or agent ID.
   */
  authorId: string;

  /**
   * The message's author name.
   */
  authorName?: string | undefined;

  /**
   * The message's author email.
   */
  authorEmail?: string | undefined;

  /**
   * The messages tags serve the purpose of distinguishing between different conversations types.
   * These tags, in turn, are utilized to determine the appropriate profile (code).
   * Tags could be agent skills, team id, chat source, channel (web chat / whatsapp / sms etc.).
   */
  tags: Record<string, string> | null;
}

mount

Mount the suggestions overlay and / or the tab completion components on a textarea or contenteditable div.

ts
deepdeskSDK.mount(element: HTMLElement, options?: MountOptions);
ts
interface MountOptions {
  /*
   * Custom suggestion overlay styling
   * See: /guide/custom-styling/introduction
   */
  customStyles?: InputOverlayCustomStyles;

  /*
   * Enable or disable text suggestions
   */
  showTextSuggestions?: boolean;

  /*
   * Provide max. number of suggestions.
   * Default: 3 (max. 10)
   */
  textSuggestionsCount?: number;

  /*
   * Enable or disable style suggestions.
   * Default: false
   */
  showStyleSuggestions?: boolean;

  /*
   * Enable or disable tab completion text.
   * Default: true
   */
  showTabCompletion?: boolean;

  /*
   * Advanced: Provide you own InputMediator class.
   * DeepdeskSDK <-> InputMediator <-> platform input
   * Default: Deepdesk's TextAreaInput or ContentEditableInput depended on mount element.
   * See: /reference/classes/input-mediator
   */
  inputMediator?: InputMediator<HTMLElement>;

  /*
   * Automatically detect when an agent submits a message.
   * Default: false
   *
   * Can be enabled instead of manually calling `DeepdeskSDK.notifySubmit()`.
   * Enabling this setting is discouraged, because it only works in ideal circumstances.
   * The algorithm assumes that if the textarea is cleared,
   * and it is not a result of user action (Delete, Backspace, Cut, etc.),
   * the text in the textarea must have been submitted.
   */
  detectSubmit?: boolean;

  /*
   * Automatically detect start/continue en stop/pauze of conversation handling
   * Default: false
   * Since: v9.3.0
   *
   * This replaces the need to programmatically call handlingTimeStart and handlingTimeStop.
   * Setting this flag to true is OK for most platforms.
   * For a more fine-grained control use handlingTimeStart and handlingTimeStop instead.
   */
  automaticHandlingTime?: boolean;

  /*
   * By default append overlay to element.parentElement
   * Optionally append to different HTMLElement, for example `document.body`
   */
  appendOverlayTo?: HTMLElement;
}

Mounting and login

Use login() after mount(). Because when a user is not logged in, and login() is called, then mount will show a login button.

ts
deepdeskSDK.mount(inputElement);

deepdeskSDK.login().then(() => {
    deepdeskSDK.getConversationBySessionId('123', {
        attempts: 5,
        retryDelay: 500,
    }).catch(() => {
        console.log('Could not find conversation');

        // Cleanup other stuf like listeners and unmount:
        deepdeskSDK.unmount();
    });
}

refresh

Refresh suggestions based on the current conversation messages. Use when agent or visitor has submitted a message and Deepdesk webhook is notified. Be carefull not to refresh suggestions when the agent is already typing.

ts
deepdeskSDK.refresh(): Promise<void>;

handlingTimeStart

Start or continue timing the interaction between agent and customer. Is used to track the average handling time (AHT).

ts
deepdeskSDK.handlingTimeStart(): void;

handlingTimeStop

Stop or pause timing the interaction between agent and customer Sends an (intermediate) analytics event to Deepdesk.

ts
deepdeskSDK.handlingTimeStop(): void;

notifySubmit

Method to call when the agent has sent a message to the visitor. Sends an analytics event to Deepdesk.

ts
// Call `notifySubmit` after message is successfully sent by platform,
// but before agent input element is emptied.
deepdeskSDK.notifySubmit();

notifySubmit sends an analytics event to Deepdesk containing the sent text. That is why it is importent to call this method when the agent input element still contains the sent text. If for some reason the input field is already reset before calling notifySubmit, pass the sent text manually:

ts
deepdeskSDK.notifySubmit({ text: sentText });

on

Listen to the DeepdeskSDK events when the agent interacts with the provided suggestions.

The function returns a callback which allows you to remove the listener. An alternative to remove a listener is to use the deepdeskSDK.off(eventName, listener) method.

tsx
const removeListener = deepdeskSDK.on(eventName, listener);

removeListener();

'select-suggestion'

An agent selected a suggestion from the suggestions overlay near the agent input, from the widget or from the search bar (CMD+K).

tsx
deepdeskSDK.on('select-suggestion', (event: SelectSuggestionEvent) => void);

interface SelectSuggestionEvent {
  /**
   * The suggestion text to insert
   */
  text: string;

  /**
   * Range of current text to be replaced.
   * New lines are counted as a single character "\n".
   */
  replace: { start: number, end: number };

  /**
   * Suggested selection after the text is replaced.
   * New lines are counted as a single character "\n".
   */
  selectionAfter?: { start: number, end: number };

  /**
   * Type of the suggestion
   * Since: v9.9.0
   */
  type: 'default' | 'url' | 'template' | 'pinned-message' | '<account-custom-type>';

  /**
   * Raw access to the selected suggestion
   */
  suggestion: TextSuggestion | URLSuggestion | PinnedMessage;
}

'select-image'

An agent selected an image by using CMD+K.

tsx
deepdeskSDK.on('select-image', (event: SelectImageEvent) => void);

interface SelectImageEvent {
  /**
   * Raw access to the selected suggestion.
   */
  suggestion: ImageSuggestion;
}

interface ImageSuggestion {
  id: string;

  /**
   * Absolute url of the image.
   */
  image: string;

  /**
   * Comma separated list of labels.
   */
  labels: string;

  /**
   * Locale of the search result.
   */
  locale?: string | null;

  /**
   * Owner of the resource.
   */
  owner?: string | null;

  /**
   * Term used to search for the resource.
   */
  searchTerm: string;

  /**
   * Analytics source type.
   */
  source: "search-image";

  /**
   * The matched text of the source.
   */
  sourceText: string;

  /**
   * Studio status. For DeepdeskSDK always 'ENABLED'.
   */
  status: "ENABLED";

  /**
   * Display text.
   */
  text: string;

  /**
   * Display title. Normally the same as `text`.
   */
  title?: string | null;

  /**
   * Type of search result.
   */
  type: "IMAGE";
}

'replace'

An agent pressed ESC to restore the input value to the typed text.

tsx
deepdeskSDK.on('replace', (event: ReplaceEvent) => void);

interface ReplaceEvent {
  /**
   * The suggestion text to insert
   */
  text: string;

  /**
   * Range of current text to be replaced.
   * New lines are counted as a single character "\n"
   */
  replace: { start: number, end: number };
}

'reset'

An agent pressed ESC to restore the input value to the typed text.

tsx
deepdeskSDK.on('reset', (event: ResetEvent) => void);

interface ResetEvent {
  /**
   * The suggestion text to insert
   */
  text: string;

  /**
   * Suggested selection after the text is replaced.
   * New lines are counted as a single character "\n".
   */
  selectionAfter: { start: number, end: number };
}

off

Remove a listener from the DeepdeskSDK.

tsx
deepdeskSDK.off(eventName: string, listener: (event: unknown) => void);

Omitting the arguments will remove all listeners.

tsx
deepdeskSDK.off();

renderWidget

Mount the the widget in a HTML element. It will expand to the full height and width of the targeted element.

The widget can contain url suggestions, pinned messages, autoflows and custom messages. For the last two the Deepdesk Broker must be configured as well. See the brokerUrl option in the DeepdeskSDK constructor.

ts
deepdeskSDK.renderWidget(element: HTMLElement, options?: WidgetOptions);
ts
interface WidgetOptions {
  /*
   * Custom widget styling
   * See: /guide/custom-styling/widget
   */
  customStyles?: WidgetCustomStyles;

  /*
   * Enable or disable images for url suggestions and pinned messages.
   * Default: false
   */
  showImages?: boolean;
}

setVisitorInfo

Set visitor info, used for placeholder interpolation in the suggestions.

ts
deepdeskSDK.setVisitorInfo(visitorInfo: VisitorInfo): void;
ts
interface VisitorInfo {
  /**
   * Platform's visitor id
   */
  visitorId?: string;

  /**
   * Visitor name. Visitor first name is often what you want to show in the suggestions.
   */
  visitorName?: string;

  /**
   * Visitor e-mail
   */
  visitorEmail?: string;

  /**
   * Visitor postal code
   */
  visitorPostalCode?: string;

  /**
   * Visitor house number
   */
  visitorHouseNumber?: string;
}

Placeholder replacements:

ts
'{visitor_name}': visitorName,
'{postal_code}': visitorPostalCode,
'{street_number}': visitorHouseNumber,
'{house_number}': visitorHouseNumber,
'{postal_code_house_number}': `${visitorPostalCode} ${visitorHouseNumber}`,
'{postal_code_street_number}': `${visitorPostalCode} ${visitorHouseNumber}`,
'{subscription_name}': visitorName,

setAgentInfo

Set agent info, used for placeholder interpolation in the suggestions.

ts
deepdeskSDK.setAgentInfo(agentInfo: AgentInfo): void;
ts
interface AgentInfo {
  /**
   * Platform's agent id
   */
  agentId?: string;

  /**
   * Agent's nickname or first name
   */
  agentNickname?: string;

  /**
   * Agent's first name or full name
   */
  agentName?: string;

  /**
   * Agent's e-mail address
   */
  agentEmail?: string;
}

Placeholder replacements:

ts
'{agent_name}': agentNickname,

setConversationQuery

Set a callback method that will return the conversation, synchronous or asynchronous.

The conversation returned has to be an array of objects. Each object containing a text and a source. See: PlainMessage below.

Setting this makes the conversation summary and entity detection features possible.

ts
deepdeskSDK.setConversationQuery(callback: setConversationQueryCallback): void;
ts
interface PlainMessage = {
  source: 'agent' | 'visitor';
  text: string;
}

type setConversationQueryCallback = () => Promise<PlainMessage[]> | PlainMessage[];

getSummary

Returns a string that contains a summary of the current conversation.

ts
await deepdeskSDK.getSummary();

It assumes that the method setConversationQuery has been called before the getSummary method and will throw an error when this is not the case.