LoginSignup
2
1

More than 5 years have passed since last update.

An example code of the chatbot using the Watson Conversation via Javascript and PHP.

Posted at

I will introduce an example code of the chatbot using the Watson Conversation via Javascript and PHP. You can download codes on Github

Table of Contents

  1. HTML code example.
  2. Javascript code example.
  3. PHP code example.
  4. References
  5. Versions

HTML code example.

index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Chatbot Test APP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="chatbot.js"></script>
  </head>
  <body>
    <main>
      <h1>Chatbot Test APP</h1>
      <div id="messages">
      </div>
      <div>
        <form>
          <input type="text" name="message" value="" placeholder="Enter your message to the bot">
          <button type="submit">Send !</button>
        </form>
      </div>
    </main>
  </body>
</html>

Javascript code example.

chatbot.js
// Backend URL.
var apiUrl = "URL of api.php";
// Variable for the conversation state.
var context = "";

$(function(){
  // Initialization of the chatbot.
  chatbot("");

  // Send a Message, When the form will be submitted.
  $("form").submit(function(e){
    // Prevent the form submission.
    e.preventDefault();
    if($("input").val()){
      // Send the message.
      chatbot($("input").val());
      // Display the message.
      $('#messages').append('<p>'+$("input").val()+'</p>');
    }
  })
})

// A function for sending message to the backend and getting result.
function chatbot(message){
  $.ajax({
    url: apiUrl,
    type: 'post',
    dataType: 'json',
    data: {
      message: message,
      context: context
    },
    timeout:1000
  }).done(function (response) {
    // Check the result.
    console.log(response);
    if(response.error){
      // Failed at getting result.
      // Display a error message.
      $('#messages').append('<p>A communication error occurred.</p>');
    }else{
      // Succeeded at getting result.
      // Clear the input element.
      $("input").val("");
      // Display the message.
      $('#messages').append('<p>'+JSON.parse(response).output.text+'</p>');
      // Upodate the conversation state.
      context = JSON.stringify(JSON.parse(response).context);
    }
  }).fail(function () {
    // Display a error message.
    $('#messages').append('<p>A communication error occurred.</p>');
  });
}

PHP code example.

api.php
<?php
  if(isset($_POST['message'])){
    // Unique identifier of the workspace.
    $workspace_id = 'Your workspace id.';
    // Release date of the API version in YYYY-MM-DD format.
    $release_date = 'Your service released date.';
    // Username of a user for the service credentials.
    $username = 'Your service credential username.';
    // Password of a user for the service credentials.
    $password = 'Your service credential password.';

    // Make a request message for Watson API in json.
    $data['input']['text'] = $_POST['message'];
    if(isset($_POST['context']) && $_POST['context']){
      $data['context'] = json_decode($_POST['context'], JSON_UNESCAPED_UNICODE);
    }
    $data['alternate_intents'] = false;
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);

    // Post the json to the Watson API via cURL.
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'https://watson-api-explorer.mybluemix.net/conversation/api/v1/workspaces/'.$workspace_id.'/message?version='.$release_date);
    curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
    curl_setopt($ch, CURLOPT_POST, true );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    $result = trim( curl_exec( $ch ) );
    curl_close($ch);

    // Responce the result.
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
  }

You can find your workspace informations at below page.
screenshot.png

References

1.Conversation v1 API Explorer
You can test your chatbot using Watson Conversation and see many examples.

Versions

  1. [2017.08.13] First Release
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1