Code Monkey home page Code Monkey logo

blip-sdk-js's Introduction

blip-sdk-js

Simple BLiP SDK for JavaScript

This is a work in progress

npm version npm downloads Gitter Travis branch Commitizen friendly


Read more about BLiP here

Installing

Node.js

If you are using node.js (or webpack), you should install the blip-sdk package (via npm) to access the BLiP server:

npm install --save blip-sdk lime-transport-websocket

Browser

If you are developing a web application (for browsers) with "pure" JavaScript, it's possible to import the package from node_modules using the <script> tag. In this case, other than the blip-sdk package, it's also necessary to include the dependencies lime-js and lime-transport-websocket:

<script src="./node_modules/lime-js/dist/lime.js" type="text/javascript"></script>
<script src="./node_modules/lime-transport-websocket/dist/WebSocketTransport.js" type="text/javascript"></script>
<script src="./node_modules/blip-sdk/dist/blip-sdk.js" type="text/javascript"></script>

You can also use unpkg to fetch the packages if you are not using npm in development:

<script src="https://unpkg.com/lime-js" type="text/javascript"></script>
<script src="https://unpkg.com/lime-transport-websocket" type="text/javascript"></script>
<script src="https://unpkg.com/blip-sdk" type="text/javascript"></script>

Instantiate the BlipSdk Client

You will need an identifier and an access key to connect a chatbot to BLiP. To get them:

  • Go to Painel BLiP and login;
  • Click Create chatbot;
  • Choose the Create from scratch model option;
  • Go to Settings and click in Connection Information;
  • Get your bot's identifier and access key.

In order to instantiate the client use the ClientBuilder class informing the identifier and access key:

import * as BlipSdk from 'blip-sdk';
import WebSocketTransport from 'lime-transport-websocket'

// Create a client instance passing the identifier and access key of your chatbot
let client = new BlipSdk.ClientBuilder()
    .withIdentifier(IDENTIFIER)
    .withAccessKey(ACCESS_KEY)
    .withTransportFactory(() => new WebSocketTransport())
    .build();

// Connect with the server asynchronously
// Connection will occurr via websocket on the 8081 port
client.connect() // This method returns a 'promise'
    .then(function(session) {
        // Connection success. Now it's possible to send and receive envelopes from the server
        })
    .catch(function(err) { /* Connection failed */ });

Each client instance represents a server connection and can be reused. To close a connection:

client.close()
    .then(function() { /* Disconnection success */ })
    .catch(function(err) { /* Disconnection failed */ });

Receiving

All messages sent to the chatbot are redirected to registered receivers of messages and notifications. You can define filters to specify which envelopes will be handled by each receiver. The following example shows how to add a simple message receiver:

client.addMessageReceiver(true, function(message) {
  // Process received message
});

The next sample shows how to add a notification receiver with a filter for the received event type:

client.addNotificationReceiver("received", function(notification) {
  // Process received notifications
});

It's also possible to use a custom function as a filter:

Example of a message receiver filtering by the originator:

client.addMessageReceiver(message => message.from === "[email protected]", function(message) {
  // Process received message
});

Each registration of a receiver returns a handler that can be used to cancel the registration:

var removeJsonReceiver = client.addMessageReceiver("application/json", handleJson);
// ...
removeJsonReceiver();

Sending

It's possible to send notifications and messages only after the session has been stablished.

The following sample shows how to send a message after the connection has been stablished:

client.connect()
    .then(function(session) {
      // Once connected it's possible to send messages
      var msg = { type: "text/plain", content: "Hello, world", to: "[email protected]" };
      client.sendMessage(msg);
    });

The following sample shows how to send a notification after the connection has been stablished:

client.connect()
    .then(function(session) {
      // Sending a "received" notification
      var notification = { id: "ef16284d-09b2-4d91-8220-74008f3a5788", to: "[email protected]", event: Lime.NotificationEvent.RECEIVED };
      client.sendNotification(notification);
    });

Contributing

For information on how to contribute to this package, please refer to our Contribution guidelines.

blip-sdk-js's People

Contributors

alacerdah avatar andrebires avatar andreminelli avatar brenoqueiroz avatar brunocamarda avatar ceifa avatar dependabot[bot] avatar helbertreguete avatar henriquetorquato avatar jujucasseb avatar liviaalmeida avatar nicolasamaduro avatar rafael-santiago-take avatar ravpacheco avatar samwx avatar victorbalbo 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

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

blip-sdk-js's Issues

the package.json states TypeScript declaraton files are being exported

Hi folks,

It seems there is a discrepancy in package declaration for NPM and content published to the registry IMO:

https://github.com/takenet/blip-sdk-js/blob/master/package.json#L9

  "files": [
    "dist/blip-sdk.js",
    "dist/types/blip-sdk.d.ts"
  ]

The types on DefinitelyTyped repository are really outdated (and should be phased out), while it seems you've stopped publishing .d.ts here for some reason into NPM repo. This can impact an 'automatic type acquisition feature in TS capable IDEs and user dev-ex,
thx!

Unhandled rejection (<{"state":"failed","reason":{"code":13,...>, no stack trace)

Quando tento rodar o código do index.js, recebo o seguinte erro Unhandled rejection (<{"state":"failed","reason":{"code":13,...>, no stack trace).
Utilizei o comando node index.js para executar o arquivo pelo terminal.

index.js

let BlipSdk = require('blip-sdk');
let WebSocketTransport = require('lime-transport-websocket');

// Put your identifier and access key here
let IDENTIFIER = 'example';
let ACCESS_KEY = 'example';

// Create a client instance passing the identifier and accessKey of your chatbot
let client = new BlipSdk.ClientBuilder()
    .withIdentifier(IDENTIFIER)
    .withAccessKey(ACCESS_KEY)
    //Erro no arrow function
    .withTransportFactory(() => new WebSocketTransport())
    .withTransportFactory(function() { return (new WebSocketTransport())})
    .build();

// Connect with server asynchronously
// Connection will occurr via websocket on 8081 port.
client.connect() // This method return a 'promise'.
    .then(function(session) {
        // Connection success. Now is possible send and receive envelopes from server. */
        console.log('Application started. Press Ctrl + c to stop.')
    })
    .catch(function(err) { /* Connection failed. */ });

Auto recover routine

I've been using this sdk for roughly 4 months now.

Since day one I suffer from situations where the connected instance simply stop receiving or sending messages, without emitting any error ou timeout events.

The customer sends a message from its device and nothing reaches my server. At the same time, I send a message to a customer and despite the sdk seemingly accepting the command, the message does not reach the customer.

At the moment, this problem is being detected only by observation, after several minutes of failing communications. The workaround is a total script restart, manually.

I can't provide solid evidence because, as I said, no error events are emitted whatsover. A blank log file would do no good here.

The main point here is: there has to be a way to realiably know the integrity of the current connected instance. Maybe some internal periodical routine or a more robust event system that allow us to develop our own routines.

Thanks in advance.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

package does not work with Typescript

After include blip-sdk-js i'm getting following error/warning:

Could not find a declaration file for module 'blip-sdk'. 'c:/dev/apps/olharacessivel-com-br/node_modules/blip-sdk/dist/blip-sdk.js' implicitly has an 'any' type. Try npm install @types/blip-sdk if it exists or add a new declaration (.d.ts) file containing declare module 'blip-sdk';ts(7016)

But @types/blip-sdk does not exist.

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.