Giter Club home page Giter Club logo

node-crisp-api's People

Contributors

ajdiaz-gapsi avatar antho1404 avatar baptistejamin avatar bdevore17 avatar creativityjuice avatar dinis07 avatar eliottvincent avatar fega avatar hec10r avatar hikkyu avatar hitkodev avatar jonathanasquier avatar marjoripomarole avatar memcorrupt avatar mrinc avatar p4sca1 avatar pierreleguen avatar rmonnier9 avatar ronaldruckus avatar valeriansaliou 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

node-crisp-api's Issues

Add @types/node-crisp-api

Please add support for typescripts types with @types/node-crisp-api.
Would remove the need for us to add a index.d.ts.

Thank you πŸ™πŸ½

Data validation error when sending message

Hello,

We have an issue when sending picker message in a conversation, could you help us please ?

The request with : CrispClient.website.sendMessageInConversation

Capture d’écran 2023-02-14 aΜ€ 10 55 16

The response :

{ "reason": "error", "message": "invalid_data", "code": 400, "data": { "namespace": "response", "message": "Got response error: data.type should be equal to one of the allowed values, data.type should be equal to one of the allowed values, data.type should be equal to one of the allowed values, data.type should be equal to one of the allowed values, data.content should have required property 'text', data.type should be equal to one of the allowed values, data.type should be equal to one of the allowed values, data.type should be equal to one of the allowed values, data should match some schema in anyOf" } }

Error in readMessages

Hi, I created chatbot and I want to mark messages that are commands (includes specific keywords) as read, to prevent crisp from sending me email notifications when user used that command and bot replied when I am offline.

I have this code in message:send event:

let arr = [];
arr.push(message.fingerprint)
CrispClient.websiteConversations.readMessages(message.website_id, message.session_id, {
from : "operator", 
origin : "chat",
fingerprints: arr

}
)  .then((data) => {
    console.info("Read message.", data);
  })
  .catch((error) => {
    console.error("Failed reading message:", error);
  });

but I am getting this in console

Failed reading message: {
  reason: 'error',
  message: 'invalid_data',
  code: 400,
  data: {
    namespace: 'response',
    message: "Got response error: data should have required property '.origin'"
  }
}

What I did wrong?

Security issues with dependencies normalize-url and ws

Hi there,

There is 2 security issues with your package that impact our API. Could fix these security issues please :

βœ— Regular Expression Denial of Service (ReDoS) [High Severity][https://snyk.io/vuln/SNYK-JS-NORMALIZEURL-1296539] in [email protected]
introduced by [email protected] > [email protected] > [email protected] > [email protected]
This issue was fixed in versions: 6.0.1, 5.3.1, 4.5.1

βœ— Regular Expression Denial of Service (ReDoS) [Medium Severity][https://snyk.io/vuln/SNYK-JS-WS-1296835] in [email protected]
introduced by [email protected] > [email protected] > [email protected] > [email protected]
This issue was fixed in versions: 7.4.6, 6.2.2, 5.2.3

Cheers,

_request method does not reject with an Error object

This method rejects the promise with a custom object:

node-crisp-api/lib/crisp.js

Lines 613 to 625 in 1e6b944

return reject({
reason : "error",
message : reason_message,
code : response.statusCode,
data : {
namespace : "response",
message : (
"Got response error: " + (data_message || reason_message)
)
}
});

Usually rejects are supplied with an Error object, so it includes stack information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject#description

I don't think it is a requirement for promise rejects to use an Error instance, but it can be expected by some frameworks.

Our use case is that we just have async function errors pass up to our error monitoring service Sentry. We fixed it now with a custom wrapper that creates an error object when the promise rejects.

I'm not sure if the information in the rejects object is used somewhere else, haven't dug too deep in the code. If you need this extra info you could consider extending the Error object.

get response times for cases

want to get first response since case was opened and response between when case was opened and when case was resolved

Nuxt 3 support?

Hi,

I'm using Nuxt 3. Adding a library by using require is not working anymore. So I can't use this library.

Do you have any plan to update the library?

Thanks

Not able to call the listPeopleConversations method

Hi,

I'm trying to get all the conversations by the a specific user using the following method

CrispClient.websitePeople.listPeopleConversations(process.env.CRISP_WEB_SITE_ID, people.people_id, 0)

I'm quite sure that the websiteId and peopleId are correct, but actually I'm receiving an exception like this: {"reason":"error","message":"not_found"}. And yes, the peopleId specified have more than one conversation.

Besides that, the method is not on the README.md file of this repository, but it's on the source code as I already checked.

Am I doing something wrong? Thanks in advance.

Event not triggering - session:request:initiated

  • Problem: 'session:request:initiated' is not triggered

  • Way to reproduce: Start a conversation using the chat widget, the event is not triggered.

This is the code I'm using:

'use strict'

const TOKEN = {
    identifier: '<my-identifier>',
    key: '<my-key>'
}

let Crisp = require('node-crisp-api')

let CrispClient = new Crisp()

console.info('Authenticating...')

CrispClient.authenticate(TOKEN.identifier, TOKEN.key)

console.info('Listening for events...')

CrispClient.on('session:request:initiated', function (message) {
    console.info("Got 'session:request:initiated' event:", message)
})

console.info('Now listening.')

No proxy support

In my network, I have to use an HTTP proxy to connect to Internet. But I didn't found any proxy option in this module.

Is there anyway to add proxy support?

How to use Bucket for uploading image via API

Hello again!
I want to upload an image with Bucket. In this way, I used crispClient.bucket.generateBucketURL(data). But it returns me 403 - not_allowed error.
I tried this code:

var data = {
    namespace: "upload",
    from: "plugin",
    identifier: crispConfig.plugin.identifier,
    id: "bal2",
    file: {
      name: input.file.name,
      type: input.file.type
    }
};

crispClient.bucket.generateBucketURL(data)

I used my plugin identifier and key for this code.
Also, can you help me how can I upload a photo after generating the bucket URL?

Thanks a lot

Does Not Work With Yarn 3

I get this error when attempting to run with Yarn 3 & a NX monorepo.

Target project does not exist: npm:fbemitter@https://github.com/crisp-dev/emitter.git#commit=695f60594bdca0c876e5c232de57702ab3151b6f

Error: restricted_route_tier

Hi I'm trying to setup the onboarding flow for when a user subscribes their website to my new plugin.

  async updatePluginForWebsite(websiteId, token, botName, botId, live, apiKey) {
    // if (!this.websites[websiteId]) {
    //   console.error("Website does not exist! Retry with a valid websiteId.");
    //   return;
    // }
  
    console.log("UPDATING VALUE")

    if (!live) {
      console.log('unsubbing!')
      await this.crispClient.plugin.unsubscribePluginFromWebsite(websiteId, this._pluginId)
      return;
    }
  
    try {
      // Subscribe the user 
      await this.crispClient.plugin.subscribeWebsiteToPlugin(websiteId, this._pluginId);
      console.log("Subbed website to plugin!")
      await this.crispClient.plugin.updateSubscriptionSettings(
        websiteId,
        this.pluginId,
        { botId: botId, botName: botName, apiKey: apiKey }
      );
  
      this.websites[websiteId] = { botName: botName, botId: botId, apiKey: apiKey };
  
      console.log(
        `Successfully updated plugin config for website ID: ${websiteId}`
      );
    } catch (error) {
      console.error(`Failed to update plugin config for website ID: ${websiteId}. Error: ${error.message}`);
      throw error;
    }
  }


I created a new crisp app account to test out the production flow (my plugin is "activated" but set to private) when I click the install link and it calls the API "subscribeWebsiteToPlugin" I get this error:

Failed to update plugin config for website ID: bc20aeec-6395-48fc-aaf2-5623af9eab5eb. Error: restricted_route_tier

What does this error mean? I am authenticating the crispClient above with my prod token id and key and calling setTier with val "plugin"

// eg. this.crispClient.authenticateTier("7c3ef21c-xxx-5605c346f73e", "cc29e1a5086e428fcc6a6xxx7a66d82808e65c5cce006fbf2191ceea80a0a");
this.crispClient.setTier("user")

How to pass URI parameters to endpoint?

HI! I would like to pass some URI parameters for example for this https://docs.crisp.chat/references/rest-api/v1/#list-helpdesk-locale-articles endpoint, but as I can see in code source here https://github.com/crisp-im/node-crisp-api/blob/07b063fb0f40ba3eea21a194bce2cd848385f96b/lib/resources/WebsiteHelpdesk.js#L185C32-L185C32 there are no way to pass URI params.

Any ways?

upd:
Also it would be nice to have an opportunity:

  1. To select fields in response
  2. To get total count of articles or pages in response to paginate them in easy way

Add a function in order to get all messages since a timestamp

Hi,

It could be great to have a function in order to get all messages since a date (or in a range)
It could be a parameter in getList function.

My use case would be to have a scheduled program which gets all messages since the last launch.
I would get a response containing an array of messages such as

[
{"website_id":"...c3","type":"text","from":"operator","origin":"chat","content":"The message","fingerprint":-333,"user":{"nickname":"My nickename","user_id":"....C4"},"timestamp":1487956507997,"stamped":true,"session_id":"session_e690....a0"}
]

How to upload file via HTTP PUT w/?

Hello again to the Crisp team!
In the last week, I tried to use the upload feature. I could generate the signed URL, but my main problem is that I can't upload my file via HTTP PUT w/.
I also tried to upload my file with Postman. I got 200 OK response, but nothing happened and my file didn't get uploaded.

Here is a screenshot of what I do in the Postman:
image

I double-checked that the name and type of my file are the same as the name and type that I used for generating the signed URL.
I think I did a mistake in setting parameters. Could you please help me?
Thanks a lot!

Event not triggering: session:request:initiated

I am working on an integration and session:request:initiated is not triggering when a new chat is started. I saw it was brought up in issue: #17 but no resolution. Other events such as message:send are working for me.

Steps done to troubleshoot:

  • Incognito window to start a new chat
  • Cleared out all crisp cookies and started a new chat
  • Looked at source and session:request:initiated is included in DEFAULT_RTM_EVENTS

Code example:

const Crisp = require('node-crisp-api')

const TOKEN_KEY = <'TOKEN'>
const TOKEN_IDENTIFIER = <'TOKEN'>

const CrispClient = new Crisp()

console.info('Authenticating...')

CrispClient.authenticateTier("plugin", TOKEN_IDENTIFIER, TOKEN_KEY);

console.info('Listening for events...')

CrispClient.on('session:request:initiated', (message) => {
  console.log("session started", message);
})

Message listeners don't work for new plugin users

Hi, having an issue where new subscribers to my plugin, the listener isn't working for them,

this.crispClient.on("message:send", async (event) => {

Only listens for plugins already registered and I can't figure out why?

What can I do to fix this in my code? How can I unsubscribe and reset the listener when a new user subscribes to the plugin? :



const Crisp = require("crisp-api");
const fetch = require('node-fetch');

class PongPlugin {
 constructor(pluginUrn, crispAPIIdentifier, crispAPIKey) {
   this.crispClient = new Crisp();
   this._initPlugin();
 }
 
 async getSubSettings(websiteId) {
   try {
     const response = await this.crispClient.plugin.getSubscriptionSettings(websiteId, this.pluginId);
 
     const settings = response.settings;
     console.log(settings);
 
     if (!settings.botId) {
       console.error("BotId is missing in the settings.");
       return;
     }
     return { botId: settings.botId, botName: settings.botName, live: settings.live };
   } catch (error) {
     console.error(`Failed to get subscription settings for website ID: ${websiteId}. Error: ${error.message}`);
   }
 }

// This is called when a new user subscribed to a plugin
 async updatePluginForWebsite(websiteId, token, botName, botId, live) {
 
   console.log("UPDATING VALUE")

   if (!live) {
     console.log('unsubbing!')
     await this.crispClient.plugin.updateSubscriptionSettings(
       websiteId,
       this.pluginId,
       { botId: botId, botName: botName, live: live}
     );
   
     console.log(
       `Successfully unlived plugin config for website ID: ${websiteId}`
     );

     return;
   }
   
   //subscribe
   try {
     await this.crispClient.plugin.updateSubscriptionSettings(
       websiteId,
       this.pluginId,
       { botId: botId, botName: botName, live: live}
     );
     console.log(
       `Successfully updated plugin config for website ID: ${websiteId}`
     );
     

   } catch (error) {
     console.error(`Failed to update plugin config for website ID: ${websiteId}. Error: ${error.message}`);
     throw error;
   }
 }

 _initPlugin() {
   this.crispClient.authenticateTier(
     "plugin", this._apiIdentifier, this._apiKey
   );
   this._events();
 }

 _events() {
   const self = this;

   this.crispClient.on("message:received", (event) => {
     console.log("Got \"message:received\" event:", event);
   });

   this.crispClient.on("message:send", async (event) => {
     console.log("HANDLING EVENT MESSAGE")

     const userMessage = event.content;
     // fetch botName and botID for particular website
     const result = await this.getSubSettings(event.website_id)
     console.log(result)
     const botName = result.botName
     const botId = result.botId
     const live = result.live

     console.log("live")
     
     if (!live) {
       return;
     }
     
     ...
}

module.exports = PongPlugin;


Request: Provide typescript typings

Would be great if this API could provide TypeScript typings.
For maintainability and developer confidence, a rewrite in TypeScript might be a good choice.

absenece of people_Id on conversation.

Hello,

I use the getConversation from the website api, I am noticing the absence of the people_Id , according to the docs this field should be returned :

bug

Bug: Error 404 not subscribed when getting conversations

I'm trying to create a plugin for the company I work for. I have setup the plugin, added the right permissions, got it approved and added it to our website.
When I try to get some conversations by search it always throws the following error:

{
  reason: 'error',
  message: 'not_subscribed',
  code: 404,
  data: {
    namespace: 'response',
    message: 'Got response error: not_subscribed'
  }
}

I have tried using the CrispClient.websiteConversations.getList endpoint as well, it gave me the same error.
This behavior is most likely a bug as the request works fine when I send a raw GET request to the endpoint.

Below I have some example code of how I'm accessing the API.

 const CrispClient = new Crisp();
 CrispClient.setTier("plugin");
 CrispClient.authenticate(identifier, key);

try {
    const res = await CrispClient.websiteConversations.findWithSearch(websiteId, page, {
        filterNotResolved: 1
    });
} catch(e) {
    console.error(e);
}

Is there something I'm doing wrong or is this a bug?

Cannot read properties of undefined (reading '_emitter') when using HTTP WebHooks

Description

When using the Crisp library with the RTM_MODES.WebHooks mode, the following error is thrown:

TypeError: Cannot read properties of undefined (reading '_emitter') at \node_modules\crisp-api\lib\crisp.js:834:31

This error occurs in the _connectLoopback method of the crisp-api library, which is called by the _prepareBroker method. The problem appears to be that the this reference is not properly bound to the Crisp instance, which causes the _emitter property to be undefined.

Steps to Reproduce:

  1. Initialize a Crisp instance with the RTM_MODES.WebHooks mode.
  2. Call the on method to bind an event listener.
  3. Wait for the error to occur.

Expected Result:

No errors should occur, and the event listener should be properly bound to the Crisp instance.

Actual Result:

The error cannot read properties of undefined (reading '_emitter') is thrown, and the event listener is not properly bound to the Crisp instance.

Potential Solution:

It appears that adding the following line of code var self = this; to the _connectLoopback method in the crisp-api library could fix the problem:

_connectLoopback : function() {
    var self = this;

    return Promise.resolve()
      .then(function() {
        // Assign emitter to loopback
        self._loopback = self._emitter;

        // Unstack broker bind hooks immediately
        self._unstackBrokerBindHooks(self._loopback);

        return Promise.resolve();
      });
  },

This would create a local variable self that references the current Crisp instance and can be used to access its properties and methods.

Version Information:

crisp-api version: 7.4.1
Node.js version: v16.19.0
Operating System: Windows 10

Additional Information:

**I'm not entirely certain that this is a proper solution, and there may be other underlying issues causing the error. Maybe it is the way i implemented the crisp-api into my service. It's also possible that adding the var self = this; line may have unintended side effects. But other functions are using the same line. **

I tried to followed these instructions. I would loved to just use this example, but i did not want to mix the express code with raw http server code.

NextJS Error

Hello,

I hope you are well. I was trying to connect crisp-api to my NextJS project.

However, I got several errors including the fact that it could not find the "dns" package. So I installed it

Here is the code (quite messy but just for testing)

/* Location: lib/c.js */

var Crisp = require("crisp-api");

var CrispClient = new Crisp();

export default CrispClient;
/* Location: components/Crisp/crisp.js */

import { CrispClient } from "../../lib/c.js";

export default function RunCrisp() {
  return (
    <div>
      {test}
    </div>
  );
}

export async function getStaticProps() {
  const identifier = "XXX-XXX-XXXX-XXX";
  const key =
    "XXX-XXX-XXXX-XXX";

  CrispClient.authenticateTier("plugin", identifier, key);

  var test = await CrispClient.website
    .listConversations("XXX-XXX-XXXX-XXX", 1)
    .then(function (conversations) {
      console.log("Listed conversations:", conversations);
    })
    .catch(function (error) {
      console.error("Error listing conversations:", error);
    });

  return {
    props: {
      test,
    },
  };
}
/* Location: pages/testcrisp.js */

import React from "react";
import RunCrisp from "../components/Crisp/crisp.js";

export default function TestCrisp() {
  return (
    <div>
      <RunCrisp />
    </div>
  );
}

And here is the error I have:

Screen Shot 2022-12-20 at 18 29 37

I try to do npm i dns but I just get another error saying that dgram is missing. What I see is that this package is deprecated.

Do you know what can I do to fix this ? Seems that some people using mongo-db package have the same issue.

8.0.1 : Cannot find name 'WebSockets'. Did you mean 'WebSocket'?

Whne updating to 8.0.1 :

$ tsc --version && tsc --noEmit
Version 4.6.4
../../node_modules/crisp-api/types/crisp.d.ts:114:325 - error TS2552: Cannot find name 'WebSockets'. Did you mean 'WebSocket'?

114     export { RTM_MODES, AVAILABLE_RTM_MODES, DEFAULT_REQUEST_TIMEOUT, DEFAULT_SOCKET_TIMEOUT, DEFAULT_SOCKET_RECONNECT_DELAY, DEFAULT_SOCKET_RECONNECT_DELAY_MAX, DEFAULT_SOCKET_RECONNECT_FACTOR, DEFAULT_BROKER_SCHEDULE, DEFAULT_EVENT_REBIND_INTERVAL_MIN, DEFAULT_USERAGENT_PREFIX, DEFAULT_REST_HOST, DEFAULT_REST_BASE_PATH, WebSockets as DEFAULT_RTM_MODE, DEFAULT_RTM_EVENTS, Crisp };
                                                                                                                                                                                                                                                                                                                                        ~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:16222:13
    16222 declare var WebSocket: {
                      ~~~~~~~~~
    'WebSocket' is declared here.


Critical issue with socket-io

Hello,

Our NPM audit say this in the current version of the SDK.

Screenshot 2022-12-08 at 12 00 44

After seeing the advisories [https://www.npmjs.com/advisories/1085044], it seems pretty serious, npm suggests to install the crisp-api >=5.2.0 to solve this issue but we don't want to downgrade either.

Is there's something we can do ?
Thanks.

Updating critical vulnerability dependency

When installing crisp-api (7.4.2), npm reported three critical vulnerabilities, like so:

# npm audit report

socket.io-parser  4.0.4 - 4.2.2
Severity: critical
Insufficient validation when decoding a Socket.IO packet - https://github.com/advisories/GHSA-qm95-pgcg-qqfq
Insufficient validation when decoding a Socket.IO packet - https://github.com/advisories/GHSA-cqmj-92xf-r6r9
fix available via `npm audit fix --force`
Will install [email protected], which is a breaking change
node_modules/crisp-api/node_modules/socket.io-parser
  socket.io-client  1.0.0-pre - 1.0.1 || 4.3.0 - 4.4.1
  Depends on vulnerable versions of socket.io-parser
  node_modules/crisp-api/node_modules/socket.io-client
    crisp-api  >=5.2.0
    Depends on vulnerable versions of socket.io-client
    node_modules/crisp-api

3 critical severity vulnerabilities

It would be great if you could upgrade the dependencies πŸ™‚

getMessagesInConversation is returning "route does not exist"

Hi there!

I'm not sure if I'm doing something wrong, but trying to access the messages in a conversation is returning a "route not found error."

My Code:

const messages = await CrispClient.website.getMessagesInConversation(websiteID, sessionID, timestampbefore);

Error:

{
  reason: 'error',
  message: 'not_found',
  code: 404,
  data: {
    namespace: 'response',
    message: 'Got response error: the route does not exist'
  }
}

I saw this: #8 but I'm not sure if this is an error on my part or something is wrong with the library. All of my website and session ids are correct. Including the timestampbefore.

issue with filterDateStart and filterDateEnd

the API list conversations with search is not reachebal from my code when using filter by date. The issue is related to time value when i omit it and work whith just date it works

Unable to create Crisp client

new Crisp() throw an error: results in MODULE_NOT_FOUND Error: 'Cannot find module './resources/BucketURL'

Version 7.3.0

{
    "stack": "Error: Cannot find module './resources/BucketURL'\nRequire stack:\n- /Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js\n- /Users/eugenekim/Projects/crisp-writer/backend/node_modules/serverless-offline/src/lambda/handler-runner/in-process-runner/aws-lambda-ric/UserFunction.js\n    at ono3 (/Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js:289:24)\n    at ono3 (/Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js:339:25)\n    at handler (/Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js:28371:43)\n    at InProcessRunner.run (file:///Users/eugenekim/Projects/crisp-writer/backend/node_modules/serverless-offline/src/lambda/handler-runner/in-process-runner/InProcessRunner.js:87:20)\n    at async MessagePort.<anonymous> (file:///Users/eugenekim/Projects/crisp-writer/backend/node_modules/serverless-offline/src/lambda/handler-runner/worker-thread-runner/workerThreadHelper.js:24:14)\n\nError: Cannot find module './resources/BucketURL'\nRequire stack:\n- /Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js\n- /Users/eugenekim/Projects/crisp-writer/backend/node_modules/serverless-offline/src/lambda/handler-runner/in-process-runner/aws-lambda-ric/UserFunction.js\n    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)\n    at Function.Module._load (internal/modules/cjs/loader.js:746:27)\n    at Module.require (internal/modules/cjs/loader.js:974:19)\n    at require (internal/modules/cjs/helpers.js:101:18)\n    at Crisp2._prepareResources (/Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js:15335:37)\n    at Crisp2._prepareServices (/Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js:15318:16)\n    at new Crisp2 (/Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js:14965:12)\n    at handler (/Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js:28341:25)\n    at InProcessRunner.run (file:///Users/eugenekim/Projects/crisp-writer/backend/node_modules/serverless-offline/src/lambda/handler-runner/in-process-runner/InProcessRunner.js:87:20)\n    at async MessagePort.<anonymous> (file:///Users/eugenekim/Projects/crisp-writer/backend/node_modules/serverless-offline/src/lambda/handler-runner/worker-thread-runner/workerThreadHelper.js:24:14)",
    "message": "Cannot find module './resources/BucketURL'\nRequire stack:\n- /Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js\n- /Users/eugenekim/Projects/crisp-writer/backend/node_modules/serverless-offline/src/lambda/handler-runner/in-process-runner/aws-lambda-ric/UserFunction.js",
    "code": "MODULE_NOT_FOUND",
    "requireStack": [
        "/Users/eugenekim/Projects/crisp-writer/backend/.esbuild/.build/src/functions/pluginAction.js",
        "/Users/eugenekim/Projects/crisp-writer/backend/node_modules/serverless-offline/src/lambda/handler-runner/in-process-runner/aws-lambda-ric/UserFunction.js"
    ],
}

Node crashes if response is not JSON

I am using v1.7.1 and occasionally I see the below error -


SyntaxError: Unexpected token < in JSON at position 0
at Object.parse (native)
at Request._callback (/home/ec2-user/repo/node_modules/node-crisp-api/lib/crisp.js:354:25)


Which can happen when any request returns an error or statusCode >= 400 without a json response.
As of posting the line number is 351 at file https://github.com/crisp-im/node-crisp-api/blob/master/lib/crisp.js

Possible fix - The JSON.parse(body) should be within a try-catch block.

PS: I understand the latest version is 1.8.1, but when I check the latest code, this issue is not addressed.

rebindSocket function not available

#57 (comment)

Please see above thread,

It is not clear how to call rebindSocket for when new users subscribe to the plugin (to refresh the "on" listeners) I got a function not found error when I tried to call rebindSocket? Why is that?

I couldn't find rebindSocket documented anywhere in the API docs.

This is my code for when a new user subscribes to the plugin:

  async updatePluginForWebsite(websiteId, token, botName, botId, live) {
  
    console.log("UPDATING VALUE")
  
    if (!live) {
      console.log('unsubbing!')
      await this.crispClient.plugin.updateSubscriptionSettings(
        websiteId,
        this.pluginId,
        { botId: botId, botName: botName, live: live}
      );
      this.reinitializeClient();
      console.log(
        `Successfully unlived plugin config for website ID: ${websiteId}`
      );
  
      return;
    }

    //subscribe
    try {
      await this.crispClient.plugin.updateSubscriptionSettings(
        websiteId,
        this.pluginId,
        { botId: botId, botName: botName, live: live}
      );
      console.log(
        `Successfully updated plugin config for website ID: ${websiteId}`
      );
      this.reinitializeClient();
  
    } catch (error) {
      console.error(`Failed to update plugin config for website ID: ${websiteId}. Error: ${error.message}`);
      throw error;
    }
  }

  _initPlugin() {
    this.crispClient.authenticateTier(
      "plugin", this._apiIdentifier, this._apiKey
    );
    this._events();
  }

  reinitializeClient() {
    // Reinitialize the Crisp client

    this.crispClient.rebindSocket(); --- function not found error
   }

Thanks In advance

How to get "identifier" and "key" for using some methods in "user" tier

Hello to the Crisp team!
I have a problem with the Crisp REST API. When I do https://api.crisp.chat/v1/website POST request in the user tier, it responds to me with 401 Unauthorized code.
I know it occurs because I use identifier and key that generated for the plugin tier. But, how can I get identifier and key for user tier?

Regards

Helpdesk -> List Helpdesk Locale Articles. Parameter order_visits by default (with 0 value) doesn't work correctly

Hello! I am trying to retrieve articles without the order_visits parameter or with order_visits=0. However, I am receiving unsorted records. The required records appear at the beginning of the list but are not sorted among themselves. For example, initially, a record with order=9, then order=2, then order=6, and so on.

My request:
https://api.crisp.chat/v1/website/:website_id/helpdesk/locale/:locale/articles/:page_number?order_visits=0

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.