Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@tiledesk/tiledesk-client

Tiledesk5kMIT0.10.13

Javascript (nodeJS) SDK for Tiledesk REST APIs

tiledesk, chatbot, client, livechat, nodejs, node, live, chat, support, helpdesk

readme

Full NodeJS API reference is hosted on Github

Introduction

Follow this guide to use the Tiledesk JavaScript SDK in your Node.js application.

Before you can add Tiledesk to your Node.js app, you need a Tiledesk account and a Tiledesk project. Once you create your project you will have a projectID, a user to play with project APIs, a project secret for custom authentication and all the stuff need to work with Tiledesk and his APIs.

Add Tiledesk to your project

Install TiledeskClient library with npm command:

npm install @tiledesk/tiledesk-client

Alternatively use package.json to import the library in the "dependencies" property, as in the following example:

{
  "name": "Hello Tiledesk nodeJS",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@tiledesk/tiledesk-client": "^0.8.5"
  }
}

Then run

npm install

Once installed you can import TiledeskClient() class in your Node.js file using the "require" command:

const { TiledeskClient } = require('@tiledesk/tiledesk-client');

Authentication

Before you can interact with Tiledesk APIs you need to authenticate. Tiledesk provides three authentication methods.

  1. Authentication with email and password
  2. Authentication as anonymous user
  3. Custom authentication

Authentication with email and password

This is the authentication method that you need when working with Tiledesk APIs. Every API methods, except authentication ones, work on a project + role + token basis. To authenticate and get a token with email and password use the authEmailPassword() method from the TiledeskClient class. You must provide the APIKEY to authenticate. Actually APIKEYs are experimental and can be omitted. Just use the string 'APIKEY' in place of the real one.

TiledeskClient.authEmailPassword(
  'APIKEY',
  /* EMAIL */,
  /* PASSWORD */,
  null,
  function(err, result) {
      if (!err && result) {
          console.log('You got your auth token!', result.token);
          console.log('Your user ID!', result.user._id);
      }
  else {
      console.err("An error occurred", err);
  }
});

In response you will get a token to interact with APIs using your account and the corresponding user ID.

Authentication as Anonymous user

This authentication method is useful for anonymous user that need to interact with support APIs

TiledeskClient.anonymousAuthentication(
  PROJECT_ID,
  APIKEY,
  null,
  function(err, result) {
    assert(result.token != null);
    let token = result.token;
  }
);

In response you will get a token to interact with APIs in anonymous mode.

Custom authentication

With custom authentication you can work with your own users making them auto-signin in Tiledesk without previous signup. This can be used in the place of anonymous authentication to certify users coming from external application, giving them a certified identity in Tiledesk.

For this example import uuid:

npm install uuid
const { v4: uuidv4 } = require('uuid');
var externalUserId = uuidv4();
var externalUser = {
    _id: externalUserId,
    firstname:"John",
    lastname:"Wick",
    email: "john@wick.com"
};
var signOptions = {                                                            
  subject:  'userexternal',
  audience:  'https://tiledesk.com/projects/' + YOUR_PROJECT_ID
};
var jwtCustomToken = "JWT " + jwt.sign(externalUser, YUOR_PROJECT_SECRET, signOptions);

TiledeskClient.customAuthentication(
  jwtCustomToken,
  APIKEY,
  null,
  function(err, result) {
      if (!err && result) {
          let token = result.token;
      }
  }
);

The TiledeskClient class

To interact with Tiledesk APIs you need to create an instance of a TiledeskClient() class using his constructor. You MUST supply an APIKEY, an existing Project ID and a valid token, this last one got through some of the authentication methods above.

In the next example we first authenticate using our user credentials, then we create a new TiledeskClient instance using a PROJECT_ID and the token we got from authentication:

TiledeskClient.authEmailPassword(
  'APIKEY',
  /* EMAIL */,
  /* PASSWORD */,
  null,
  function(err, result) {
      if (!err && result) {
          console.log('You got the token!', result.token);
          const tdclient = new TiledeskClient({
              APIKEY: /* APIKEY */,
              projectId: /* PROJECT_ID */,
              token: result.token
          });
      }
  else {
      console.err("An error occurred", err);
  }
});

Working with support requests

A Support Request is a set of metadata and messages that describe whole conversation. A Support Request contains data regarding the Request status (open/assigned/closed etc.), the web/app source page of the conversation, the end-user ID, his email etc. The main information consist of the messages sent and received by the request. Using messaging APIs is indeed the most common way to interact with the request.

Yiou can interact with the request messages using Messaging APIs. Or you can interact directly with Request's metadata using the Request APIs.

Create a support request

To create a support request you simply send a message to a not-existing request ID. A request is automcatically created when you send a message to a no-existing request.

It's up to you to create a new, UNIQUE request ID, following the Tiledesk rules. If you don't want to know how to create a new request ID, to get a new one you can use the static function TiledeskClient.newRequestId() passing PROJECT_ID as a parameter, as in the following example:

const text_value = 'test message';
const request_id = TiledeskClient.newRequestId(PROJECT_ID);
tdclient.sendSupportMessage(
  request_id,
  {text: text_value},
  (err, result) => {
    assert(err === null);
    assert(result != null);
    assert(result.text === text_value);
});

As soon as you send a new message to Tiledesk with the new requestID, the request is created and ready to be processed.

With the same sendSupportMessage() function you can send additional messages to the request. In this example we send a second message to the request using the same request id we used to create the request in the previous example.

tdclient.sendSupportMessage(
  request_id,
  {text: 'second message'},
  (err, result) => {
    assert(err === null);
    assert(result != null);
    assert(result.text === text_value);
});

With Tiledesk you can also get sent messages to a request's conversation using Webhooks, subscribing to the Message.create event.

Get a support request by id

let REQUEST_ID = /* THE REQUEST ID */;
tdclient.getRequestById(REQUEST_ID, (err, result) => {
    const request = result;
    if (request.request_id != null) {
      console.log("Got request with first text:", request.first_text);
    }
});

Query support requests

tdclient.getAllRequests(
  {
      limit: 1,
      status: TiledeskClient.UNASSIGNED_STATUS
  },
  (err, result) => {
    assert(result);
    const requests = result.requests;
    assert(requests);
    assert(result.requests);
    assert(Array.isArray(requests));
    assert(result.requests.length > 0);
  }
);

Working with teamates

A Project's teammate is a user who collaborates with you on a specific project.

While the name on the User Interface and documentaion level is always teammate, on the APIs level a teamate is called ProjectUser. As the the name suggests, a ProjectUser is a Tiledesk User invited with a specific role on a specific Project.

Update teamate status to available/unavailable

With TiledeskClient.updateProjectUserCurrentlyLoggedIn() you will update the status of the user token in the TiledeskClient constructor.

const tdclient = new TiledeskClient({
    APIKEY: /* APIKEY */,
    projectId: /* PROJECT_ID */,
    token: result.token
});
tdclient.updateProjectUserCurrentlyLoggedIn(
    {
        user_available: true
    },
    function(err, result) {
        if (!err && result) {
            assert(result);
            assert(result.user_available === true);
        }
    }
);

Check teamate status

const tdclient = new TiledeskClient({
    APIKEY: /* APIKEY */,
    projectId: /* PROJECT_ID */,
    token: result.token
});
tdclient.getProjectUser(
  USER_ID,
  function(err, result) {
      if (!err && result) {
          assert(Array.isArray(result));
          assert(result[0]._id != null);
          assert(result[0].user_available === true);
          let PROJECT_USER_ID = result[0]._id;
      }
      else {
          assert.ok(false);
      }
  }
);

The PROJECT_USER_ID variable is the teamate ID of your user (USER_ID) on the PROJECT_ID you specified in the TiledeskClient custructor.

Switch between Cloud and Self hosted instances

Self hosted option

These APIs automatically work with the Tiledesk cloud instance.

If you are running your own self-hosted instance of Tiledesk, the APIs provide a specific option to select your endpoint.

Specify the API endpoint in class methods

If you are using a class method, i.e. authentication methods, use the options.APIURL parameter to specify the endpoint, as in the following example:

TiledeskClient.authEmailPassword(
    APIKEY,
    EMAIL,
    PASSWORD,
    {
      APIURL: API_ENDPOINT
    }
});

Specify the API endpoint in instance methods

If instead you are using instance methods working with an instance of TiledeskClient, you must specify the parameter in the constructor config object as config.APIRUL:

const tdclient = new TiledeskClient({
    APIKEY: APIKEY,
    projectId: PROJECT_ID,
    token: YOUR_TOKEN,
    APIURL: API_ENDPOINT
})

PS: Just remember that the test/test.js is the best place to get working examples of how the library works!

changelog

Client library for Tiledesk nodejs APIs client

This library is on npm: https://www.npmjs.com/package/@tiledesk/tiledesk-client

0.10.13 - online

  • fix: added return on err callbacks of this.findBotByName()

0.10.12 - online

  • fixed reject(error) => reject(err) in closeRequest()
  • added test test/CHATBOT_close_conversation_bot-auto_import.js

0.10.11 - online

  • fixed log in authEmailPassword(): this.log => _log
  • added getGroup() - untested
  • added check on request in changeBot() => if (request && request.participantsBots && request.participantsBots.length > 0)...

0.10.10 - online

  • check post missing params errors on mqtt-route /connect

0.10.9

  • mqtt route settings removed from startApp and moved in post /connect

0.10.8

  • log fix

0.10.7

  • fix: added libs mqtt, body-parser to packege.json

0.10.6

  • added support for tags
  • added mqtt-route.js with /connect endpoint

0.10.5

  • added test 'updateRequestProperties()'
  • added getLeadById()
  • added test 'updateLead(), getLeadById()'

0.10.4 - online

  • /emails/send => /emails/internal/send

0.10.3 - online

  • deprecated leadUpdateData() for leadUpdate()

0.10.2 - online

  • fixed reject/resolve (callback or .then/.catch) in sendSupportMessage()

0.10.1 - online

  • added moveToAgent() method

0.10.0 - online

  • updated to /v3 endpoint

0.9.6 - online

  • fixed stringyfied some logs

0.9.5 - online

  • sendSupportMessage() async fix.

0.9.4 - online

  • improved testing with multiple sendSupportMessage()

0.9.3 - online

  • added sendEmail

0.9.3 - online

  • debug log => console.log("Tiledesk Client v 0.9.x: url.startsWith https: && httpsOptions")
  • bug fixed this.httpsOptions in static myrequest

0.9.2 - online

  • test method static version09()

0.8.42 - online

  • added options.httpsOptions (supports additional options ex. rejectUnauthorized = true|false)
  • added default to rejectUnauthorized = false on https connections

0.8.41

  • getRequestById() not-found simply sends "null", removed error

0.8.40

  • console.error() log removed from TiledeskClient.myrequest()
  • added test for getRequestById() not found

0.8.39

  • added getProjectAvailableAgents()

0.8.38

  • added closeRequest()
  • Added async/await to sendSupportMessage()

0.8.37

  • updatedLeadEmailFullname() renamed => updateLead()
  • updateLead() added new "attributes" parameter
  • Added async/await to updateLead()

0.8.36

  • Added async/await to getIntents()

0.8.34

  • Added async/await to getRequestById()

0.8.33

  • replaceBotByName() removed hidden start message sending

0.8.30

  • added replaceBotByName()
  • fixed findBotByName()

0.8.29

  • added createIntent()
  • added getIntents()

0.8.24

  • bug fix

0.8.23

  • bug fix

0.8.22

  • bug fix

0.8.21

  • HMESSAGE_DIRECTIVE constant renamed to: HIDDEN_MESSAGE_DIRECTIVE
  • Orchestration APIs, added removeCurrentBot() and normalizeBotId()

0.8.20

  • added assign() method

0.8.19

  • fixed doc getTeam() added REST API doc reference

0.8.18 - online

  • added getTeam()

0.8.17 - online

  • log fix

0.8.16 - online

  • changeBot() now takes a simple botId ('bot_' prefix constraint removed)

0.8.15 - online

  • added orchestration APIs: changeBot, changeBotAndMessage, addParticipantAndMessage

0.8.14 - online

  • added "console.error("An error occurred:", error)" in TiledeskClient.myrequest "catch" block.

0.8.13 - online

  • added getDepartment()
  • added createDepartment()
  • added updateDepartment()
  • added deleteDepartment()
  • added testing

0.8.12 - online

  • added getDepartments() -> TODO TEST
  • added getAllDepartments() -> TODO TEST

0.8.11

  • added test for empty text

0.8.10 - online

  • bug fix: fixToken() call removed from some methods

0.8.9 - online

  • bug fix: updateRequestDepartment()

0.8.8 - online

  • bug fix

0.8.7 - online

  • added deleteRequestParticipant() -> TODO TEST
  • added addRequestParticipant() -> TODO TEST
  • added getAllBots()
  • added getBot()
  • added createBot()
  • added updateBot()
  • added deleteBot()
  • updated documentation

0.8.6 - online

  • TiledeskClient.myrequest callback refactored to take only 2 parameters: err, resbody

0.8.5 - online

  • doc fix

0.8.4 - online

0.8.3 - online

  • changed method signature (token first): customAuthentication(token, apikey, options, callback)

0.8.2

  • 'project_id' instance property and constructor options property renamed in 'projectId' (camel case)
  • updateDepartment() renamed in updateRequestDepartment()
  • updateRequestDepartment: in options parameter added 'nobot' option
  • added updateProjectUser()
  • added documentation with jsdoc
  • added getAllRequests()
  • added test case for getRequestById()
  • sendDirectMessage() renamed in sendChatMessage()
  • sendMessage() renamed in sendSupportMessage()
  • added newRequestId()
  • anonymousAuthentication(callback, options) signature refactored (removed first 'projectId' param, added 'options' param)
  • added Axios. Removed Request.
  • anonymousAuthentication(), customAuthentication(), authEmailPassword() are now 'static'. Signature modifed to provide 'apikey' and options (APIURL, log).
  • options.projectId and options.token are now mandatory in constructor()
  • removed tail 'options' parameter from all calls.

0.7.14 - online

  • added getRequestById()

0.7.13 - online

  • bug fix - removed from updateLeadEmailFullname(): throw new Error('options.lead_id can NOT be empty.');

0.7.12 - online

  • added sendDirectMessage()

0.7.11 - online

  • bug fix - some projectId to project_id

0.7.10 - online

  • removed token as explicit parameter in some function calls. token is now an optional constructor parameter. It's also supported by "options" parameter in some function calls.
  • added customAuthentication()

0.7.9 - online

  • Added "options" parameter some function calls.
  • removed project_id as explicit parameter in some function calls. project_id is now an optional constructor parameter. It's also supported by "options" parameter in some function calls.
  • added customAuthentication()

0.7.8 - online

  • bug fix - Added missing jwt_token() to sendMessage and more.

0.7.7 - online

  • bug fix: APIURL

0.7.6 - online

  • added updateProjectUserCurrentlyLoggedIn
  • added "options" as last parameter of getRequests to allow adding additional params as no_populate, snap_department etc.

0.7.5 - online

  • error log refactored adding request and response headers of the http-request

0.7.4 - online

  • for each call always do: const jwt_token = TiledeskClient.fixToken(token)
  • added err.options in error obj replies
  • improved log
  • added getProjectUser() to test

0.7.3 - online

  • removed the unused, undocumented "getAllProjectUsers()"

0.7.2 - online

  • bug fix

0.7.1 - online

  • Removed raw methods, now creating an instance of TiledeskClient is mandatory, see test 'init()'
  • APIKEY is mandatory
  • added option to log request and response HTTP calls, see test for the howto
  • added automated testing

0.6.36 - online

  • some methods refactoring

0.6.27 - online

  • added updateLeadEmailFullname()
  • added updateDepartment()
  • added updateRequest()
  • added dependency declaration in package.json: "request": "^2.88.2"

0.6.26 - online

  • SendMessageRaw fix: response not defined

0.6.25 - online

  • introduced myrequest() to decouple "request" lib
  • now each method shares the same return callback/error handling

0.6.24 - online

  • getErr()

0.6.22 - online

  • added some console.log to openNow()

0.6.21 - online

  • added: moved request -> myrequesat for openNow()
  • fixed: call of fixToken for openNow()

0.6.20

  • added: test fireEvent()
  • added: test anonymousAuthentication()
  • added: test openNow()

0.6.19

  • added: fireEvent() raw method
  • added: fireEvent() instance method

0.6.18

  • added: openNow() instance method