Giter Site home page Giter Site logo

node-wit's Introduction

Wit Node.js SDK npm

node-wit is the Node.js SDK for Wit.ai.

Install

In your Node.js project, run:

npm install --save node-wit

Quickstart

Run in your terminal:

node examples/basic.js <WIT_TOKEN>

See examples folder for more examples. Some examples have associated .zip files, do not forget to import those when creating a new app and grab your access token from the Settings section.

Messenger integration example

See examples/messenger.js for a thoroughly documented tutorial.

Overview

The Wit module provides a Wit class with the following methods:

  • runComposerAudio - the Composer integration for voice;
  • runComposer - the Composer integration for other inputs;
  • converse - the Wit converse API;
  • event - the Wit event API;
  • message - the Wit message API;
  • speech - the Wit speech API;
  • dictation - the Wit dictation API;
  • synthesize - the Wit synthesize API.

You can also require a library function to test out your Wit app in the terminal. require('node-wit').interactive

Wit class

The Wit constructor takes the following parameters:

  • accessToken - the access token of your Wit instance;
  • actions - the object of client action definitions for Composer;
  • logger - (optional) the object handling the logging;
  • apiVersion - (optional) the API version to use instead of the recommended one

The logger object should implement the methods debug, info, warn and error. They can receive an arbitrary number of parameters to log. For convenience, we provide a Logger class, taking a log level parameter

Example:

const {Wit, log} = require('node-wit');

const actions = {
  confirm_order(contextMap) {
    return {context_map: {...contextMap, order_confirmation: 'PIZZA42'}};
  },
};

const client = new Wit({
  accessToken: MY_TOKEN,
  actions,
  logger: new log.Logger(log.DEBUG), // optional
});

console.log(client.message('set an alarm tomorrow at 7am'));

.runComposerAudio()

The Composer integration for voice.

Takes the following parameters:

  • sessionId - a unique string identifying the user session
  • contentType - the Content-Type header
  • body - the audio Readable stream
  • contextMap - the context map object

Emits partialTranscription, response and fullTranscription events. Run the provided actions as instructed by the API response, and calls back with the resulting updated context map (unless the action returns stop: true). The Promise returns the final JSON payload of the last API call (POST /converse or POST /event).

See lib/interactive.js for an example.

.runComposer()

The Composer integration for other inputs, including text.

Takes the following parameters:

  • sessionId - a unique string identifying the user session
  • contextMap - the context map object
  • message - the optional user text query

Emits response events. Run the provided actions as instructed by the API response, and calls back with the resulting updated context map (unless the action returns stop: true). The Promise returns the final JSON payload of the last POST /event API call.

See lib/interactive.js for an example.

.converse()

The Wit converse API.

Takes the following parameters:

  • sessionId - a unique string identifying the user session
  • contentType - the Content-Type header
  • body - the audio Readable stream
  • contextMap - the context map object

Emits partialTranscription, fullTranscription, and response events. Runs intermediate actions as instructed by the API.

We recommend to use .runComposerAudio() instead of this raw API.

.event()

The Wit event API.

Takes the following parameters:

  • sessionId - a unique string identifying the user session
  • contextMap - the context map object
  • message - the optional user text query

Emits response events, and run intermediate actions as instructed by the API.

We recommend to use .runComposer() instead of this raw API.

.message()

The Wit message API.

Takes the following parameters:

  • q - the text input you want Wit.ai to extract the information from
  • context - (optional) the Context object
  • n - (optional) the max number of intents and traits to get back

Example:

const client = new Wit({accessToken: 'MY_TOKEN'});
client
  .message('what is the weather in London?', {})
  .then(data => {
    console.log('Yay, got Wit.ai response: ' + JSON.stringify(data));
  })
  .catch(console.error);

See lib/interactive.js for another example integration.

.speech()

The Wit speech API.

Takes the following paramters:

  • contentType - the Content-Type header
  • body - the audio Readable stream
  • context - (optional) the Context object
  • n - (optional) the max number of intents and traits to get back

Emits partialTranscription, partialUnderstanding and fullTranscription events. The Promise returns the final JSON payload.

See lib/interactive.js for an example.

.dictation()

The Wit dictation API.

Takes the following paramters:

  • contentType - the Content-Type header
  • body - the audio Readable stream

Emits partialTranscription, and fullTranscription events. The Promise returns the final JSON payload.

See examples/synthesize-speech.js for an example.

.synthesize()

The Wit synthesize API.

Takes the following paramters (click on link above for more details):

  • q - The query containting text to synthesize
  • voice - The voice name. For voices and styles available, see GET voices.
  • style - (optional) The style to speak in
  • speed - (optional) the speed the text is spoken
  • pitch - (optional) the pitch of the audio
  • gain - (optional) the gain of the audio

The Promise returns the final response, with the body containing the audio stream of the synthesized text.

See examples/synthesize-speech.js for an example.

interactive

Starts an interactive conversation with your Wit app.

Full conversational interactions: Use !converse to send an audio request from the microphone using Composer. Enter any text input to send a text request using Composer.

One-off natural language requests: Use !speech to send an audio request from the microphone. Use !message <your message> to send a text request.

Example:

const {interactive} = require('node-wit');
interactive(client);

See the docs for more information.

Changing the API version

The default (recommended, latest) API version is set in config.js.

On May 13th, 2020, the GET /message API was updated to reflect the new data model: intents, traits and entities are now distinct. You can target a specific version by passing the apiVersion parameter when creating the Wit object.

{
  "text": "hello",
  "intents": [
    {
      "id": "1353535345345",
      "name": "greet",
      "confidence": 0.9753
    }
  ],
  "entities": [],
  "traits": []
}

Running tests

  1. Create a new app in wit.ai web console using tests/wit-ai-basic-app-for-tests.zip
  2. Copy the Server Access Token from app settings
  3. Run WIT_TOKEN=XXX npm test, where XXX is the Server Access Token

License

The license for node-wit can be found in LICENSE file in the root directory of this source tree.

Terms of Use

Our terms of use can be found at https://opensource.facebook.com/legal/terms.

Use of Wit.ai services fall under the terms of use found here: https://wit.ai/terms.

Privacy Policy

Our privacy policy can be found at https://opensource.facebook.com/legal/privacy.

The privacy policy for the Wit.ai service can be found at https://wit.ai/privacy.

node-wit's People

Contributors

alec2435 avatar amowu avatar blandinw avatar chessai avatar chrispanag avatar dependabot[bot] avatar diegorbaquero avatar duffmeister avatar fengyangzhang avatar glavin001 avatar gleuch avatar jedireza avatar jtliao avatar kartikchugh avatar keyvanakbary avatar kidexp avatar laardee avatar marcbachmann avatar oniken avatar patapizza avatar ptab avatar rdbmax avatar stopachka avatar tonywangcn avatar tunilame avatar ush189 avatar vbhaip avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-wit's Issues

conversational actions not being called.

Hello,

I am working through the quick start example and dont seem to be receiving back any bot messages. I have created my story exactly how the example illustrates so think it may be my code setup.

It seems that the only way to receive the next actions is through the command line.

my setup is as the example illustrates:

const actions = {
          say: (sessionId, msg, cb) => {
            console.log(msg);
            cb();
          },
          merge: (context, entities, cb) => {

              console.log('context ', context, entities );

              const loc = firstEntityValue(entities, 'location');
              if(loc) {
                context.loc = loc;
              }
            cb(context);
          },
          error: (sessionId, msg) => {
            console.log('Oops, I don\'t know what to do.');
          }

    };

this.client = new Wit(this.token, actions);
this.client.interactive();

// sending message
 this.client.message( messageStr, ( ) =>{ } );

The code executes with no errors, however I am not receiving a response as illustrated in the example? Am I setting up the code incorrectly? Do I need to change the code to receive the automated bot questions?

Any help would be much appreciated.

Thanks

Having trouble getting the context to send location when integrating with Messenger

Hi!

I'm playing around with Messenger integration and having trouble getting the "loc" context variable to get correctly passed using the "messenger.js" example. It works correctly using the same method in "quickstart.js" on the interactive client.

I've noticed a lot of changes recently, has something changed in messenger.js that would cause the context to get lost?

Thanks!

Error action "Oops, I don't know what to do."

I don't know what is wrong with my action

I am making two api calls, fetchSummonerByName and fetchStats, which return promises. the context is logged in the console correctly, so i know the promises work.

any ideas?

    fetchSummonerByName('na', context.name)
      .then(summonersResult => {
        const summoner = summonersResult[context.name]
        context.summonerLevel = summoner.summonerLevel
        return fetchStats('na', summoner.id)
      })
      .then(statsResult => {
        statsResult.sort(sortByTotalSessionsPlayed)
        context.championName = statsResult[0].id
        context.totalSessionsPlayed = statsResult[0].stats.totalSessionsPlayed
        console.log(context)
        cb(context);
      })
      .catch(err => console.log(err))

Actions from another stories are being executed

I created two stories.

Story 1:
screen shot 2016-04-27 at 2 39 13 am

Story 2:
screen shot 2016-04-27 at 2 39 26 am

Actions:

const actions = {
  say(sessionId, context, message, cb) {
    console.log(message);
    cb();
  },
  merge(sessionId, context, entities, message, cb) {
    const wsName = firstEntityValue(entities, 'workspace');
    if (wsName) {
      context.ws_name = wsName;
    }
    cb(context);
  },
  error(sessionId, context, error) {
    console.log(error.message);
  },
  ['fetch-ws-status'](sessionId, context, cb) {
    if(context.ws_name=='ws1'){
      context.colour = 'green';
    }else{
      context.colour = 'red';
    }
    cb(context);
  },
  ['start-ws'](sessionId,context,cb){
    console.log('invoke the url to start ws'+context.ws_name);
    cb(context);
 }
};

When I start the client and type "how is ws4?", I see that the action from the other story is also getting executed. Then it seems like it is invoking the two actions repeatedly.

screen shot 2016-04-27 at 2 30 25 am

Am I doing something wrong ?

Tests and CI

I think is really important to have test and CI

Error when I try npm install node-wit

I try npm install node-wit when I 'm connected to various networks but I have the same error:

WI0035947P:node-wit vcasari$ npm install node-wit
npm ERR! Darwin 15.0.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "node-wit"
npm ERR! node v5.6.0
npm ERR! npm v3.6.0
npm ERR! code E401

npm ERR! Registry returned 401 for GET on http://registry.npmjs.org/node-wit
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:
npm ERR! /Users/vcasari/Documents/projects_node/node-wit/npm-debug.log

Thanks a lot,
Vanni

Very odd results when passing a session id starting with '/#'

Very odd results when passing a session id starting with '/#'. I'm using socket.io to create a bot on top of node-wit. Sadly when I pass the socket.id (which starts with /#) to the wit instance as as sessionId I get crazy results coming back.

When I run the quickstart.js, I have got this error.

string_decoder.js:68
if (buf.length === 0)
^

TypeError: Cannot read property 'length' of null
at StringDecoder.write (string_decoder.js:68:10)
at Interface._normalWrite (readline.js:335:30)
at Interface.write (readline.js:326:49)
at prompt (F:\github\node-wit\lib\wit.js:143:10)
at Wit.interactive (F:\github\node-wit\lib\wit.js:145:5)
at Object. (F:\github\node-wit\examples\quickstart.js:60:8)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)

Entity object is empty

I'm working on integrating node-with with a Slack bot. I pieced together a bit of code from the Quick Start Guide that uses this;

witClient.message('hello', {})
  .then((data) => {
    console.log('Yay, got Wit.ai response: ' + JSON.stringify(data));
  });

Which logs the following;

Yay, got Wit.ai response: {"msg_id":"00000000000","_text":"Hello","entities":{}}

I'm not sure why the entities object is blank. It should be registering as a "greeting" intent, which I set up in Wit.ai. Any ideas on what I could check to debug this?

Support different js environments

The problem:

Users could want to run node-wit in different javascript environments, such as the browser, or react-native. This could be ideal for building interactive Bot experiences, where functions are redefined in a repl-like experience.

node-wit has very few dependencies (node-fetch, node-uuid, readline).

We could quite easily make node-wit, have no real dependency on node.

This would involve:

  1. using isomorphic-fetch instead of node-fetch
  2. node-uuid already works isomorphically, so no change needed
  3. for interactive
    -- separate interactive out of wit.js, into interactive.js
    -- require 'readline' there
    -- the new interactive will take as arguments (client, initContext, maxSteps)
    -- if a user wants to run interactive in node, they can do ->
const {Wit, interactive} = require('node-wit');
const client = new Wit(WIT_TOKEN);

interactive(client); // runs readline

This way, if a user requires wit anywhere, they will only get the universal js modules

Finally, we would change the name of this package, to ~wit-js-sdk.

Thoughts?

TypeError from wit.js

I recently implemented a new action for my bot and it is throwing the following error:

Oops! Got an error from Wit: TypeError: Cannot read property 'then' of undefined at /Users/username/Desktop/wit-test/node_modules/node-wit/lib/wit.js:110:40 at process._tickCallback (internal/process/next_tick.js:103:7)

I've done some digging and I'm not sure what the root issue is, here is the code that results in the error:

else if (json.type === 'action') {
     const action = json.action;
     throwIfActionMissing(actions, action);
     return actions[action](request).then((ctx) => {
               const nextContext = ctx || {};
               return this.converse(sessionId, null, nextContext).then(
                    continueRunActions(sessionId, message, nextContext, i - 1)
               );
     });
}`

More structured and testable integration with FB messanger?

I really like Wit.ai and the messenger.js example. Thanks a lot for that. However, since bot engine, Facebook API, and (express) server is all in one file, it's hard to test each feature.

I basically, separate them into three files and make them testable individually: jest, bot and server with a simple payload.

Jest

 npm test

Bot testing

 $WIT_TOKEN=insert_token_here node bot

Server testing

First, run the server

 $WIT_TOKEN=insert_token_here node index

In other shell, fire this command:

 $curl -X POST -H "Content-Type: application/json" -d @__tests__/msg.json http://localhost:8445/webhook

Also, I added a quick button and app.json to quickly deploy the bot server in the Heruko effortlessly.

Are you potentially interested having this change as a PR to a node-wit subdirectory (like examples)? I would be more than happy to clean up the code, send a PR and get your comments.

Please take a look at the preliminary code at https://github.com/hunkim/Wit-Facebook.

Issues in when integrating with FB bot.

When I'm trying to integrate with FB bot, I'm unable to get entities at back-end(node) and heroku throws error as it don't understand new ECMAScript 6 features.

Syntax error in messenger.js Or something I'm doing wrong?

I went through quickstart guide, but I am stuck at when running node examples/messenger.js. It gives me this error:

/home/rizwan/chatbot/examples/messenger.js:16
const bodyParser = require('body-parser');
^^^^^
SyntaxError: Use of const in strict mode.
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

Let me know if there's something I'm missing?

Getting syntax error

Getting the following syntax error when deploying an app

SyntaxError: Unexpected token {

/app/node_modules/node-wit/lib/wit.js:18

microphone

Hi

|t seems the microphone input is missing from the later packages.
Isn't this supposed to be included?

thanks.

firstEntityValue is not defined

Hello guys,

I'm a bit ashamed I can't even reproduce the QuickStart doc.. Anyway when I clone the repo, all I get into the index.js in the root is :

module.exports = { Logger: require('./lib/logger.js').Logger, logLevels: require('./lib/logger.js').logLevels, Wit: require('./lib/wit.js').Wit, }

And not what is written in the QuickStart doc. The code is actually in example/weather.js. So I do paste the merge code where it belongs :

merge: (context, entities, cb) => { //Retrieve the location entity and store it into a context field const loc = firstEntityValue(entities, 'location'); if(loc) { context.loc = loc; } cb(context); },

But I do get the following error in my terminal :
ReferenceError: firstEntityValue is not defined

Any ideas on how i could fix that and make it work ?
Thanks !

*/node_modules/node-wit/lib/wit.js:18

after upgrading to the latest sdk, I get this error

node_modules/node-wit/lib/wit.js:18
const {
^

SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17) ...

Invalid session id

Im trying a basic http post for the converse endpoint but I keep getting the invalid session id error. Documentation on this is very sparse https://wit.ai/docs/http/20160511#post--converse-link , it says "A specific ID of your choosing representing the session your query belongs to". I can't really understand what to do with this, since I guess it's some random number I can generate no?
Where does this get checked?

Thanks in advance for your help! :)

Usage behind a proxy

I don't get the quickstart to work. Could it be because I'm working behind a proxy? How to configure it?

Thank you very much!

warnings about argument lengths, when creating higher-order actions

When developing bots, one may want to decorate their actions with some meta info.

For example --

function decorateActions(actions, cb) {
  /* 
     mapObject, 
     a utility function that maps f(v, k) over an object, 
     and returns a new object
  */
  return mapObject(
    (action, name) => (...args) => {
      cb({name, args});
      return f(...args);
    }
  );
}

The intent here could be to capture which actions run. This could be used for custom logging, or other purposes.

When we run this code, we get a warning --

  [wit] The 'send' action should accept 2 arguments: request and response. Learn more at https://wit.ai/docs/quickstart
  [wit] The 'fetchWeather' action should accept 1 argument: request. Learn more at https://wit.ai/docs/quickstart

To fix this problem, we would have to make the decorateActions function much more explicit, and more tightly coupled with actions


function decorateActions(actions, cb) {
  const withoutSend = {...actions};
  delete withoutSend.send;

  return {
    send(request, response) {
      cb({name: send}, args: [request, response]);
      return actions.send(request, response);
    },
    ...mapObject(
      withoutSend,
      (action, name) => (request) => {
        cb({name, args: [request]});
        return action(request);
      },
    )
  }
}

My current idea, is to just disable this warning. Other thoughts much appreciated

I can't access wit.ai service.

I have inputted correct service token, But I can't access on it.
The response is only "Bad Auth".
It seems node-wit's problem.

[error] [converse] Error: Bad auth, check token/params

Hi, executing
sudo node quickstart.js with my server app token, I have the following error:

[error] [converse[ Error: Bad auth, check token/params
[error] Bad auth, check token/params

What could be the possible error?

Thanks

Show that the bot is typing

Hello,

is there a way to show the dots bubble while executing an action that takes longer. Now it shows it only when I click a postback button.

Best Regards,
Alexander Stoimenov

error executing quickstart.js

hello, I have been trying to run the quickstart.js but always fails with error:
Executing merge action C:\Users\username\node_modules\node-wit\lib\wit.js:161 this.converse( ^ TypeError: Cannot read property 'converse' of undefined at C:\Users\username\node_modules\node-wit\lib\wit.js:161:13 at Object.actions.say.merge (C:\Users\username\quickstart.js:41:5) at null.<anonymous> (C:\Users\username\node_modules\node-wit\lib\wit.js :230:22) at C:\Users\username\node_modules\node-wit\lib\wit.js:32:9 at process._tickCallback (node.js:355:11)

I have installed all the dependencies. Any idea? I am stuck at this point and don't know what to do to solve this issue.

Thanks in advance

Running into trouble while running the quickstart.js

I was following the instructions on the
https://wit.ai/docs/quickstart

When running the quick start and replacing the access token with a fresh Node v4.4.7:

node examples/quickstart.js

I get:

/Applications/MAMP/htdocs/wit/node-wit/examples/quickstart.js:36
    const {sessionId, context, entities} = request;
          ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

ReadMe#message needs fixin

The code snippet is out of date wrt to the API. Should remove the context and read:

client.message('what is the weather in London?', (error, data) => {
  if (error) {
    console.log('Oops! Got an error: ' + error);
  } else {
    console.log('Yay, got Wit.ai response: ' + JSON.stringify(data));
  }
});

Error when I run quickstart.js file

C:\xampp\htdocs\BOT\node-wit-master>node examples/quickstart.js BQFCOQP2JB7HZLX2O4OXW6LRE3YELPQT
C:\xampp\htdocs\BOT\node-wit-master\examples\quickstart.js:36
const {sessionId, context, entities} = request;
^

SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3

Null actions

node examples/weather.js

What's the weather?
[error] No 'null' action found.

deployment fails on heroku

I get following error upon deployment to heroku.

2016-07-18T14:18:06.984747+00:00 heroku[web.1]: State changed from crashed to starting
2016-07-18T14:18:08.283334+00:00 heroku[web.1]: Starting process with command `node index.js`
2016-07-18T14:18:10.527022+00:00 app[web.1]: /app/index.js:220
2016-07-18T14:18:10.527061+00:00 app[web.1]:                     const {text, attachments} = event.message;
2016-07-18T14:18:10.527096+00:00 app[web.1]:     at Module.load (module.js:357:32)
2016-07-18T14:18:10.527096+00:00 app[web.1]:     at Function.Module._load (module.js:314:12)
2016-07-18T14:18:11.566180+00:00 heroku[web.1]: Process exited with status 1
2016-07-18T14:18:11.581860+00:00 heroku[web.1]: State changed from starting to crashed

Windows (only?) Null Buffer Length

Found someone else on SO posting about this so I thought I'd make an issue here. For those working in Windows or deploying to Azure Web Apps, we're all running into a null reference error determining the length of the write buffer here:

string_decoder.js:66
var buflen = buffer.length;

TypeError: Cannot read property 'length' of null
    at StringDecoder.write (string_decoder.js:66:22)
    at Interface._normalWrite (readline.js:319:30)
    at Interface.write (readline.js:310:49)
    at message.converse.makeActionCallback.runActions.interactive.rl.on [as interactive] (D:\R&D\witai\node_modules\node-wit\lib\wit.js:286:13)
    at Object.<anonymous> (\witai\node_modules\node-wit\examples\template.js:29:8)

http://stackoverflow.com/questions/37266010/wit-ai-example-code-error-null-buffer-length

This can be reproduced on a Mac/Linux machine if you install Visual Studio Code and run the debugger with this as your launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/app.js",
            "stopOnEntry": false,
            "args": [],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": null,
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy",
                "--harmony"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "externalConsole": false,
            "sourceMaps": false,
            "outDir": null
        },
        {
            "name": "Attach",
            "type": "node",
            "request": "attach",
            "port": 3000,
            "address": "localhost",
            "restart": false,
            "sourceMaps": false,
            "outDir": null,
            "localRoot": "${workspaceRoot}",
            "remoteRoot": null
        }
    ]
}

For what it's worth this can be fixed by updating to this:

this.rl.on('line', ((line) => {
      const msg = line.trim();
      this.runActions(
        sessionId,
        msg,
        this.context,
        (error, context) => {
          if (error) {
            l.error(error);
          } else {
            this.context = context;
          }
          this.rl.prompt();
          this.rl.write('', {ctrl: true, name: 'e'});
        },
        steps
      );
    }).bind(this));

Just replace the null with an empty string. Seems trivial, I'm not sure why this is happening. NPM version 3.8.1, "node-wit": "^3.3.0", "node": "0.12.6"

The documentation is a mess.

First of all, thanks for the library! Now... the documentation is a mess. Did I miss the announcement of all those major changes? Where were them announced (I am sure it was my fault)

I had everything set up for a launch, and now I have no idea how to adapt my old code (7 days old) with the new version of the library.

When trying to run my new code I get errors like this

[wit] The 'goodbye' action should accept 1 argument: request. Learn more at https://wit.ai/docs/quickstart

The problem is that when I go to that URL and check some examples, I see code like this:

getForecast({context, entities}) {
  return new Promise(function(resolve, reject) {
    var location = firstEntityValue(entities, "location")
    if (location) {
      context.forecast = 'sunny in ' + location; // we should call a weather API here
      delete context.missingLocation;
    } else {
      context.missingLocation = true;
      delete context.forecast;
    }
    return resolve(context);
  });
},

With 2 parameters

Also, where did say, merge, cb, sessionId, went?

I will be more than happy to contribute with docs if that is what's needed. I think the project deserves it.

Thanks again

[Question] Is it required to highlight intent value ?

I'm training the game bot. Currently I've trained him to answer what platforms the game is supported on.
Example questions:
Is the game available on PS4?
Can I play the game on OSX ?
Do you know what platforms Overwatch is available on ?

The bot answers with a list of supported platforms:
The game is available on PC, Xbox One and PS4.

Currently I don't highlight words for the intent list. And in logs I see that he is using "default intent".

The question is should I highlight it ? And if yes what words should be highlighted in the listed questions above ?
Maybe I just structure my entities wrong. If so what in what way should I train the bot to answer this question ?

FB Messenger integration - Generic Template as reponse from wit.ai

Can the response of wit.ai be a generic template?

I haven't figured out if the following is possible or not (yet?). I want to integrate the wit.ai to a fb messenger bot where the whole conversations should be run by wit.ai (via runActions). Some of the responses needs to be instances of the generic template some should be a video reponse. Is this possible?
All the examples I have seen so far is, that the bot can return only strings (weather in XXX is sunny).

Thanks for reading,
Joshy

CB is not a function

        const context = {};
        client.message('what is the weather in London?', context, (error, data) => {
            if (error) {
                console.log('Oops! Got an error: ' + error);
            } else {
                console.log('Yay, got Wit.ai response: ' + JSON.stringify(data));
            }
        });

Produces:

/Users/daniel/Code/opensource/botkit-middleware-witai/node_modules/node-wit/lib/wit.js:32
        cb(null, data);
        ^

TypeError: cb is not a function
    at /Users/daniel/Code/opensource/botkit-middleware-witai/node_modules/node-wit/lib/wit.js:32:9
    at doNTCallback0 (node.js:417:9)
    at process._tickCallback (node.js:346:13)
[nodemon] app crashed - waiting for file changes before starting...

All the other methods work fine. Odd?

no matching user

Error: (#100) No matching user found
2016-07-18T22:20:41.674308+00:00 app[web.1]:     at fetch.then.then.json (/app/services/wit.js:103:23)
2016-07-18T22:20:41.674324+00:00 app[web.1]:     at process._tickCallback (internal/process/next_tick.js:103:7)

quickstart.js error

I am following the Quick Start guide here: https://wit.ai/docs/quickstart
I tried to run the quickstart example

node examples/quickstart.js (i put tried putting my wit token in, or leave it blank)

but I'm getting the same error:

const {sessionId, context, entities} = request;
      ^

SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3

I have already updated to the latest node.js v4.7.7 on my Windows 7 64-bit. What else am I missing?

X-Hub-Signature verification fails

Verifying Facebook Messenger's X-Hub-Signature fails in the messenger example. I fixed this in my own code by replacing the verification function with an example from Facebook's graph-api-webhooks-samples. It uses the express-x-hub library, which makes the code a bit cleaner in my opinion.

Disabling the signature check to allow babel async/await

Hey there,

We use babel/bluebird to allow the use of async/await patterns for promise resolution. Unfortunately this transpiling step changes the method signature for our Wit actions and the app fails. We'd like to retain this ability,

One possible solution is allowing an environment variable to disable the signature check in your validateActions method before the argument length is validated.

if(process.env.DISABLE_WIT_SIGNATURE_CHECK){
logger.warn("Signature checks for your app's actions are disabled. Unless you are performing async/await calls please re-enable");
return actions;
}

Remove harmony-destructuring in node-wit

Currently, we use destructuring in node-wit.

This means that we have to write

node --harmony_destructuring app.js

if a user's version of node is < 6. and

node app.js

Now, if a user creates a package, where he wants to support both versions, he will need to create a script, which will have to detect the node version, and run either node, or node --harmony_destructuring,

Furthermore, we have other problems if we try to require node-wit in browser environment, where destructuring is not supported.

We could do 2 things

  1. Remove destructuring
  2. We could introduce a build process within node-wit, and use all of the es2015 greatness.

I propose we first do 1. , then open an issue with 2.

Example messenger.js and template.js have unexpected token issue

Unable to figure out how to navigate away from these issues. Do not let me run the examples as expected for testing/integration to proceed. Any guidance or help or if this is a real issue, please acknowledge.

Issue with template.js
[ec2-user@ip-122-51-20-10 node-wit]$ node --harmony examples/template.js MYWITTOKEN

/home/ec2-user/node_modules/node-wit/examples/template.js:7
const token = (() => {
^
SyntaxError: Unexpected token )
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:935:3

Issue with messenger.js
[ec2-user@ip-122-51-20-10 node-wit]$ node --harmony examples/messenger.js

/home/ec2-user/node_modules/node-wit/examples/messenger.js:53
const fbMessage = (recipientId, msg, cb) => {
^
SyntaxError: Unexpected token >
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:935:3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.