<commit_before>'use strict';

const request = require('request-promise');
const session = require('./session.js');
const witAi = require('./wit-ai');

function sendGenericMessage(recipientId) {
  const messageData = {
    attachment: {
      type: 'template',
      payload: {
        template_type: 'generic',
        elements: [{
          title: 'Hi I\'m a bot on serverless 1.0! Do you like me?',
          buttons: [{
            type: 'postback',
            title: 'Yes',
            payload: 'like'
          }, {
            type: 'postback',
            title: 'No',
            payload: 'dislike'
          }]
        }]
      }
    }
  };

  return request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: process.env.FACEBOOK_BOT_PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: {
      recipient: { id: recipientId },
      message: messageData,
    }
  });
}

/**
 * Sends text message to recipient
 * @param recipientId
 * @param result
 */
function sendTextMessage(recipientId, result) {
  const message = { text: result.text };

  if (result.quickreplies) {
    Object.assign(message, {
      quick_replies: result.quickreplies.map(x => ({ title: x, content_type: 'text', payload: 'empty' }))
    });
  }

  return request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: process.env.FACEBOOK_BOT_PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: {
      recipient: { id: recipientId },
      message
    }
  });
}

/**
 * Handles postback message
 * @param event
 */
function receivePostback(event) {
  if (event.postback.payload === 'like') {
    return sendTextMessage(event.sender.id, '^_^ I\'m very happy to hear that!');
  }
  return sendTextMessage(event.sender.id, 'Too bad :-(');
}

/**
 * Handles opt in message
 * @param event
 * @returns {null}
 */
function receiveOptIn(event) {
  if (event.sender && event.sender.id) {
    console.log('Received opt-in from user', event.sender.id, 'with ref', event.optin.ref);
    return sendTextMessage(event.sender.id, 'Hello! I\'m a bot. Ask me anything you like.');
  }
  return null;
}

/**
 * Handles text message and passes it to wit.ai
 * @param event
 * @returns {Promise.<TResult>}
 */
function receiveMessage(event) {
  // if (event.sender && event.sender.id && event.message && event.message.text) {
  //   return sendTextMessage(event.sender.id, 'Hello!');
  // }
  // return null;
  return witAi(event)
    .then(result => sendTextMessage(event.sender.id, result))
    .catch(error => console.error('wit send error', error.message));
}

/**
 * Example generic message
 * @returns {null}
 */<commit_msg>Check WIT_AI_TOKEN and give response if it is missing<commit_after>'use strict';

const request = require('request-promise');
const session = require('./session.js');
const witAi = require('./wit-ai');

function sendGenericMessage(recipientId) {
  const messageData = {
    attachment: {
      type: 'template',
      payload: {
        template_type: 'generic',
        elements: [{
          title: 'Hi I\'m a bot on serverless 1.0! Do you like me?',
          buttons: [{
            type: 'postback',
            title: 'Yes',
            payload: 'like'
          }, {
            type: 'postback',
            title: 'No',
            payload: 'dislike'
          }]
        }]
      }
    }
  };

  return request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: process.env.FACEBOOK_BOT_PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: {
      recipient: { id: recipientId },
      message: messageData,
    }
  });
}

/**
 * Sends text message to recipient
 * @param recipientId
 * @param result
 */
function sendTextMessage(recipientId, result) {
  const message = { text: result.text };

  if (result.quickreplies) {
    Object.assign(message, {
      quick_replies: result.quickreplies.map(x => ({ title: x, content_type: 'text', payload: 'empty' }))
    });
  }

  return request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: process.env.FACEBOOK_BOT_PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: {
      recipient: { id: recipientId },
      message
    }
  });
}

/**
 * Handles postback message
 * @param event
 */
function receivePostback(event) {
  if (event.postback.payload === 'like') {
    return sendTextMessage(event.sender.id, '^_^ I\'m very happy to hear that!');
  }
  return sendTextMessage(event.sender.id, 'Too bad :-(');
}

/**
 * Handles opt in message
 * @param event
 * @returns {null}
 */
function receiveOptIn(event) {
  if (event.sender && event.sender.id) {
    console.log('Received opt-in from user', event.sender.id, 'with ref', event.optin.ref);
    return sendTextMessage(event.sender.id, 'Hello! I\'m a bot. Ask me anything you like.');
  }
  return null;
}

/**
 * Handles text message and passes it to wit.ai
 * @param event
 * @returns {Promise.<TResult>}
 */
function receiveMessage(event) {
  if (process.env.WIT_AI_TOKEN) {
    return witAi(event)
      .then(result => sendTextMessage(event.sender.id, result))
      .catch(error => console.error('wit send error', error.message));
  } else {
    console.log(event);
    if (event.sender && event.sender.id) {
      return sendTextMessage(event.sender.id, {
        text: 'Hello! I should converse with Wit.ai but I do not have a key!'
      });
    }
    return null;
  }
}

/**
 * Example generic message
 * @returns {null}
 */
{'fraction_non_alphanumeric': 0.15319772768920653, 'fraction_numerical': 0.0021990104452996153, 'mean_word_length': 2.7053632043448745, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 11, 'https://': 4, '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': '3281440', 'n_tokens_mistral': 1778, 'n_tokens_neox': 1766, 'n_words': 419}