NAV Navbar
shell javascript
api
  • Introduction
  • Authentication
  • NLP services
  • QnA
  • Webchat
  • Botmeter
  • Introduction

    Botfuel offers a set of authenticated APIs to enhance your bots:

    The platform supports the following languages:

    Language Parameter
    French
    fr
    English
    en
    Spanish
    es

    Authentication

    Our APIs require authentication for security and identification purposes. To get app credentials, create an account on the developer portal (https://app.botfuel.io) and create an App from your account.

    Create an account

    Add both the app id and key in the headers of any request to our APIs, with keys App-Id and App-Key.

    # With shell, you can just pass the correct header with each request
    
    curl 'https://api.botfuel.io/<api_route>' \
      -H "App-Id: <your_app_id>" \
      -H "App-Key: <your_app_key>"
    

    If you use Node.js, our SDKs will take that out of your plate : simply instantiate classes with an object having keys keys APP_ID and APP_KEY.

    const SdkClass = require('@botfuel/<choice_of_sdk>');
    
    const sdk = new SdkClass({
      appId: '<your_app_id>',
      appKey: '<your_app_key>',
    });
    

    NLP services

    We also provide a set of SDKs in Node.js to handle authentication and response format. You can view examples in both curl request format and by using SDKs in the right pane.

    These SDKs are all open source, you can view them or post an issue on Github:

    See our Github

    Entity extraction

    Specifications

    HTTP Request

    GET https://api.botfuel.io/nlp/entity-extraction

    Query Parameters

    Parameter Default Type Description Required
    sentence null String Sentence you want to extract entities from. Required
    dimensions null Array Array of strings representing entities.
    If provided, the result is filtered by this list
    The full list of dimensions available is described below.
    Optional
    antidimensions [] Array Array of strings representing entities.
    If provided, the result is filtered out by this list.
    Optional
    timezone UTC String Timezone in which timestamps (in milliseconds) from relative and absolute times are computed.
    The timezone id must be in long form, e.g. 'America/Matamoros'.
    Optional
    case_sensitive false Boolean If false, replace capitalized characters by non-capitalized characters before treating the sentence. Optional
    keep_quotes false Boolean If false, replace single quotes by blank spaces. Optional
    keep_accents false Boolean If false, replace accented characters by non-accented characters. Optional

    Possible dimensions

    Here is the list of implemented dimensions.

    NameDescriptionExamples
    street-number well formed street number 221b
    street-type street-type used in address roads
    postal postal code wellformed of UK NW1 6XE
    city name of a city Paris
    country name of a country France
    address well formed postal address 2 Macquarie Street, Sydney Australia
    language a spoken language tamil
    nationality a name ofr people of a country irishwoman
    email well formed email address [email protected]
    handle any group of characters beginning with '@' @myself
    hashtag any group of characters begining with '#' #ThisIsIt
    number an integer in numerical form 1024
    an integer spelt out forty two
    ordinal an ordinal number third
    time a relative time tomorrow
    an interval of time from 8am to noon
    an absolute time 11th august 1999
    duration a duration together with an unit 2mins
    distance a length measurment with unit 3 kilometers
    area a area measurment with unit 4 sq ft
    volume a volume measurment with unit 5 liters
    temperature a temperature measurment with unit 5 degres celcius below zero
    forename a common forename Mary
    family a family member aunt
    percentage a number representing a percentage 50%
    url extract a well formed url http://botfuel.io/
    item-count a number of items 2 flowers
    currency a currency dollars
    money a currency amount three dollars
    color a color red

    Response structure

    Parameter Type Description
    dim String Dimension of the returned entity.
    body String Part of the sentence that produced the entity.
    values Array Array of details object of each extracted entity.
    start Number Start index of the body substring in the whole sentence.
    end Number End index of the body substring in the whole sentence.

    Examples

    Basic

    Let's extract the address entity from the sentence 137 boulevard de Sébastopol à Paris: https://api.botfuel.io/staging/nlp/entity-extraction?sentence

    curl -X GET 'https://api.botfuel.io/nlp/entity-extraction'\
    '?sentence=221+Baker+St+London+NW1+6XE+UK'\
    '&dimension=address' \
    -H "App-Id: $APP_ID" \
    -H "App-Key: $APP_KEY"
    
    const { EntityExtraction } = require('botfuel-nlp-sdk');
    
    const extractor = new EntityExtraction({
      appId: '<APP_ID>',
      appKey: '<APP_KEY>',
    });
    extractor
      .compute({
        sentence: '221b Baker St London NW1 6XE UK',
        dimensions: ['address'],
      })
      .then(entities => {
        console.log(entities);
      });
    
    // Response
    [
      {
        "dim": "address",
        "body": "221 baker st london nw1 6xe",
        "values": [
          {
            "value": "221 baker street London nw1 6xe",
            "street": "baker street",
            "location": "London",
            "number": "221"
          }
        ],
        "start": 0,
        "end": 27
      }
    ]
    

    Several dimensions extracted

    Here are some more complex examples, combining more than one dimension.

    More than one entity can be extracted from one sentence. For instance, consider the example:

    two liters of water cost 4.02 pounds, you can claim 50% discount on sunday

    where a time (sunday) and a percentage (50%) will be extracted. We can provide as many 'antidimensions' as we want to hide in the result. Let's remove time, percentage and number

    curl \
    -X GET \
    'https://api.botfuel.io/nlp/entity-extraction'\
    '?sentence=two+liters+of+water+cost+4.02+pounds'\
    '%2C+you+can+claim+50%25+discount+on+sunday'\
    '&antidimensions=percentage,time,number' \
    -H "App-Id: $APP_ID" \
    -H "App-Key: $APP_KEY"
    
    const { EntityExtraction } = require('botfuel-nlp-sdk');
    
    const extractor = new EntityExtraction({
      appId: '<APP_ID>',
      appKey: '<APP_KEY>',
    });
    extractor
      .compute({
        sentence:
          'two liters of water cost 4.02 pounds, you can claim 50% discount on sunday',
        antidimensions: ['percentage', 'time', 'number'],
      })
      .then(entities => {
        console.log(entities);
      });
    
    // Response
    [
      {
        "dim": "money",
        "body": "4.02 pounds",
        "values": [
          {
            "value": 4.02,
            "unit": "£",
            "type": "float"
          }
        ],
        "start": 25,
        "end": 36
      },
      {
        "dim": "volume",
        "body": "two liters",
        "values": [
          {
            "value": 2,
            "unit": "litre",
            "type": "integer"
          }
        ],
        "start": 0,
        "end": 10
      }
    ]
    

    Extracting intervals

    When two time entities are detected and they are boundaries of an interval of time, an interval entity is extracted. For instance, here is an example including a time interval:

    Post Office is closed last sunday of march between 8am and noon

    curl \
    -X GET \
    'https://api.botfuel.io/nlp/entity-extraction'\
    '?sentence=Post+Office+is+closed+last+sunday+of+march'\
    '+between+8am+and+noon' \
    -H "App-Id: $APP_ID" \
    -H "App-Key: $APP_KEY"
    
    const { EntityExtraction } = require('botfuel-nlp-sdk');
    
    const extractor = new EntityExtraction({
      appId: '<APP_ID>',
      appKey: '<APP_KEY>',
    });
    extractor
      .compute({
        sentence: 'Post Office is closed last sunday of march between 8am and noon',
      })
      .then(entities => {
        console.log(entities);
      });
    
    // Response
    [
      {
        "dim": "time",
        "body": "last sunday of march between 8am and noon",
        "values": [
          {
            "type": "interval",
            "from": {
              "time-stamp": "2018-03-25T08:00:00.000Z",
              "unit": "hour",
              "milliseconds": 1521964800000
            },
            "to": {
              "time-stamp": "2018-03-25T12:00:00.000Z",
              "unit": "hour",
              "milliseconds": 1521979200000
            }
          }
        ],
        "start": 22,
        "end": 63
      }
    ]
    

    Spell checking

    The Spell checking service takes a sentence as a parameter and returns its correct spelling. The service detects at most two additions, deletions or modifications of characters. You can reduce the maximum distance to 1 to allow at most one change.

    Specifications

    HTTP Request

    GET https://api.botfuel.io/nlp/spellchecking

    Query Parameters

    Parameter Default Type Description Required
    sentence null String Sentence you want to spell check. Required
    key null String
    Possible values: 'FR_1', 'EN_1', 'FR_2', 'EN_2'
    Language in which you want to spell check.
    The number after the underscore represents the maximum distance allowed.
    Required

    Response structure

    Parameter Type Description
    originalSentence String The sentence you want to spell check
    sentenceTemplate String Template string representing the structure of the originalSentence.
    {x} are placeholders for the words to correct.
    correctWords Array The list of the corrected words
    correctSentence String The spell checked sentence
    originalWords Number The list of words composing the originalSentence
    possibleCorrections Number For each word, a list of possible corrections and the original word

    Examples

    Let’s spell check the sentence:
    the sentnece yuo watn to chekc:

    curl \
    -X GET \
    'https://api.botfuel.io/nlp/spellchecking'\
    '?sentence=the+sentnece+yuo+watn+to+chekc'\
    '&key=EN_1' \
    -H "App-Id: $APP_ID" \
    -H "App-Key: $APP_KEY"
    
    const { Spellchecking } = require('botfuel-nlp-sdk');
    
    const spellchecker = new Spellchecking({
      appId: '<APP_ID>',
      appKey: '<APP_KEY>',
    });
    spellchecker
      .compute({
        sentence: 'the sentnece yuo watn to chekc',
        key: 'EN_1',
      })
      .then(corrected => {
        console.log(corrected);
      });
    
    // Response
    {
      "originalSentence": "the sentnece yuo watn to chekc",
      "sentenceTemplate": "the {0} {1} {2} to {3}",
      "correctWords": ["sentence", "you", "want", "check"],
      "originalWords": ["sentnece", "yuo", "watn", "chekc"],
      "correctSentence": "the sentence you want to check",
      "possibleCorrections": [
        {
          "corrections": ["sentence"],
          "originalWord": "sentnece"
        },
        {
          "corrections": ["you"],
          "originalWord": "yuo"
        },
        {
          "corrections": ["want", "wasn", "warn", "watt", "wan", "wat"],
          "originalWord": "watn"
        },
        {
          "corrections": ["check"],
          "originalWord": "chekc"
        }
      ]
    }
    

    QnA

    Specifications

    HTTP Request

    POST https://api.botfuel.io/qna/api/v1/bots/classify

    Query Parameters

    Parameter Default Type Description Required
    sentence null String Question you want to get questions set and answer for Required

    Response structure

    The matching QnAs are provided as a list of elements with the structure below.

    Parameter Type Description
    probability float Probability that the sentence matches this question
    answer String Text to provide as an answer to the question asked
    questions Array Array of questions associated with the answer

    Examples

    Here is an example of how to use the classify API.

    curl -X POST 'https://api.botfuel.io/qna/api/v1/bots/classify' \
    -H 'Content-Type: application/json' \
    -H 'App-Id: <APP_ID>' \
    -H 'App-Key: <APP_KEY>' \
    -d '{ "sentence": "When will the post-office close ?" }'
    
    const QnA = require('botfuel-qna-sdk');
    
    const QnAClient = new QnA({
      appId: '<APP_ID>',
      appKey: '<APP_KEY>',
    });
    
    QnAClient
      .getMatchingQnas({ sentence: 'When will the post-office close ?' })
      .then(response => {
            console.log(response);
        });
    
    // Response
    [
        {
            "probability": 0.428571428,
            "answer" : "The post-office is open from 8am to 4pm.",
            "questions": [
                "At what time does the post-office close ?",
                "When does the post-office open ?",
                "What are the opening hours of the post-office ?"
            ]
        }
    ]
    

    Webchat

    Configuration

    <!-- This will include the latest version -->
    <script src="https://cdn.jsdelivr.net/npm/botfuel-webchat-client"></script>
    <script>
    BotfuelWebChat.init({
      appToken: '<APP_TOKEN>'
      // ...options
    });
    </script>
    
    <!-- To use an older webchat version, specify the version with @  -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    

    To integrate the webchat into your HTML page, use the code provided on the right pane and paste it just before the </html> tag.

    UI

    You can customize the webchat look and behavior using options documented below.

    Parameter Default Description Type
    appToken - String Required. Your app’s appToken. You can find it in the HTML snippet on the webchat page of your app or on the app edition page on the Botfuel Developer Portal.
    size {width: 400, height: 500} Object Size of the webchat window
    startOpen false Boolean Start with the dialog open or not
    startFullScreen false Boolean Start fullscreen
    embeddedContainerId "" String Embed the dialog inside the page instead of at the bottom right. Disables the startButton and forces startOpen to true
    theme See hereunder Object See Theme object
    labels See hereunder Object See Labels object
    menuActions See hereunder Array See Menu actions array
    voiceEnabled false Boolean Whether speech to text is enabled

    To receive and send messages, you must:

    <APP_TOKEN> is the appToken you set in the webchat script.
    <USER_ID> is generated client-side and sent to your bot on each user message.

    Theme

    The parameters of the theme object. Every parameter is optional, see default values on the right pane.

    theme: {
      colors: {
        main: '#65758e',
        mainText: '#fff',
        primary: '#0084f4',
        secondary: '#f1f0f0',
        primaryText: '#fff',
        secondaryText: '#000',
        background: '#fff'
      },
      buttons: {
        close: true,
        fullScreen: true
      },
      images: {
        botAvatar: '<DEFAULT_BOT_AVATAR>',
        userAvatar: '<DEFAULT_USER_AVATAR>',
        startButton: '<DEFAULT_START_BUTTON>'
      },
      startButtonStyle: 'bubble',
      dialogStyle: 'hover',
      fluid: false
    
    }
    
    Parameter Type Description
    colors.main String Background color of the title bar
    colors.mainText String Text color of the title bar
    colors.primary String Primary color (used for user messages)
    colors.primaryText String Color used for text with primary background
    colors.secondary String Secondary color (used for bot/operator messages)
    colors.secondaryText String Color used for text with secondary background
    colors.background String Background color of the webchat dialog
    buttons.close Boolean Show or hide the close button
    buttons.fullScreen Boolean Show or hide the fullscreen button
    images.botAvatar String Image url for the avatar of a user
    images.userAvatar String Image url for the avatar of the bot
    images.startButton String Image url for the startButton icon
    startButtonStyle String 'bubble' adds a background and border around the start button logo
    dialogStyle String 'hover' adds a border and shadow around the webchat dialog
    fluid Boolean Make the dialog use the width and height of its parent

    Default images

    botAvatar:

    userAvatar:

    startButton:

    Labels

    Text labels displayed in the webchat UI. Every parameter is optional, see default values on the right pane.

    labels: {
      sendButtonLabel: 'Send',
      messageInputPlaceholder: 'Write a message...',
      webchatHeaderTitle: 'How can I help you?',
      helpMessage: 'Our support is open from 9am to 7pm CET, from Monday to Friday.'
    }
    
    Parameter Type Description
    sendButtonLabel String Text label of the send message button
    messageInputPlaceholder String Placeholder of the user message input
    webchatHeaderTitle String Text displayed in the webchat header, at the top of the webchat UI
    helpMessage String Text displayed as a help message below the webchat header and above chat messages
    onboardingMessage String Text displayed as the initial bot message. If no value is specified, no message will be displayed

    Menu actions

    You can provide an array of custom actions that will be displayed on the left-hand side of the user input:

    Webchat menu actions

    menuActions: [
      {
        label: 'Greet',
        message: {
          type: 'text',
          payload: {
            value: 'Hello!',
          },
        },
      },
      {
        label: 'Custom action',
        message: {
          type: 'postback',
          payload: {
            value: {
              custom: 'this is custom',
            },
          },
        },
      },
    ];
    

    Each entry has to have a label and a message. Clicking on the menu entry will have the same effect as sending the message by typing it or clicking on a Postback button.

    Parameter Type Description
    label String Text label of menu entry
    message Object User message sent to the bot

    If you don’t provide a menuActions option or if it is an empty array, the menu won’t be displayed.

    Message format

    Bot messages

    Bot messages are sent from the bot to the webchat endpoint. The webchat server then publishes them to the client.

    Parameter Type Description
    type String
    Possible values:
    'text', 'table', 'quickreplies', 'actions'
    A string representing the message type.
    payload Object Object containing the message value. The Object structure changes according to the message type. See hereunder for an explanation for each type.

    Text

    To display a 'text', send a POST request to the webchat server endpoint (see right pane):

    curl -X POST 'https://webchat.botfuel.io/bots/<APP_TOKEN>/users/<USER_ID>/conversation/messages' \
    -H 'Content-Type: application/json' \
    -d '{
      "type": "text",
      "payload": {
        "value": "Hello world"
      }
    }'
    
    const rp = require('request-promise');
    
    rp
      .post({
        method: 'POST',
        uri:
          'https://webchat.botfuel.io/bots/<APP_TOKEN>/users/<USER_ID>/conversation/messages',
        body: {
          type: 'text',
          payload: {
            value: 'Hello world',
          },
        },
        json: true,
      })
      .then(result => {
        console.log(result);
      });
    
    // Response
    "OK"
    

    This will display:

    Webchat text message

    Payload value parameters:

    Parameter Type Description
    value String A string containing the message.

    Table

    To display a 'table', send a POST request to the webchat server endpoint (see right pane):

    curl -X POST 'https://webchat.botfuel.io/bots/<APP_TOKEN>/users/<USER_ID>/conversation/messages' \
    -H 'Content-Type: application/json' \
    -d '{
      "type": "table",
      "payload": {
        "value": {
          "schema": [
            {
              "key": "name",
              "label": "Name"
            },
            {
              "key": "job",
              "label": "Job title"
            }
          ],
          "rows": [
            {
              "name": "John Doe",
              "job": "Plumber"
            },
            {
              "name": "Jane Doe",
              "job": "Designer"
            }
          ]
        }
      }
    }'
    
    const rp = require('request-promise');
    
    rp
      .post({
        method: 'POST',
        uri:
          'https://webchat.botfuel.io/bots/<APP_TOKEN>/users/<USER_ID>/conversation/messages',
        body: {
          type: 'table',
          payload: {
            value: {
              schema: [
                {
                  key: 'name',
                  label: 'Name',
                },
                {
                  key: 'job',
                  label: 'Job title',
                },
              ],
              rows: [
                {
                  name: 'John Doe',
                  job: 'Plumber',
                },
                {
                  name: 'Jane Doe',
                  job: 'Designer',
                },
              ],
            },
          },
        },
        json: true,
      })
      .then(result => {
        console.log(result);
      });
    
    // Response
    "OK"
    

    This will display:

    Webchat table message

    Payload value parameters:

    Parameter Type Description
    schema Array An array of { key, label } couples. key is a String linking a column and its rows. label is the title of the column that will be displayed in the webchat.
    rows Array An array of { <KEY>: <VALUE> } objects. <KEY> is a String linking to a column key. <VALUE> is the String you want to display as a value in the table.

    Quickreplies

    To display 'quickreplies', send a POST request to the webchat server endpoint (see right pane):

    curl -X POST 'https://webchat.botfuel.io/bots/<APP_TOKEN>/users/<USER_ID>/conversation/messages' \
    -H 'Content-Type: application/json' \
    -d '{
      "type": "quickreplies",
      "payload": {
        "value": [
          "Hello",
          "World",
          "Cool"
        ]
      }
    }'
    
    const rp = require('request-promise');
    
    rp
      .post({
        method: 'POST',
        uri:
          'https://webchat.botfuel.io/bots/<APP_TOKEN>/users/<USER_ID>/conversation/messages',
        body: {
          type: 'quickreplies',
          payload: {
            value: ['Hello', 'World', 'Cool'],
          },
        },
        json: true,
      })
      .then(result => {
        console.log(result);
      });
    
    // Response
    "OK"
    

    This will display:

    Webchat quickreplies message

    When the user clicks on a quickreply, it will effectively send a text message to the bot as if the user typed it.

    Payload value parameters:

    Parameter Type Description
    value Array Array of Strings representing possible text values for the user to send.

    Actions

    An Action can either be:

    A message of type 'actions' can contain as many Actions as you need. To display 'actions', send a POST request to the webchat server endpoint (see right pane):

    curl -X POST 'https://webchat.botfuel.io/bots/<APP_TOKEN>/users/<USER_ID>/conversation/messages' \
    -H 'Content-Type: application/json' \
    -d '{
      "type": "actions",
      "payload": {
        "value": [
          {
            "type": "link",
            "text": "Botfuel Developer Portal",
            "value": "https://app.botfuel.io"
          },
          {
            "type": "link",
            "text": "Botfuel GitHub",
            "value": "https://github.com/Botfuel"
          },
          {
            "type": "postback",
            "text": "I want something else",
            "value": {
                "customKey": "customValue"
            }
          }
        ]
      }
    }'
    
    const rp = require('request-promise');
    
    rp
      .post({
        method: 'POST',
        uri:
          'https://webchat.botfuel.io/bots/<APP_TOKEN>/users/<USER_ID>/conversation/messages',
        body: {
          type: 'actions',
          payload: {
            value: [
              {
                type: 'link',
                text: 'Botfuel Developer Portal',
                value: 'https://app.botfuel.io',
              },
              {
                type: 'link',
                text: 'Botfuel GitHub',
                value: 'https://github.com/Botfuel',
              },
              {
                type: 'postback',
                text: 'I want something else',
                value: {
                  customKey: 'customValue',
                },
              },
            ],
          },
        },
        json: true,
      })
      .then(result => {
        console.log(result);
      });
    
    // Response
    "OK"
    

    This will display:

    Webchat actions message

    Clicking on a 'link' will open a new tab with value as its URL, while clicking on a 'postback' button will send the value back to your bot endpoint. Following the last example, clicking on the last button will send (see right pane):

    // Clicking on `I want something else` button will send this message to the bot endpoint
    {
      "type": "postback",
      "payload": {
        "text": "I want something else",
        "value": {
          "customKey": "customValue"
        }
      }
    }
    

    Payload value parameters:

    Parameter Type Description
    value Array A array of Action.

    Action parameters:

    Parameter Type Description
    type String
    Possible values: 'link', 'postback'
    A String representing the Action type.
    text String Label of the button if Action is of type 'postback', text of the link if Action is of type 'link'
    value Object/String Object representing a custom payload to send to the bot if Action is of type 'postback', URL of the link if Action is of type 'link'

    User messages

    A user message can either be 'text' or 'postback'.

    Text

    A 'text' message is sent when sending text from the text input or when the user clicks a quickreply. Either of these events will send the following message (see right pane):

    {
      "type": "text",
      "payload": {
        "value": "I would like more information please"
      }
    }
    

    Payload value parameters:

    Parameter Type Description
    value String A string containing the message.

    Postback

    A 'postback' message is sent when clicking an Action button of type 'postback'. It will send back the same payload.value as the Action (see right pane for an example):

    {
      "type": "postback",
      "payload": {
        "value": {
          "customKey": "customValue"
        }
      }
    }
    

    Payload value parameters:

    Parameter Type Description
    value Object A object representing the postback to send to the bot.

    Browser compatibility

    The webchat is compatible with the vast majority of browsers on the market including Internet Explorer 10 and above and adapts to the user screen size.

    Botmeter

    Specifications

    HTTP Request

    POST https://api.botfuel.io/botmeter/

    Query Parameters

    Parameter Default Type Description Required
    bot_version null String Bot version
    Example: '1.0.3'
    Optional
    channel null String Messaging channel
    Example: 'Messenger', 'Webchat'
    Optional
    user_id null String User id Optional
    user null Object User properties
    Example: {name: 'John Doe'}
    Optional
    conversation_id null String Conversation id Optional
    body null String Message body
    'how are you doing dude?'
    Optional
    body_type 'text' String
    Possible values: 'text', 'postback'
    Type of body Optional
    responses [] Array(String) The bot responses Optional
    state_in null String The input state Optional
    state_out null String The output state Optional
    intent null Object Name and score of intent
    Example: {name:'foo', score: 0.9}
    Optional
    tags [] Array(String) Message tags
    Example: ['small-talk', 'greetings']
    Optional

    Examples

    Generic

    You can use Botmeter whatever your implementation, as long as you are able to call the API.

    curl -X POST 'https://api.botfuel.io/botmeter/' \
      -H 'Content-Type: application/json' \
      -H "App-Id: $APP_ID" \
      -H "App-Key: $APP_KEY" \
      -d '{
        "body": "Hello",
        "responses": [
          "Hi !",
          "How are you ?"
        ],
        "bot_version": "0.0.2",
        "timestamp": 1491475013000,
        "body_type": "text",
        "intent": {
          "score": 0.8,
          "name": "Greetings"
        },
        "user": {
          "first_name": "John",
          "last_name": "Doe"
        },
        "state_out": "Root",
        "user_id": "JohnDoe",
        "state_in": "Root",
        "channel": "Webchat"
      }'
    
    # Body will equal 'ok' if logging is successful
    

    We also provide a generic wrapper in Node.js.

    To use it, install botmeter-logger:

    npm install --save botmeter-logger
    
    const BotmeterLogger = require('botmeter-logger');
    
    const genericLogger = new BotmeterLogger({
      appId: 'id',
      appKey: 'key',
    }).generic;
    
    const document = {
      bot_version: '1.0.2',
      timestamp: 1491475013000,
      channel: 'Webchat',
      user_id: 'JohnDoe',
      user: {
        first_name: 'John',
        last_name: 'Doe',
      },
      body: 'Hello',
      body_type: 'text',
      responses: ['Hi !', 'How are you ?'],
      state_in: 'Root',
      state_out: 'Root',
      intent: {
        name: 'Greetings',
        score: 0.8,
      }
    };
    
    genericLogger.indexDocument(document, function(error, body) {
      // Body will equal 'ok' if logging is successful
      ...
    });
    

    Facebook Messenger

    First, install botmeter-logger:

    npm install --save botmeter-logger
    

    Log the message inside the POST request callback made when the bot replies (the user message and bot response(s) must be logged in the same document) (see right pane).

    See our sample bot

    const BotmeterLogger = require('botmeter-logger');
    const request = require('request');
    
    const messengerLogger = new BotmeterLogger({
      appId: '<APP_ID>',
      appKey: '<APP_KEY>',
    }).messenger;
    
    // User message
    const requestBody = 'Hello';
    
    // Bot response
    const responseJson = {
      recipient: {
        id: senderId,
      },
      message: {
        text: 'Hello World',
      },
    };
    
    // POST bot reponse to facebook
    request(
      {
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: process.env.PAGE_ACCESS_TOKEN },
        method: 'POST',
        json: responseJson,
      },
      () => {
        // The user message and bot response(s) must be logged in the same document
        messengerLogger.logDocument(requestBody, responseJson, (e, r) => {
          if (e) {
            console.log('Botmeter error: ', e);
          } else {
            console.log('Botmeter logging: ', r);
          }
        });
      }
    );
    

    Microsoft Bot Builder

    First, install botmeter-logger:

    npm install --save botmeter-logger
    

    We provide a middleware that you can easily plug to Microsoft bot builder (see right pane).

    See our sample bot

    const BotmeterLogger = require('botmeter-logger');
    const builder = require('botbuilder');
    const restify = require('restify');
    
    // Create a server
    const server = restify.createServer();
    server.listen(process.env.PORT || 3978, function() {
      console.log('%s listening to %s', server.name, server.url);
    });
    
    // Instantiate the Bot builder connector and bot
    const connector = new builder.ChatConnector({
      // can be left undefined when testing with emulator
      appId: process.env.MICROSOFT_APP_ID,
      // can be left undefined when testing with emulator
      appPassword: process.env.MICROSOFT_APP_PASSWORD,
    });
    
    const bot = new builder.UniversalBot(connector);
    
    // Instantiate Bot builder logger
    const builderLogger = new BotmeterLogger({
      appId: '<APP_ID>',
      appKey: '<APP_KEY>',
    }).botbuilder;
    
    // Plug it
    server.post('/api/messages', connector.listen());
    
    bot.use(builderLogger);
    
    bot.dialog('/', session => session.send('Hello World'));