Git Product home page Git Product logo

chatbase-node's Introduction

Chatbase Node.JS Client

This is not an official Google Product

Use

Install Via NPM

npm install --save @google/chatbase

Require the client in the target application:

var chatbase = require('@google/chatbase');

Set a valid api key, user id, agent-type, and platform on the imported module to automatically create new messages with these fields pre-populated:

var chatbase = require('@google/chatbase')
	.setApiKey(process.env.MY_CHATBASE_KEY) // Your Chatbase API Key
	.setPlatform('PLATFORM-X') // The platform you are interacting with the user over
	.setAsTypeUser(); // The type of message you are sending to chatbase: user (user) or agent (bot)
	
var msg = chatbase.newMessage();
// the following would then be true
assert(msg.api_key === process.env.MY_CHATBASE_KEY);

Or one can set these on each individual message. Note: api key and user id must be provided as arguments to newMessage if one would like to override the factory when it has been previously set.

var chatbase = require('@google/chatbase')
	.setAsTypeAgent()
	.setPlatform('PLATFORM-Y');
	
var msg = chatbase.newMessage('my-api-key', 'my-user-id')
	.setAsTypeUser()
	.setPlatform('PLATFORM-Y');
// the following would then be true
assert(msg.platform === 'PLATFORM-Y');

All fields, with the exception of user id and api key can be set on a message instance. User id and api key must be given as arguments when the message is instantiated.

var chatbase = require('@google/chatbase');
	
var msg = chatbase.newMessage('my-api-key', 'my-user-id')
	.setAsTypeUser() // sets the message as type user
	.setAsTypeAgent() // sets the message as type agent
	// WARNING: setTimestamp() should only be called with a Unix Epoch with MS precision
	.setTimestamp(Date.now().toString()) // Only unix epochs with Millisecond precision
	.setPlatform('PLATFORM-Z') // sets the platform to the given value
	.setMessage('MY MESSAGE') // the message sent by either user or agent
	.setIntent('book-flight') // the intent of the sent message (does not have to be set for agent messages)
	.setAsHandled() // set the message as handled -- this means the bot understood the message sent by the user
	.setAsNotHandled() // set the message as not handled -- this means the opposite of the preceding
	.setVersion('1.0') // the version that the deployed bot is
	.setUserId('user-1234') // a unique string identifying the user which the bot is interacting with
	.setAsFeedback() // sets the message as feedback from the user
	.setAsNotFeedback() // sets the message as a regular message -- this is the default
	.setCustomSessionId('123') // custom sessionId. A unique string used to define the scope of each individual interaction with bot.
	.setMessageId('123'); // the id of the message, this is optional
	.setClientTimeout(5000) // Set the TTL in Milliseconds on requests to the Chatbase API. Default is 5000ms.

Once a message is populated, one can send it to the service and listen on its progress using promises. Note that timestamp is not explicitly set here (although it can be) since it is automatically set on the message to the time of instantiation. Note also that the client type does not need to be explictly set either unless an agent client type is required since the message will automatically default to the user type.

var chatbase = require('@google/chatbase');

chatbase.newMessage('my-api-key')
	.setPlatform('INTERWEBZ')
	.setMessage('CAN I HAZ?')
	.setVersion('1.0')
	.setUserId('unique-user-0')
	.send()
	.then(msg => console.log(msg.getCreateResponse()))
	.catch(err => console.error(err));

Given that a newly created message can be updated this can be achieved via the message interface as well.

var chatbase = require('@google/chatbase');

chatbase.newMessage('my-api-key', 'my-user-id')
	.setPlatform('INTERWEBZ')
	.setMessage('DO NOT WORK')
	.setVersion('1.0');
	.setUserId('unique-user-0')
	.send()
	.then(msg => {
		msg.setIntent('an-intent')
			.setAsFeedback()
			.setAsNotHandled()
			.update()
			.then(msg => console.log(msg.getUpdateResponse()))
			.catch(err => console.error(err));
	})
	.catch(err => console.error(err));

Groups of messages can also be queued and sent together:

var chatbase = require('@google/chatbase');

const set = chatbase.newMessageSet()
	// The following are optional setters which will produce new messages with
	// the corresponding fields already set!
	.setApiKey('abc')
	.setPlatform('chat-space');

// Once can add new messages to the set without storing them locally
set.newMessage()
	.setMessage('test_1')
	.setIntent('book-flight')
	.setUserId('unique-user-0')
	.setClientTimeout(8000)
	// This is a regular message object with all the same setter with the caveat
	// that one cannot send the message individually. All other setter methods
	// still apply though.

// One can also store the reference to the individual message if one would like
// to keep a reference to the individual message instance
const msg = set.newMessage()
	.setMessage('test_2')
	// Pass msg around and profit

// Once the desired messages are queued on the set it can be sent
set.sendMessageSet()
	.then(set => {
		// The API accepted our request!
		console.log(set.getCreateResponse());
	})
	.catch(error => {
		// Something went wrong!
		console.error(error);
	})

chatbase-node's People

Contributors

cristiancavalli avatar frogermcs 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

Watchers

 avatar  avatar  avatar  avatar  avatar

chatbase-node's Issues

Error: One or more required fields were not set on the message

I am trying to implement the chatbase analytics for dialogflow agent using dialogflow google cloud function.

When I send the chatbase message independently using the sample nodejs function. It sends the message to chatbase without any issues and I can able to view the analytics in chatbase dashboard. But copied the same code to dialogflow cloud function it throws the following error.

Error: One or more required fields were not set on the message, please check the documentation on how to set the following message fields: api_key, type, user_id, time_stamp, platform, message at RequiredKeysNotSet

I have set all the required fields but it still throwing an error. Tried for both single and multiple messages. Attached the sample code here.

I am using the following chatbase dependency
@google/chatbase": "^1.1.1"

Issue with using this with react native

Hello,

I was wondering if this is compatible with React Native or if you can point me in the right direction.
Trying to use the lib... I installed it using the npm command but I get the following error when I try to run my app. Every time I include the line:

var chatbase = require('@google/chatbase')

I get this error, so I haven't been able to use the lib

Bundling `index.js`  [development, non-minified]  22.3% (123/1345), failed.
error: bundling failed: UnableToResolveError: Unable to resolve module `events` from `/user/helloproject/node_modules/@google/chatbase/node_modules/got/index.js`: Module does not exist in the module map

Could you help me get some direction on how to address this

newMessage (apiKey=null, userId=null)

/home/ubuntu/www/myproj.com.mm/node_modules/@google/chatbase/lib/MessageFactory.js:118
  newMessage (apiKey=null, userId=null) {
                    ^

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)
    at Object.<anonymous> (/home/ubuntu/www/myproj.com.mm/node_modules/@google/chatbase/lib/ApplicationInterface.js:19:24)
    at Module._compile (module.js:410:26)
    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)
    at Object.<anonymous> (/home/ubuntu/www/myproj.com.mm/node_modules/@google/chatbase/index.js:19:30)
    at Module._compile (module.js:410:26)

Still having error on nodejs v6.7.0

setCustomSessionId is not a function

Hi,

It seems the version published on npm does not have the setCustomSessionId function added to it. Is there an estimate on when the updated version will be published?

Thanks

Is it possible to update the endpoints to use behind an HTTP proxy?

Hi all,

For my current project that I'm working on we are using a reverse proxy using nginx. I found CREATE_ENDPOINT, CREATE_SET_ENDPOINT, and UPDATE_ENDPOINT here in chatbase-node/lib/Transport.js

const CREATE_ENDPOINT = 'https://chatbase-area120.appspot.com/api/message';
const CREATE_SET_ENDPOINT = 'https://chatbase-area120.appspot.com/api/messages';
const UPDATE_ENDPOINT = 'https://chatbase-area120.appspot.com/api/message/update';

We are not allowed to use https connections but have to route our external connections through an outbound gateway as follows

const CREATE_ENDPOINT = 'http://chatbase.outbound-gateway.prd.evilcorp.com.api/message';
const CREATE_SET_ENDPOINT = 'http://chatbase.outbound-gateway.prd.evilcorp.com/api/messages';
const UPDATE_ENDPOINT = 'http://chatbase.outbound-gateway.prd.evilcorp.com/api/message/update';

where nginx then takes care of rerouting the urls.

Therefore, I wonder whether it is possible to do this in a native way without having to manually change these endpoints in our /node_modules. I know that IBM Watson for example has a function .updateServiceUrl, I was wondering if there is a chatbase equivalent to this!

Kind regards,
Jan

how to tell which fields aren't set?

since this library cannot take an object for options, we have to set all the props with functions
is there a way to tell which properties are missing?

afaik all have been set

(node:38429) UnhandledPromiseRejectionWarning: Error: One or more required fields were not set on the message, please check the documentation on how to set the following message fields:
api_key, type, user_id, time_stamp, platform, message
    at MessageStateWrapper.exportCreatePayload (/Users/dc/dev/ten/xbot/server/node_modules/@google/chatbase/lib/MessageSink.js:430:14)
    at /Users/dc/dev/ten/xbot/server/node_modules/@google/chatbase/lib/MessageStateWrapper.js:145:29
    at new Promise (<anonymous>)

to make the library more usable:

  • error messages should be more precise - what fields weren't set?
  • allow to set all options eg msg.setOptions(opts)
  • at least inspect the options that are set? const obj = msg.getOptions()

otherwise it's just tedious trial and error to use this thing.

Session count metrics issue

Hi All,
Recently I had integrated dialogflow bot with chatbase. I am passing both userid and sessionid to chatbase api , both are different values. I could see that the session count metric is not correct in chatbase in the below case,

When a single user(same userid) is having multiple sessions within 15 minutes, only one session is getting counted in session metric dashboard, eventhough the sessionid's are different.

Can someone please help on this issue??

Not usable with NodeJs 8.x

When I track an Set of messages (messageset.sendMessageSet();) on the newest LTS of Node, I get the following error:
Error: One or more required fields were not set on the message, please check the documentation on how to set the following message fields: api_key, type, user_id, time_stamp, platform, message
Switching back to Node 6.x resolves this issue.

Please fix and update the npm package!

Feedback doesn't have any effect

I was exploring the chatbase platform recently. I tried testing with every option with message set. But when I tried sending a message with feed back flag set using setAsFeedback(), it worked fine but I couldn't see any difference in the chatbase analytics. Also no equivalent feature is available in the python API or the Generic REST API, but in the dotnet one. Is this an implementation left for future upgrade? or Am I missing anything?

Feedback attribute: What does it do?

I do not understand the usage of the "feedback" attribute

.setAsFeedback() // sets the message as feedback from the user

Could you share a meaningful use case? I couldn't find anything relevant in the official chatbase documentation either.

How to get reports using API

I got analytics on chatbase. but i want those in API so that i can result them in mt chat question. like

how many users are using from last 7 days.
What are top questions Etc.

Improveable design

Many thanks for the useful library. I just integrated Chatbase with this library. In my eyes there are already some design issues with this library:

  • Neither the Chatbase documentation nor this library really show, which properties are valid for a user- or an agent-message. E.g. does Chatbase concern about the intent-property of an agent message? Would be great if this could be documented more clearly and reflected in the library.

  • setHandled(boolean) would be more handy than two methods setAsNotHandled/setAsHandled. Like this it needs usually an additional condition in the code.

  • What's the idea behind the set.newMessage-method. Why not offering the same interface that set usually has: set.add(new Message());?

  • Are there any Typescript typings?

I'm curious about your thoughts.

setUserId should allow numbers

Some platforms like Telegram use number as user id, so function setUserId should allow numbers.

Currently if I put number in setUserId I will get:

Error: One or more requir
ed fields were not set on the message, please check the documentation on how to set the following message fields:
api_key, type, user_id, time_stamp, platform, message

Support for link tracking

Hi,
The chatebase documentation suggests on Integrate link tracking
Is there any support for that

setUserId is not a function

Trying to use this library and keep getting this error, my code looks like this:

chatbase.newMessage()
      .setAsTypeUser()
      .setPlatform(event.address.channelId)
      .setVersion(version)
      .setTimestamp(new Date(event.timestamp).getTime())
      .setMessage(event.text)
      .setUserId(event.address.user.id || event.user.id)
      .send()
      .then(msg => console.log(msg.getCreateResponse()))
      .catch(err => console.error(err));

Error I get is:

TypeError: chatbase.newMessage(...).setAsTypeUser(...).setPlatform(...).setVersion(...).setTimestamp(...).setMessage(...).setUserId is not a function

Running this on:

  • Node v7.5.0
  • MacOS Sierra v10.12.6

What am I doing wrong?

Thanks

API key is null

Getting this error for the demo:

/Users/jozefw/Desktop/chatbase-codelab-io-2017-master/node_modules/@google/chatbase/lib/MessageFactory.js:118
newMessage (apiKey=null, userId=null) {
^

SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:414:25)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/Users/jozefw/Desktop/chatbase-codelab-io-2017-master/node_modules/@google/chatbase/lib/ApplicationInterface.js:19:24)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)

setMessage is not a function

I have the following code:

var chatbase = require('@google/chatbase')
	.setApiKey(CHATBASE_KEY)
  .setPlatform('Actions');

module.exports = {
   userMessage: function (conv) {
     let userID = conv._userid;
     let conversationID = conv.id;
     let message = conv.query;
     console.log("USER MESSAGE: "+message);
     return chatbase
      .setAsTypeUser()
      .setUserId(userID)
      .setCustomSessionId(conversationID)
      .setMessage(message)
      .send();
   },
   agentMessage: function (message, conv) {
     let conversationID = conv.id;
     console.log("AGENT MESSAGE: "+message);
     return chatbase
      .setAsTypeAgent()
      .setMessage(message)
      .setCustomSessionId(conversationID)
      .send();
   }
 }

However, when I call agentMessage("Hello", conv) my console.log shows the Hello message but I get an error that says:

TypeError: chatbase.setAsTypeAgent(...).setMessage is not a function at agentMessage

Am I doing something wrong?

Can't send group of messages using sendMessageSet

I have the following code:

    this.chatbaseMessageGroup = chatbase
      .newMessageSet()
      .setApiKey(this.chatbaseApiKey)
      .setUserId(this.deviceId)
      .setPlatform(this.platform)
      .setCustomSessionId(this.sessionId)
      .setIntent(this.agent.intent);
    this.chatbaseUserMessage = this.chatbaseMessageGroup
      .newMessage()
      .setAsTypeUser()
      .setMessage(this.agent.query)
      .setAsHandled()
      .setMessageId(this.responseId);

    this.chatbaseChatbotMessage = this.chatbaseMessageGroup
      .newMessage()
      .setAsTypeAgent()
      .setMessageId(this.responseId);
    console.log('--chatbaseMessageGroup', this.chatbaseMessageGroup);

Which produce the following output:

server --chatbaseMessageGroup MessageSet {
server   api_key: 'api-key',
server   user_id: '311adf00-11dd-11e9-8b1a-fbc5613ee3c7',
server   platform: 'web_unly',
server   type: null,
server   version: null,
server   intent: 'GeneralFallback',
server   session_id: '0bd74650-11f8-11e9-99a7-61058335dad0',
server   transport_timeout: 5000,
server   messages: 
server    [ MessageSetMessage {
server        api_key: 'api-key',
server        user_id: '311adf00-11dd-11e9-8b1a-fbc5613ee3c7',
server        type: 'user',
server        time_stamp: '1546809267025',
server        platform: 'web_unly',
server        message: 'AUTO_TALK',
server        intent: 'GeneralFallback',
server        not_handled: false,
server        feedback: false,
server        version: null,
server        message_id: '665ef794-912f-4f45-922c-76475e22e83e',
server        response_time: null,
server        session_id: '0bd74650-11f8-11e9-99a7-61058335dad0',
server        _state: [Object],
server        transport_timeout: 5000 },
server      MessageSetMessage {
server        api_key: 'api-key',
server        user_id: '311adf00-11dd-11e9-8b1a-fbc5613ee3c7',
server        type: 'agent',
server        time_stamp: '1546809267025',
server        platform: 'web_unly',
server        message: null,
server        intent: 'GeneralFallback',
server        not_handled: false,
server        feedback: false,
server        version: null,
server        message_id: '665ef794-912f-4f45-922c-76475e22e83e',
server        response_time: null,
server        session_id: '0bd74650-11f8-11e9-99a7-61058335dad0',
server        _state: [Object],
server        transport_timeout: 5000 } ],
server   _state: MessageLifecycleState { _state: { create: [Object], update: [Object] } } }

Then, I do some dynamic version resolving:

    // figure out version 

    this.chatbaseUserMessage.setVersion(chatbaseVersion);
    this.chatbaseChatbotMessage.setVersion(chatbaseVersion);

    // Send statistics to chatbase
    this.chatbaseMessageGroup.sendMessageSet()
      .then(set => {
        logger.info(set.getCreateResponse());
      })
      .catch(err => {
        logger.error(err);
      });

But I get the following anyway:

server 2019-01-06T21:18:18.782Z [Chatbot] error: One or more required fields were not set on the message, please check the documentation on how to set the following message fields:
server api_key, type, user_id, time_stamp, platform, message

Even if I provide a proper version at the beginning, same result.

It is really not nice to have the same debug message at every try, you should consider improving the debugging DX here and let us know what's wrong exactly. It's a waste of time for everyone who tries to use this tool.

Data sync takes a while

Hi there, why does data sync take 1 to 6 hours to go onto my dashboard? I saw it being mentioned in the docs, but there was no explanation as to why the data sync takes that long. Not that I need a real time analyzing tool, but it's hard on development since every message being sent from my server shows up hours later in the dashboard.

Allow a boolean parameter to `setAsHandled`

It would be nice if setAsHandled could take a boolean (default true for backwards compatibility) that would allow it to behave as setAsNotHandled. This is especially helpful when building messages using message sets since it can avoid storing a reference to the message just to conditionally call this later.

Sending a message twice with the same messageId converage into one?

On my bot, I'm sending a new message received through a middleware once it's being routed.
Later sometimes, i want to tag it as a feedback message, or not_handled.
If i'm sending the message once again, with the same messageId, will Chatbase know to converge them into one message?

If setTimestamp is used, throws an error about missing fields

Error I'm getting:

Error: One or more required fields were not set on the message, please check the documentation on how to set the following message fields:
api_key, type, user_id, time_stamp, platform, message

Code using it:

.setTimestamp(new Date(event.timestamp).getTime())

which generates a timestamp such as 1503956668941

If setTimestamp is not used, it works fine.

Running this on:

  • Node v7.5.0
  • MacOS Sierra v10.12.6

Thanks

set intent for type="Agent"

Hi, The documentation says:

.setIntent('book-flight') // the intent of the sent message (does not have to be set for agent messages)

But in the case of Watson Conversation (IBM tool), the intention its determined by the "Agent" not by the user so..what would happenedd if I do this?:
...
chatbase.setAsTypeAgent();
...
var msg = chatbase.newMessage()
.setMessage(data.output.text.toString())
msg.setIntent('XXX')

Would be broke something? The request was sended

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.