<commit_before>'use strict';

const RiveScript = require('rivescript');
const logger = require('./logger');
const config = require('../config/lib/rivescript');

let brain;
let additionalRivescripts;
let hasSortedReplies = false;

function handleError(error) {
  logger.error('rivescript.handleError', { error });
}

function loadingDone() {
  logger.info('rivescript.brain.loadDirectory success');
  // Loads our saved additionalRivescript into the brain.
  // @see https://github.com/aichaos/rivescript-js/blob/v1.17.2/docs/rivescript.md#bool-stream-string-code-func-onerror
  additionalRivescripts.forEach(item => brain.stream(item, handleError));
  logger.info('rivescript.brain.stream success');
  brain.sortReplies();
  logger.info('rivescript.brain.sortReplies success');
  hasSortedReplies = true;
}

/**
 * Creates a Rivescript bot and loads it with our hardcoded rivescript as well as rivescripts passed
 * in a rivescripts array property.
 *
 * @param {Array} rivescripts
 */
function loadBotWithRivescripts(rivescripts = []) {
  logger.debug('loadBotWithRivescripts');
  additionalRivescripts = rivescripts;
  try {
    if (!brain) {
      brain = new RiveScript({ debug: config.debug, concat: config.concat });
    }
    brain.loadDirectory(config.directory, loadingDone, handleError);
  } catch (err) {
    logger.error('bot.createNewBot', err);
  }
}

/**
 * @param {String} userId
 * @param {String} topicId
 * @param {String} messageText
 * @return {Promise}
 */
function getBotReply(userId, topicId, messageText) {
  if (!brain) {
    return Promise.reject(Error('Bot is not loaded, please retry your message.'));
  }
  // Set the Conversation's current topic in bot.uservars.
  // @see https://github.com/aichaos/rivescript-js/wiki/Asynchronous-Support#user-variable-session-adapters
  brain.setUservars(userId, { topic: topicId });

  return brain.replyAsync(userId, messageText)
    .then((rivescriptReplyText) => {
      if (!hasSortedReplies) {
        throw new Error('Still sorting bot replies, please retry your message.');
      }
      // The inbound message may have triggered a topic change, check bot.uservars to return topic.
      const updatedUservars = brain.getUservars(userId);
      return {
        text: rivescriptReplyText,
        topicId: updatedUservars.topic,
        match: updatedUservars.__initialmatch__, // eslint-disable-line no-underscore-dangle
      };
    });
}

module.exports = {
  loadBotWithRivescripts,
  getBotReply,
};
<commit_msg>Set hasSortedReplies to false when reloading per https://github.com/DoSomething/gambit-conversations/pull/390#pullrequestreview-150584626<commit_after>'use strict';

const RiveScript = require('rivescript');
const logger = require('./logger');
const config = require('../config/lib/rivescript');

let brain;
let additionalRivescripts;
let hasSortedReplies = false;

function handleError(error) {
  logger.error('rivescript.handleError', { error });
}

function loadingDone() {
  logger.info('rivescript.brain.loadDirectory success');
  // Loads our saved additionalRivescript into the brain.
  // @see https://github.com/aichaos/rivescript-js/blob/v1.17.2/docs/rivescript.md#bool-stream-string-code-func-onerror
  additionalRivescripts.forEach(item => brain.stream(item, handleError));
  logger.info('rivescript.brain.stream success');
  brain.sortReplies();
  logger.info('rivescript.brain.sortReplies success');
  hasSortedReplies = true;
}

/**
 * Creates a Rivescript bot and loads it with our hardcoded rivescript as well as rivescripts passed
 * in a rivescripts array property.
 *
 * @param {Array} rivescripts
 */
function loadBotWithRivescripts(rivescripts = []) {
  logger.debug('loadBotWithRivescripts');
  additionalRivescripts = rivescripts;
  hasSortedReplies = false;
  try {
    if (!brain) {
      brain = new RiveScript({ debug: config.debug, concat: config.concat });
    }
    brain.loadDirectory(config.directory, loadingDone, handleError);
  } catch (err) {
    logger.error('bot.createNewBot', err);
  }
}

/**
 * @param {String} userId
 * @param {String} topicId
 * @param {String} messageText
 * @return {Promise}
 */
function getBotReply(userId, topicId, messageText) {
  if (!brain) {
    return Promise.reject(Error('Bot is not loaded, please retry your message.'));
  }
  // Set the Conversation's current topic in bot.uservars.
  // @see https://github.com/aichaos/rivescript-js/wiki/Asynchronous-Support#user-variable-session-adapters
  brain.setUservars(userId, { topic: topicId });

  return brain.replyAsync(userId, messageText)
    .then((rivescriptReplyText) => {
      if (!hasSortedReplies) {
        throw new Error('Still sorting bot replies, please retry your message.');
      }
      // The inbound message may have triggered a topic change, check bot.uservars to return topic.
      const updatedUservars = brain.getUservars(userId);
      return {
        text: rivescriptReplyText,
        topicId: updatedUservars.topic,
        match: updatedUservars.__initialmatch__, // eslint-disable-line no-underscore-dangle
      };
    });
}

module.exports = {
  loadBotWithRivescripts,
  getBotReply,
};

{'fraction_non_alphanumeric': 0.12558411214953272, 'fraction_numerical': 0.003894080996884735, 'mean_word_length': 4.106361829025845, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2834175', 'n_tokens_mistral': 1630, 'n_tokens_neox': 1606, 'n_words': 357}