Skip to content

Instantly share code, notes, and snippets.

@germanattanasio
Created December 8, 2016 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save germanattanasio/35ada5d1e35d63f19139eb67638b02dc to your computer and use it in GitHub Desktop.
Save germanattanasio/35ada5d1e35d63f19139eb67638b02dc to your computer and use it in GitHub Desktop.
Conversation example that sends messages from the user to the Conversation API
var prompt = require('prompt-sync')();
var ConversationV1 = require('watson-developer-cloud/conversation/v1');
var conversation = new ConversationV1({
username: 'USERNAME',
password: 'PASSWORD',
path: { workspace_id: 'WORKSPACE_ID' },
version_date: '2016-07-11'
});
/**
* Process the conversation response and decides if it needs to
* continue the conversation or not based on the context flags.
*/
function processMessage(err, response) {
if (err) {
console.error(err); // something went wrong
return;
}
var endConversation = false;
// If an intent was detected, log it out to the console.
if (response.intents.length > 0) {
console.log('Detected intent: #' + response.intents[0].intent);
}
// Check for action flags.
if (response.output.action === 'display_time') {
// User asked what time it is, so we output the local system time.
console.log('The current time is ' + new Date().toLocaleTimeString() + '.');
} else if (response.output.action === 'end_conversation') {
// User said goodbye, so we're done.
console.log(response.output.text[0]);
endConversation = true;
} else {
// Display the output from dialog, if any.
console.log(response.output.text[0]);
}
if (!endConversation) {
// Prompt for the new user message
var newMessageFromUser = prompt('Type a message: ');
conversation.message({
input: { text: newMessageFromUser },
context : response.context, // keep the conversation context
}, processMessage)
}
}
// Start conversation. This preloads the action flags in the context with
// false, and then triggers the conversation_start node.
var initialMessage = {
context: {
display_time: false,
end_conversation: false
}
};
// send initial message
conversation.message(initialMessage, processMessage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment