crisp-im / node-crisp-api

:zap: Crisp API Node Wrapper
https://docs.crisp.chat/guides/rest-api/
MIT License
99 stars 38 forks source link

Message listeners don't work for new plugin users #57

Closed jryebread closed 1 year ago

jryebread commented 1 year ago

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;
valeriansaliou commented 1 year ago

This is expected. If you have new subscribers (or removed subscribers), you need to rebind the socket as described here: https://github.com/crisp-im/node-crisp-api#realtime-events

Using: CrispClient.rebindSocket()

jryebread commented 1 year ago

@valeriansaliou I tried calling rebindSocket() in my updatePlugin function:

      await this.crispClient.plugin.rebindSocket();

I also tried await this.crispClient.rebindSocket();

both give an error. can you share an example of how I should be calling it please? the other crispAPI calls work image

valeriansaliou commented 1 year ago

It is this.crispClient.rebindSocket not this.crispClient.plugin.rebindSocket. Check your local crispClient object.

jryebread commented 1 year ago

I tried this.crispClient.rebindSocket as well and it didn't work, said is not a function.

the local crispClient object is the same as new Crisp() it doesn't actually show this as a function

 declare class Crisp {
    auth: {};
    /**
     * @private
     * @type {string}
    */
    private _tier;
    /** @private */
    private _rest;
    /** @private */
    private _rtm;
    /** @private */
    private _useragent;
    /** @private */
    private _emitter;
    /** @private */
    private _socket;
    /** @private */
    private _socketScheduler;
    /** @private */
    private _socketBindHooks;
    /** @private */
    private _boundEvents;
    setRestHost: (host: string) => void;
    setRtmHost: (host: string) => void;
    setTier: (tier: string) => void;
    authenticate: (identifier: string, key: string) => void;
    authenticateTier: (tier: string, identifier: string, key: string) => void;
    head: (resource: string, query: object, body: object) => any;
    get: (resource: string, query: object) => any;
    post: (resource: string, query: object, body: object) => any;
    patch: (resource: string, query: object, body: object) => any;
    put: (resource: string, query: object, body: object) => any;
    delete: (resource: string, query: object, body: object) => any;
    on: (event: string, callback: Function) => void;
    _prepareRestUrl: (paths: any[]) => string;
    _prepareServices: () => void;
    _prepareResources: (serviceInstance: object, resources: any[]) => void;
    _prepareSocket: (fnBindHook: Function) => void;
    _request: (resource: string, method: string, query: object, body: object, resolve: Function, reject: Function) => void;
    _emitAuthenticate: () => void;
}

Also tried setting RTM mode following https://github.com/crisp-im/node-crisp-api/blob/master/examples/events_webhooks.js but even that didn't work? image

jryebread commented 1 year ago

@valeriansaliou any ideas?