<commit_before>#!/usr/bin/env node

'use strict';

var
  fs = require('fs'),
  path = require('path');

var
  program = require('commander'),
  updateNotifier = require('update-notifier'),
  chalk = require('chalk'),
  css = require('css'),
  _ = require('underscore');

var
  pkg = require('./package.json');

updateNotifier({
  packageName: pkg.name,
  packageVersion: pkg.version
}).notify();

css.stringifyRule = function(rule, options) {
  options = options || {};
  options.compress = options.compress !== false;

  return this.stringify({
    stylesheet: {
      rules: [rule]
    }
  }, options);
};

program
  .version(pkg.version, '-v, --version')
  .description(pkg.description)
  .usage('<stylesheet> [js]')
  .parse(process.argv);

var ln = program.args.length;

if (ln === 0) {
  program.help();
}

if (ln > 2) {
  console.error(chalk.red('Just one stylesheet please'));
  process.exit(1);
}

var stylesheet = path.normalize(program.args[0]);
var js;

if (ln === 2) {
  js = path.normalize(program.args[1]);
} else {
  js = stylesheet.replace(/\.css$/, '.js');
}

fs.readFile(stylesheet, function(err, data) {

  if (err) {
    console.error(chalk.red(err));
    process.exit(1);
  }

  var code = data.toString();

  var obj = css.parse(code, stylesheet);

  if (!obj.stylesheet || !obj.stylesheet.rules) {
    console.error(chalk.red('Cannot find rules in the root'));
    process.exit(1);
  }

  var icons = {};
  var prefixes = [];

  _.each(obj.stylesheet.rules, function(rule) {

    if (!rule.selectors || !rule.declarations) {
      return;
    }

    var declaration = _.findWhere(rule.declarations, {
      property: 'content'
    });

    if (!declaration) {
      return;
    }

    var content = declaration.value;

    var matches = content.match(/^("|')(.+)\1$/i);

    if (!matches) {
      console.warn(chalk.yellow('Skipping content without string value: ') + chalk.blue(css.stringifyRule(rule)));
      return;
    }

    var string = matches[2];

    if (string.match(/^\\[a-z0-9]{1,4}$/i)) {
      string = '\\u' + (new Array(4 + 2 - string.length)).join('0') + string.substr(1);
    }

    _.each(rule.selectors, function(selector) {

      var matches2 = selector.match(/^\.(([a-z0-9]+-)?[a-z0-9]+(?:-[a-z0-9]+)*):before$/i);

      if (!matches) {
        return;
      }

      var name = matches2[1];
      var prefix = matches2[2];

      if (name === 'icon-fold') {
        console.log(matches, string);
      }

      if (prefixes.indexOf(prefix) === -1) {
        prefixes.push(prefix);
      }

      icons[name] = string;
    });
  });

  var ln = _.size(icons);

  if (ln === 0) {
    console.error(chalk.red('Found no icons'));
    process.exit(1);
  }

  var prefix = (prefixes.length === 1) ? prefixes[0] : null;

  data = 'module.exports = {\n';

  _.each(_.keys(icons), function(name, i) {
    var unicode = icons[name];

    if (prefix) {
      name = name.substr(prefix.length);
    }

    if (name.indexOf('-') !== -1) {
      name = name.replace(/(\-[a-z0-9])/g, function($1) {
        return $1.toUpperCase().replace('-', '');
      });
    }

    data += '  ' + name + ': "' + unicode + '"' + ((i === ln - 1) ? '' : ',') + '\n';
  });

  data += '};';

  fs.writeFile(js, data, null, function(err) {

    if (err) {
      console.error(chalk.red(err));
      process.exit(1);
    }

    console.info(chalk.green('Written ' + ln + ' icons to: ' + js));
  });

});<commit_msg>Fixes #4<commit_after>#!/usr/bin/env node

'use strict';

var
  fs = require('fs'),
  path = require('path');

var
  program = require('commander'),
  updateNotifier = require('update-notifier'),
  chalk = require('chalk'),
  css = require('css'),
  _ = require('underscore');

var
  pkg = require('./package.json');

updateNotifier({
  packageName: pkg.name,
  packageVersion: pkg.version
}).notify();

css.stringifyRule = function(rule, options) {
  options = options || {};
  options.compress = options.compress !== false;

  return this.stringify({
    stylesheet: {
      rules: [rule]
    }
  }, options);
};

program
  .version(pkg.version, '-v, --version')
  .description(pkg.description)
  .usage('<stylesheet> [js]')
  .parse(process.argv);

var ln = program.args.length;

if (ln === 0) {
  program.help();
}

if (ln > 2) {
  console.error(chalk.red('Just one stylesheet please'));
  process.exit(1);
}

var stylesheet = path.normalize(program.args[0]);
var js;

if (ln === 2) {
  js = path.normalize(program.args[1]);
} else {
  js = stylesheet.replace(/\.css$/, '.js');
}

fs.readFile(stylesheet, function(err, data) {

  if (err) {
    console.error(chalk.red(err));
    process.exit(1);
  }

  var code = data.toString();

  var obj = css.parse(code, stylesheet);

  if (!obj.stylesheet || !obj.stylesheet.rules) {
    console.error(chalk.red('Cannot find rules in the root'));
    process.exit(1);
  }

  var icons = {};
  var prefixes = [];

  _.each(obj.stylesheet.rules, function(rule) {

    if (!rule.selectors || !rule.declarations) {
      return;
    }

    var declaration = _.findWhere(rule.declarations, {
      property: 'content'
    });

    if (!declaration) {
      return;
    }

    var content = declaration.value;

    var matches = content.match(/^("|')(.+)\1$/i);

    if (!matches) {
      console.warn(chalk.yellow('Skipping content without string value: ') + chalk.blue(css.stringifyRule(rule)));
      return;
    }

    var string = matches[2];

    if (string.match(/^\\[a-z0-9]{1,4}$/i)) {
      string = '\\u' + (new Array(4 + 2 - string.length)).join('0') + string.substr(1);
    }

    _.each(rule.selectors, function(selector) {

      var matches2 = selector.match(/^\.(([a-z0-9]+-)?[a-z0-9]+(?:[_-][a-z0-9]+)*):before$/i);

      if (!matches2) {
        return;
      }

      var name = matches2[1];
      var prefix = matches2[2];

      if (prefixes.indexOf(prefix) === -1) {
        prefixes.push(prefix);
      }

      icons[name] = string;
    });
  });

  var ln = _.size(icons);

  if (ln === 0) {
    console.error(chalk.red('Found no icons'));
    process.exit(1);
  }

  var prefix = (prefixes.length === 1) ? prefixes[0] : null;

  data = 'module.exports = {\n';

  _.each(_.keys(icons), function(name, i) {
    var unicode = icons[name];

    if (prefix) {
      name = name.substr(prefix.length);
    }

    if (name.indexOf('-') !== -1 || name.indexOf('_') !== -1) {
      name = name.replace(/[_-]([a-z0-9])([^_-]*)/gi, function(match, p1, p2) {
        return p1.toUpperCase() + p2.toLowerCase();
      });
    }

    data += '  ' + name + ': "' + unicode + '"' + ((i === ln - 1) ? '' : ',') + '\n';
  });

  data += '};';

  fs.writeFile(js, data, null, function(err) {

    if (err) {
      console.error(chalk.red(err));
      process.exit(1);
    }

    console.info(chalk.green('Written ' + ln + ' icons to: ' + js));
  });

});<|endoftext|>


<commit_before>var hexpp = require('hexpp')
var fs = require('fs')
var decode = require('./decode')

function open (file) {
  return file === typeof number ? file : fs.openSync(file)
}

function open (file, cb) {
  fs.open(file, 'r', function (err, fd) {
    if(err) return cb(err)
    fs.stat(file, function (err, stat) {
      if(err) return cb(err)
      cb(null, {filename: file, fd: fd, size: stat.size})
    })
  })
}

function read (file, start, end, cb) {
  if('string' == typeof file)
    open(file, next)
  else next(null, file)

  function next (err, opts) {
    if(err) return cb(err)

    //handle regative lengths from the end.
    if(start < 0) start = opts.size - ~start
    if(end < 0) end = opts.size - ~end
    var buffer = new Buffer(end - start)
    fs.read(opts.fd, buffer, 0, buffer.length, start, function (err) {
      cb(err, buffer, opts)
    })
  }

}

module.exports = function (file, cb) {
  read(file, ~8, ~0, function (err, footerLength, opts) {
    if(err) return cb(err)
    read(opts, ~(footerLength.readUInt32LE(0) + 8), ~8,
      function (err, footer) {
      var fmd = decode.FileMetaData(footer)
      cb(null, fmd, opts)
    })
  })
}

function dump (data) {
  console.log(JSON.stringify(data, null, 2))
}

if(!module.parent) {
  var opts = require('minimist')(process.argv.slice(2))
  var filename = opts._.shift()

  module.exports(filename, function (err, data, file) {
    if(err) throw err
    if(opts.meta) dump(data)
    if(opts.schema) dump(data.schema)
    if(opts.row_group != null)
      dump(data.row_groups[+opts.row_group])
    if(opts.column != null) {
      console.log(opts)
      var rg = data.row_groups[0]
      var column = rg.columns[opts.column]
      console.log(
        column.file_offset,
        column.file_offset + column.meta_data.total_compressed_size
      )
      read(
        file,
        +column.file_offset,
        column.file_offset + column.meta_data.total_compressed_size,
        function (err, buf) {
          if(err) throw err
          console.log(data.schema[1+opts.column])
          console.log(column)
          console.log(decode.PageHeader(buf))
          var body = buf.slice(decode.bytes)
          console.log(hexpp(body.slice(0, body.readUInt32LE(0))))
          console.log("REST")
          console.log(hexpp(body.slice(body.readUInt32LE(0))))
        })
    }
  })
}

<commit_msg>better errors<commit_after>var hexpp = require('hexpp')
var fs = require('fs')
var decode = require('./decode')

function open (file) {
  return file === typeof number ? file : fs.openSync(file)
}

function open (file, cb) {
  fs.open(file, 'r', function (err, fd) {
    if(err) return cb(err)
    fs.stat(file, function (err, stat) {
      if(err) return cb(err)
      cb(null, {filename: file, fd: fd, size: stat.size})
    })
  })
}

function read (file, start, end, cb) {
  if('string' == typeof file)
    open(file, next)
  else if(file && 'object' == typeof file)
    next(null, file)
  else
    throw new Error('unknown type:'+JSON.stringify(file))

  function next (err, opts) {
    if(err) return cb(err)

    //handle regative lengths from the end.
    if(start < 0) start = opts.size - ~start
    if(end < 0) end = opts.size - ~end
    var buffer = new Buffer(end - start)
    fs.read(opts.fd, buffer, 0, buffer.length, start, function (err) {
      cb(err, buffer, opts)
    })
  }

}

module.exports = function (file, cb) {
  read(file, ~8, ~0, function (err, footerLength, opts) {
    if(err) return cb(err)
    read(opts, ~(footerLength.readUInt32LE(0) + 8), ~8,
      function (err, footer) {
      var fmd = decode.FileMetaData(footer)
      cb(null, fmd, opts)
    })
  })
}

function dump (data) {
  console.log(JSON.stringify(data, null, 2))
}

if(!module.parent) {
  var opts = require('minimist')(process.argv.slice(2))
  var filename = opts._.shift()

  if(!filename) throw new Error('filename must be provided')
  module.exports(filename, function (err, data, file) {
    if(err) throw err
    if(opts.meta) dump(data)
    if(opts.schema) dump(data.schema)
    if(opts.row_group != null)
      dump(data.row_groups[+opts.row_group])
    if(opts.column != null) {
      console.log(opts)
      var rg = data.row_groups[0]
      var column = rg.columns[opts.column]
      console.log(
        column.file_offset,
        column.file_offset + column.meta_data.total_compressed_size
      )
      read(
        file,
        +column.file_offset,
        column.file_offset + column.meta_data.total_compressed_size,
        function (err, buf) {
          if(err) throw err
          console.log(data.schema[1+opts.column])
          console.log(column)
          console.log(decode.PageHeader(buf))
          var body = buf.slice(decode.bytes)
          console.log(hexpp(body.slice(0, body.readUInt32LE(0))))
          console.log("REST")
          console.log(hexpp(body.slice(body.readUInt32LE(0))))
        })
    }
  })
}

<|endoftext|>


<commit_before>const fs = require('fs');
const exec = require('child_process').exec;
const moment = require('moment');

/*****************************************************************
    0.........1.........2.........3.........4.........5.........
0   ------------------------------------------------------------
1   ---##----##----####-------##------##---#####---#####--------
2   ---####--##---##--##------##-----------##------##-----------
3   ---##-##-##---##--##------##------##---####----####---------
4   ---##--####---##--##------##------##---##------##-----------
5   ---##----##----####-------#####---##---##------#####--------
6   ------------------------------------------------------------
// run in console to draw on github timeline:
a = document.getElementsByClassName('day')
for (let i=0, l=a.length; i<l; i++ ){
  a[i].setAttribute('fill', '#c6e48b')
  a[i].addEventListener('click', ()=>{ a[i].setAttribute('fill', '#196127') })
  a[i].addEventListener('contextmenu', ()=>{ a[i].setAttribute('fill', '#c6e48b') })
}
*****************************************************************/

let days = [
  '------------------------------------------------------------'.split(''),
  '----##--##--###----##-----##--##--##--##--#-#-#-------------'.split(''),
  '----###-##-##-##----#--#--#--####--#--#---#-#-#-------------'.split(''),
  '----######-##-##----##-#-##-##--##-####---#-#-#-------------'.split(''),
  '----##-###-##-##----######--######--##----------------------'.split(''),
  '----##--##--###------##-##-###--###-##----#-#-#-------------'.split(''),
  '------------------------------------------------------------'.split('')
];

let offset = 17; // because the day i wrote this was 12 days after %60 == 0
// find indexes
let x = ( Math.floor((moment().diff(moment().startOf('year'), 'weeks') )-offset) ) % 60;
let y = moment().weekday() % 7;
// define if it s letter day or not
let isPixel = days[y][x] == '#';
log = (...opts) => {
  console.log( (isPixel?'#':'-')+' ['+moment().format('M-D-YY, h:mm a')+'] -', opts.join(' ') );
}

// Randomize:
// if it IS an update day, LOW exit likelyness
if ( isPixel && Math.random()<.15 ) {
  return log('Busy day but not now...');
}
// if it IS NOT an update day, HIGH exit likelyness
if ( !isPixel && Math.random()<.8 ) {
  return log('Not a busy day, not now...');
}

const emos = ["😀","😃","😄","😁","😆","😅","😂","😊","😇","🙂","🙃","😉","😌","😍","😘","😗","😙","😚",
  "😋","😜","😝","😛","🤑","🤗","🤓","😎","😏","😒","😞","😔","😟","😕","🙁","☹","😣","😖","😫","😩","😤",
  "😠","😡","😶","😐","😑","😯","😦","😧","😮","😲","😵","😳","😱","😨","😰","😢","😥","😭","😓","😪","😴",
  "🙄","🤔","😬","🤐","😷","🤒","🤕","😈","👿","👹","👺","💩","👻","💀","☠","👽","👾","🤖","🎃","😺","😸",
  "😹","😻","😼","😽","🙀","😿","😾","👐","🙌","👏","🙏","👍","👎","👊","✊","✌","🤘","👌","👈","👉","👆",
  "👇","☝","✋","🖐","🖖","👋","💪","🖕","✍","💅","🖖","💄","💋","👄","👅","👂","👃","👣","👁","👀","🗣",
  "👤","👥","👶","👦","👧","👨","👩","👱","👱","👴","👵","👲","👳","👳","👮","👮","👷","👷","💂","💂","🕵",
  "🕵","👩","👨","👩","🌾","👨","🌾","🍳","👨","🍳","👩","🎓","👨","👩","👨","🎤","👩","🏫","👨","🏫","👩",
  "🏭","👨","💻","👚","👕","👖","👔","👗","👙","👘","👠","👡","👢","👞","👟","👒","🎩","🎓","👑","⛑","🎒",
  "👝","👛","👜","💼","👓","🕶","🌂","☂"
];

// generate commit message
let n = 10;
let code = '';
let message = ''
while ( n-- > 0 )
  message += emos[Math.floor(Math.random()*emos.length)] + ' '
// generate random code
n = 3 + Math.random() * 10;
while ( n-- > 0 )
  code += emos[Math.floor(Math.random()*emos.length)] + ' '
  if ( Math.random() > .8 ) code += '\r\n';
// save code
fs.writeFileSync('jam.txt', code, 'utf8');
// push changes to github
exec('git pull && git add jam.txt && git commit -m "'+message+'" && git push', (error, stdout, stderr)=>{
  if (error) {
    return log('Error:', error, error.code);
  }
  log('√ Pushed to Git -', message);
})

<commit_msg>Stash changes<commit_after>const fs = require('fs');
const exec = require('child_process').exec;
const moment = require('moment');

/*****************************************************************
    0.........1.........2.........3.........4.........5.........
0   ------------------------------------------------------------
1   ---##----##----####-------##------##---#####---#####--------
2   ---####--##---##--##------##-----------##------##-----------
3   ---##-##-##---##--##------##------##---####----####---------
4   ---##--####---##--##------##------##---##------##-----------
5   ---##----##----####-------#####---##---##------#####--------
6   ------------------------------------------------------------
// run in console to draw on github timeline:
a = document.getElementsByClassName('day')
for (let i=0, l=a.length; i<l; i++ ){
  a[i].setAttribute('fill', '#c6e48b')
  a[i].addEventListener('click', ()=>{ a[i].setAttribute('fill', '#196127') })
  a[i].addEventListener('contextmenu', ()=>{ a[i].setAttribute('fill', '#c6e48b') })
}
*****************************************************************/

let days = [
  '------------------------------------------------------------'.split(''),
  '----##--##--###----##-----##--##--##--##--#-#-#-------------'.split(''),
  '----###-##-##-##----#--#--#--####--#--#---#-#-#-------------'.split(''),
  '----######-##-##----##-#-##-##--##-####---#-#-#-------------'.split(''),
  '----##-###-##-##----######--######--##----------------------'.split(''),
  '----##--##--###------##-##-###--###-##----#-#-#-------------'.split(''),
  '------------------------------------------------------------'.split('')
];

let offset = 17; // because the day i wrote this was 12 days after %60 == 0
// find indexes
let x = ( Math.floor((moment().diff(moment().startOf('year'), 'weeks') )-offset) ) % 60;
let y = moment().weekday() % 7;
// define if it s letter day or not
let isPixel = days[y][x] == '#';
log = (...opts) => {
  console.log( (isPixel?'#':'-')+' ['+moment().format('M-D-YY, h:mm a')+'] -', opts.join(' ') );
}

// Randomize:
// if it IS an update day, LOW exit likelyness
if ( isPixel && Math.random()<.15 ) {
  return log('Busy day but not now...');
}
// if it IS NOT an update day, HIGH exit likelyness
if ( !isPixel && Math.random()<.8 ) {
  return log('Not a busy day, not now...');
}

const emos = ["😀","😃","😄","😁","😆","😅","😂","😊","😇","🙂","🙃","😉","😌","😍","😘","😗","😙","😚",
  "😋","😜","😝","😛","🤑","🤗","🤓","😎","😏","😒","😞","😔","😟","😕","🙁","☹","😣","😖","😫","😩","😤",
  "😠","😡","😶","😐","😑","😯","😦","😧","😮","😲","😵","😳","😱","😨","😰","😢","😥","😭","😓","😪","😴",
  "🙄","🤔","😬","🤐","😷","🤒","🤕","😈","👿","👹","👺","💩","👻","💀","☠","👽","👾","🤖","🎃","😺","😸",
  "😹","😻","😼","😽","🙀","😿","😾","👐","🙌","👏","🙏","👍","👎","👊","✊","✌","🤘","👌","👈","👉","👆",
  "👇","☝","✋","🖐","🖖","👋","💪","🖕","✍","💅","🖖","💄","💋","👄","👅","👂","👃","👣","👁","👀","🗣",
  "👤","👥","👶","👦","👧","👨","👩","👱","👱","👴","👵","👲","👳","👳","👮","👮","👷","👷","💂","💂","🕵",
  "🕵","👩","👨","👩","🌾","👨","🌾","🍳","👨","🍳","👩","🎓","👨","👩","👨","🎤","👩","🏫","👨","🏫","👩",
  "🏭","👨","💻","👚","👕","👖","👔","👗","👙","👘","👠","👡","👢","👞","👟","👒","🎩","🎓","👑","⛑","🎒",
  "👝","👛","👜","💼","👓","🕶","🌂","☂"
];

// generate commit message
let n = 10;
let code = '';
let message = ''
while ( n-- > 0 )
  message += emos[Math.floor(Math.random()*emos.length)] + ' '
// generate random code
n = 3 + Math.random() * 10;
while ( n-- > 0 )
  code += emos[Math.floor(Math.random()*emos.length)] + ' '
  if ( Math.random() > .8 ) code += '\r\n';
// save code
fs.writeFileSync('jam.txt', code, 'utf8');
// push changes to github
exec('git stash && git pull && git add jam.txt && git commit -m "'+message+'" && git push', (error, stdout, stderr)=>{
  if (error) {
    return log('Error:', error, error.code);
  }
  log('√ Pushed to Git -', message);
})

<|endoftext|>


<commit_before>// initialization

var Discord = require("discord.js");
var bot = new Discord.Client();
var fs = require('fs');

// global vars

var config;
var jaredInfo = {
  id: '236715184251469825',
  username: '2D (Undead Speaker)',
  discriminator: '6748',
  avatar: '45e8fee6889688cd3547cb6216adb69c',
  bot: false }
var responseObjects = {};
var shipObjects = {};

// message triggerer

bot.on("message", msg => {
  for (i = 0; i < fs.readdirSync('plugins/triggers').length; i++) {
    if (responseObjects[fs.readdirSync('plugins/triggers')[i]][msg.content.toLowerCase()]) {
      msg.channel.sendMessage(responseObjects[fs.readdirSync('plugins/triggers')[i]][msg.content.toLowerCase()]);
    }
  }
});

// commands

// SHIP
bot.on("message", msg => {
  if (msg.content.match (" x ") != null) {
    shipArray = msg.content.split(" x ");
    ship1 = shipArray[0];
    ship2 = shipArray[1];

    if (shipObjects[ship1]) {
      if (shipObjects[ship1][ship2]) {
        msg.channel.sendMessage(shipObjects[ship1][ship2]);
      }
    } else {
      ship1half = "";
      ship2half = "";
      for (i = 0; i < Math.round(ship1.length/2); i++)  {
        ship1half += ship1[i];
      }
      for (i = Math.round(ship2.length/2); i < ship2.length; i++) {
        ship2half += ship2[i];
      }
      finalShip = ship1half + ship2half;
      msg.channel.sendMessage(finalShip);
    }
  }
});

;

// VENT RESET
/*bot.on('message', msg => {
  currentDate = new Date();
  //if (msg.channel.name == "vent" && currentDate.getHours() == 1 && currentDate.getMinutes() == 50 && currentDate.getSeconds == 0) {
  //  msg.channel.sendMessage("Daily reset begins in **5 minutes**.");
  //}
  //if (msg.channel.name == "vent" && currentDate.getHours() == 1 && currentDate.getMinutes() == 54 && currentDate.getSeconds == 55) {
  //  msg.channel.sendMessage("Daily reset begins in **5 seconds**.");
  //}
  if (msg.channel.name == "vent" && currentDate.getHours() == 2 && currentDate.getMinutes() == 30 && currentDate.getSeconds() < 30) {
    msg.channel.messages.deleteAll();
  } else if (msg.channel.name == "vent" && currentDate.getHours() == 2 && currentDate.getMinutes() == 30 && currentDate.getSeconds() > 30) {
    msg.channel.messages.deleteAll();
  }
  if (msg.channel.name == "vent" && currentDate.getHours() == 2 && currentDate.getMinutes() == 30 && currentDate.getSeconds() == 0) {
      msg.channel.sendMessage("Daily reset complete.");
  }
});*/

// JARED SPAMMER
bot.on('message', msg => {
  if (msg.content == "activate jared") {
    msg.channel.sendMessage(jaredInfo);
  }
});

// functions

function loadConfiguration(callback) {
  config = JSON.parse(fs.readFileSync('config.json'));
  console.log('Read configuration from `config.json`.');

  if (config.token === undefined || config.token.length < 1) {
    console.log('No bot token is set in config.json.');
  } else {
    bot.login(config.token);
  }

  if (fs.readdirSync('plugins/triggers') != undefined || fs.readdirSync('plugins/triggers').length > 0) {
    for (i = 0; i < fs.readdirSync('plugins/triggers').length; i++) {
      responseObjects[fs.readdirSync('plugins/triggers')[i]] = JSON.parse(fs.readFileSync('./plugins/triggers/' + fs.readdirSync('plugins/triggers')[i]))
    }
  }

  if (fs.readdirSync('plugins') != undefined || fs.readdirSync('plugins').length > 0) {
    shipObjects = JSON.parse(fs.readFileSync('plugins/ships.json'));
  }
}

// essentials

loadConfiguration();

bot.on('ready', () => {
  console.log('HALOBOT ONLINE :3');
});
<commit_msg>what<commit_after>// initialization

var Discord = require("discord.js");
var bot = new Discord.Client();
var fs = require('fs');

// global vars

var config;
var jaredInfo = {
  id: '236715184251469825',
  username: '2D (Undead Speaker)',
  discriminator: '6748',
  avatar: '45e8fee6889688cd3547cb6216adb69c',
  bot: false }
var responseObjects = {};
var shipObjects = {};

// message triggerer

bot.on("message", msg => {
  for (i = 0; i < fs.readdirSync('plugins/triggers').length; i++) {
    if (responseObjects[fs.readdirSync('plugins/triggers')[i]][msg.content.toLowerCase()]) {
      msg.channel.sendMessage(responseObjects[fs.readdirSync('plugins/triggers')[i]][msg.content.toLowerCase()]);
    }
  }
});

// commands

// SHIP
bot.on("message", msg => {
  if (msg.content.match (" x ") != null) {
    shipArray = msg.content.split(" x ");
    ship1 = shipArray[0];
    ship2 = shipArray[1];

    if (shipObjects[ship1]) {
      if (shipObjects[ship1][ship2]) {
        msg.channel.sendMessage(shipObjects[ship1][ship2]);
      }
    } else {
      ship1half = "";
      ship2half = "";
      for (i = 0; i < Math.round(ship1.length/2); i++)  {
        ship1half += ship1[i];
      }
      for (i = Math.round(ship2.length/2); i < ship2.length; i++) {
        ship2half += ship2[i];
      }
      finalShip = ship1half + ship2half;
      msg.channel.sendMessage(finalShip);
    }
  }
})

;

// VENT RESET
/*bot.on('message', msg => {
  currentDate = new Date();
  //if (msg.channel.name == "vent" && currentDate.getHours() == 1 && currentDate.getMinutes() == 50 && currentDate.getSeconds == 0) {
  //  msg.channel.sendMessage("Daily reset begins in **5 minutes**.");
  //}
  //if (msg.channel.name == "vent" && currentDate.getHours() == 1 && currentDate.getMinutes() == 54 && currentDate.getSeconds == 55) {
  //  msg.channel.sendMessage("Daily reset begins in **5 seconds**.");
  //}
  if (msg.channel.name == "vent" && currentDate.getHours() == 2 && currentDate.getMinutes() == 30 && currentDate.getSeconds() < 30) {
    msg.channel.messages.deleteAll();
  } else if (msg.channel.name == "vent" && currentDate.getHours() == 2 && currentDate.getMinutes() == 30 && currentDate.getSeconds() > 30) {
    msg.channel.messages.deleteAll();
  }
  if (msg.channel.name == "vent" && currentDate.getHours() == 2 && currentDate.getMinutes() == 30 && currentDate.getSeconds() == 0) {
      msg.channel.sendMessage("Daily reset complete.");
  }
});*/

// JARED SPAMMER
bot.on('message', msg => {
  if (msg.content == "activate jared") {
    msg.channel.sendMessage(jaredInfo);
  }
});

// functions

function loadConfiguration(callback) {
  config = JSON.parse(fs.readFileSync('config.json'));
  console.log('Read configuration from `config.json`.');

  if (config.token === undefined || config.token.length < 1) {
    console.log('No bot token is set in config.json.');
  } else {
    bot.login(config.token);
  }

  if (fs.readdirSync('plugins/triggers') != undefined || fs.readdirSync('plugins/triggers').length > 0) {
    for (i = 0; i < fs.readdirSync('plugins/triggers').length; i++) {
      responseObjects[fs.readdirSync('plugins/triggers')[i]] = JSON.parse(fs.readFileSync('./plugins/triggers/' + fs.readdirSync('plugins/triggers')[i]))
    }
  }

  if (fs.readdirSync('plugins') != undefined || fs.readdirSync('plugins').length > 0) {
    shipObjects = JSON.parse(fs.readFileSync('plugins/ships.json'));
  }
}

// essentials

loadConfiguration();

bot.on('ready', () => {
  console.log('HALOBOT ONLINE :3');
});
<|endoftext|>


<commit_before>const Discord = require("discord.js");
const Request = require("request");
const Cheerio = require("cheerio");
const Tokens = require("./tokens.json");

const bot = new Discord.Client();

// When bot is launched
bot.on("ready", function() {
  console.log(`\nCollege Stats Bot ready to server in `
    + `${bot.channels.size} channels on ${bot.guilds.size} servers, `
    + `for a total of ${bot.users.size} users.\n`);
  bot.user.setGame("-college <uni name>");
});

// When bot receives a message
bot.on("message", function(message) {
  // Prefix for bot commands
  let prefix = "-";

  var input = message.content;

  // Exits function if message doesn't start with prefix or is from a bot
  if (!input.startsWith(prefix)) return;
  if (message.author.bot) return;

  // Command -help results in bot explaining how command college works
  if (input === prefix + "help") {
    message.channel.sendEmbed(new Discord.RichEmbed()
    .setTitle("College Stats Bot Instructions")
    .setColor(0x323D7F)
    .setDescription("Just type '-college <name of university>' without the "
      + "quotes to get a link to its statistics page. For example, '-college "
      + "princeton' will return a link to Princeton's statistics. You can see "
      + "the code at https://github.com/45b16/college-stats-bot.")
    .setTimestamp());
  }
  // Command -college <insert college> results in bot sending a link to search
  // results and basic stats of the college
  else if (input.startsWith(prefix + "college ")) {
    // Logs the time that the -stats message was sent
    var hours = message.createdAt.getHours().toString();
    var minutes = message.createdAt.getMinutes().toString();
    var seconds = message.createdAt.getSeconds().toString();
    if (hours.length < 2) {
      hours = "0" + hours;
    }
    if (minutes.length < 2) {
      minutes = "0" + minutes;
    }
    if (seconds.length < 2) {
      seconds = "0" + seconds;
    }
    console.log(`${message.guild.name} - ${message.channel.name}`);
    console.log(`${hours}:${minutes}:${seconds} `
      + `- ${message.author.username}: ${message.content}\n`);

    // Gets college name to search for
    var college = input.substring(9);
    college2 = college.replace(/ /g, "_");

    // Gets US News National Universities search link and does an
    // HTTP GET request on it with headers
    var link = `http://colleges.usnews.rankingsandreviews.com/best-colleges`
      +`/rankings/national-universities?school-name=${college2}&_mode=list`;
    Request({
        uri: link,
        headers: {
          "User-Agent": Tokens.userAgent,
          "Accept": "/",
          "Connection": "Keep-Alive",
          "Accept-Encoding": "identity"
        },
        jar: true,
      },
      function(err, resp, body) {
        if (!err && resp.statusCode == 200) {
          var $ = Cheerio.load(body);

          // Filters out html except for the search results
          $(".search-results-view").filter(function() {
            var data = $(this);

            // If no search results found, embed sent informing user
            if (data.children()[0] == null) {
              message.channel.sendEmbed(new Discord.RichEmbed()
              .setTitle("First US news search result for " + college)
              .setColor(0x323D7F)
              .setDescription(`No valid search results found at ${link}. `
		+ `This bot only pulls from US News's list of National `
		+ `Universities.`)
              .setTimestamp());
              console.log("None found\n");
            }
            // Takes url of the first college in the search results and does an
            // HTTP request to get more information
            else {
              var endUrl = data.children()[0].children[1].children[1]
                .children[1].children[3].children[1].attribs.href;
              var pg = `http://colleges.usnews.rankingsandreviews.com${endUrl}`;
              Request({
                  uri: pg,
                  headers: {
                    "User-Agent": Tokens.userAgent,
                    "Accept": "/",
                    "Connection": "Keep-Alive",
                    "Accept-Encoding": "identity"
                  },
                  jar: true,
                },
                function(error, response, html) {
                  if (!error && response.statusCode == 200) {
                    var $ = Cheerio.load(html);

                    var name, ranking, stats;
                    var info = {name : "", ranking : "", stats : ""};

                    // Gets name
                    var nameClass = ".hero-heading.flex-media-heading"
                      + ".block-tight.hero-heading.text-tighter.block-tight"
                      + ".flex-media-heading";
                    $(nameClass).filter(function() {
                      var collName = $(this)[0].children[0].data;
                      info.name = collName.replace(/^\s+|\s+$/g, "");
                    });

                    // Gets National Universities ranking
                    var rankClass = ".block-normal.block-flush-for-medium-up"
                      + ".display-inline-block.hero-ranking-data-rank";
                    $(rankClass).filter(function() {
                      var rank = $(this).children()[0].children[0].data;
                      info.ranking = rank.replace(/\s/g, "");
                    });

                    // Gets stats on tuition, room and board, enrollment,
                    // and application deadline
                    $(".hero-stats-widget-stats li").each(function() {
                      info.stats += `${$(this)[0].children[0].children[0].data}`
                        + `\n${$(this)[0].children[2].children[0].data}\n\n`;
                    });

                    // Sends embed with information to Discord channel
                    message.channel.sendEmbed(new Discord.RichEmbed()
                    .setTitle("First US news search result for " + college)
                    .setColor(0x323D7F)
                    .setDescription(info.name)
                    .addField("Link", pg)
                    .addField("National Universities Ranking", info.ranking)
                    .addField("College Statistics", info.stats)
                    .setTimestamp());
		    console.log(info.name + "\n");
                  }
              });
            }
          });
        }
    });
  }
  else return;
});

// Bot sends crash messages to console
bot.on('error', function(e) {
    console.error(e);
});
bot.on('warn', function(w) {
    console.warn(w);
});

// Bot logs in with token
bot.login(Tokens.discordToken);
<commit_msg>Fixed typos, tabbing errors, and readibility<commit_after>const Discord = require("discord.js");
const Request = require("request");
const Cheerio = require("cheerio");

// Need .json file in the directory storing a user agent for web scraping
// and the Discord token to log the bot in with
const Tokens = require("./tokens.json");

const bot = new Discord.Client();

// When bot is launched
bot.on("ready", function() {
  console.log(`\nCollege Stats Bot ready to server in `
    + `${bot.channels.size} channels on ${bot.guilds.size} servers, `
    + `for a total of ${bot.users.size} users.\n`);
  bot.user.setGame("-college <uni name>");
});

// When bot receives a message
bot.on("message", function(message) {
  // Prefix for bot commands
  let prefix = "-";

  var input = message.content;

  // Exits function if message doesn't start with prefix or is from a bot
  if (!input.startsWith(prefix)) return;
  if (message.author.bot) return;

  // Command -help results in bot explaining how command college works
  if (input === prefix + "help") {
    message.channel.sendEmbed(new Discord.RichEmbed()
    .setTitle("College Stats Bot Instructions")
    .setColor(0x323D7F)
    .setDescription("Just type '-college <name of university>' without the "
      + "quotes to get a link to its statistics page. For example, '-college "
      + "princeton' will return a link to Princeton's statistics. You can see "
      + "the code at https://github.com/abhinavk99/CollegeBot.")
    .setTimestamp());
  }
  // Command -college <insert college> results in bot sending a link to search
  // results and basic stats of the college
  else if (input.startsWith(prefix + "college ")) {
    // Logs information about the message
    infoLogger(message);

    // Gets college name to search for
    var college = input.substring(9);
    college2 = college.replace(/ /g, "_");

    // Gets US News National Universities search link and does an
    // HTTP GET request on it with headers
    var link = `http://colleges.usnews.rankingsandreviews.com/best-colleges`
      +`/rankings/national-universities?school-name=${college2}&_mode=list`;
    Request({
        uri: link,
        headers: {
          "User-Agent": Tokens.userAgent,
          "Accept": "/",
          "Connection": "Keep-Alive",
          "Accept-Encoding": "identity"
        },
        jar: true,
      },
      function(err, resp, body) {
        if (!err && resp.statusCode == 200) {
          var $ = Cheerio.load(body);

          // Filters out html except for the search results
          $(".search-results-view").filter(function() {
            var data = $(this);

            // If no search results found, embed sent informing user
            if (data.children()[0] == null) {
              message.channel.sendEmbed(new Discord.RichEmbed()
              .setTitle("First US news search result for " + college)
              .setColor(0x323D7F)
              .setDescription(`No valid search results found at ${link}. `
		            + `This bot only pulls from US News's list of National `
		            + `Universities.`)
              .setTimestamp());
              console.log("None found\n");
            }
            // Takes url of the first college in the search results and does an
            // HTTP request to get more information
            else {
              var endUrl = data.children()[0].children[1].children[1]
                .children[1].children[3].children[1].attribs.href;
              var pg = `http://colleges.usnews.rankingsandreviews.com${endUrl}`;
              Request({
                  uri: pg,
                  headers: {
                    "User-Agent": Tokens.userAgent,
                    "Accept": "/",
                    "Connection": "Keep-Alive",
                    "Accept-Encoding": "identity"
                  },
                  jar: true,
                },
                function(error, response, html) {
                  if (!error && response.statusCode == 200) {
                    var $ = Cheerio.load(html);

                    var name, ranking, stats;
                    var info = {name : "", ranking : "", stats : ""};

                    // Gets name
                    var nameClass = ".hero-heading.flex-media-heading"
                      + ".block-tight.hero-heading.text-tighter.block-tight"
                      + ".flex-media-heading";
                    $(nameClass).filter(function() {
                      var collName = $(this)[0].children[0].data;
                      info.name = collName.replace(/^\s+|\s+$/g, "");
                    });

                    // Gets National Universities ranking
                    var rankClass = ".block-normal.block-flush-for-medium-up"
                      + ".display-inline-block.hero-ranking-data-rank";
                    $(rankClass).filter(function() {
                      var rank = $(this).children()[0].children[0].data;
                      info.ranking = rank.replace(/\s/g, "");
                    });

                    // Gets stats on tuition, room and board, enrollment,
                    // and application deadline
                    $(".hero-stats-widget-stats li").each(function() {
                      info.stats += `${$(this)[0].children[0].children[0].data}`
                        + `\n${$(this)[0].children[2].children[0].data}\n\n`;
                    });

                    // Sends embed with information to Discord channel
                    message.channel.sendEmbed(new Discord.RichEmbed()
                    .setTitle("First US news search result for " + college)
                    .setColor(0x323D7F)
                    .setDescription(info.name)
                    .addField("Link", pg)
                    .addField("National Universities Ranking", info.ranking)
                    .addField("College Statistics", info.stats)
                    .setTimestamp());
		                console.log(info.name + "\n");
                  }
              });
            }
          });
        }
    });
  }
  else return;
});

// Bot sends crash messages to console
bot.on('error', function(e) {
    console.error(e);
});

bot.on('warn', function(w) {
    console.warn(w);
});

// Bot logs in with token
bot.login(Tokens.discordToken);

// logs information about the command
function infoLogger(message) {
  // Logs the time that the -stats message was sent
  var hours = message.createdAt.getHours().toString();
  var minutes = message.createdAt.getMinutes().toString();
  var seconds = message.createdAt.getSeconds().toString();
  if (hours.length < 2) {
    hours = "0" + hours;
  }
  if (minutes.length < 2) {
    minutes = "0" + minutes;
  }
  if (seconds.length < 2) {
    seconds = "0" + seconds;
  }
  console.log(`${message.guild.name} - ${message.channel.name}`);
  console.log(`${hours}:${minutes}:${seconds} `
    + `- ${message.author.username}: ${message.content}\n`);
}<|endoftext|>


<commit_before>require('./server.js');
var dischord = require('discord.js');

var bot = new dischord.Client();

function searchGrimoire() {
    bot.on("message", function(message) {
        var input = message.content;
        var stripeCmd = input.substr('8');
        var siteSearch = input.startsWith('!search');

        if(siteSearch) {
            bot.reply(message, "http://www.ishtar-collective.net/search/" + encodeURIComponent(stripeCmd));
        } return
    });
}

function searchCard() {
    bot.on("message", function(message) {
        var input = message.content;
        var stripeCmd = input.substr('6');
        var cardSearch = input.startsWith('!card');
        var trailingUri = stripeCmd.replace(/\s+/g, "-");

        if(cardSearch) {
            bot.reply(message, "http://www.ishtar-collective.net/cards/" + trailingUri);
        } return
    });
}

function searchItems() {
    bot.on("message", function(message) {
        var input = message.content;
        var stripeCmd = input.substr('6');
        var cardSearch = input.startsWith('!item');
        var stripApostrophe = stripeCmd.replace("'", "");
        var trailingUri = stripApostrophe.replace(/\s+/g, "-");

        if(cardSearch) {
            bot.reply(message, "http://www.ishtar-collective.net/items/" + trailingUri);
        } return
    });
}

bot.loginWithToken(process.env.CLIENT_ID, function (token, err) {
    if(err){
        console.log(err);
    }

    searchGrimoire();
    searchCard();
    searchItems();

});<commit_msg>covert all input for item search to lowercase<commit_after>require('./server.js');
var dischord = require('discord.js');

var bot = new dischord.Client();

function searchGrimoire() {
    bot.on("message", function(message) {
        var input = message.content;
        var stripeCmd = input.substr('8');
        var siteSearch = input.startsWith('!search');

        if(siteSearch) {
            bot.reply(message, "http://www.ishtar-collective.net/search/" + encodeURIComponent(stripeCmd));
        } return
    });
}

function searchCard() {
    bot.on("message", function(message) {
        var input = message.content;
        var stripeCmd = input.substr('6');
        var cardSearch = input.startsWith('!card');
        var trailingUri = stripeCmd.replace(/\s+/g, "-");

        if(cardSearch) {
            bot.reply(message, "http://www.ishtar-collective.net/cards/" + trailingUri);
        } return
    });
}

function searchItems() {
    bot.on("message", function(message) {
        var input = message.content;
        var stripeCmd = input.substr('6');
        var lowercaseify = stripeCmd.toLowerCase();
        var cardSearch = input.startsWith('!item');
        var stripApostrophe = lowercaseify.replace("'", "");
        var trailingUri = stripApostrophe.replace(/\s+/g, "-");

        if(cardSearch) {
            bot.reply(message, "http://www.ishtar-collective.net/items/" + trailingUri);
        } return
    });
}

bot.loginWithToken(process.env.CLIENT_ID, function (token, err) {
    if(err){
        console.log(err);
    }

    searchGrimoire();
    searchCard();
    searchItems();

});<|endoftext|>


<commit_before>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const yaml = require('js-yaml')
const config = require('./config')
const dotenv = require('dotenv')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online');
  // bot.user.setActivity('Generating Code');
  bot.setStreaming('Call of Duty: Black Ops 10', 'https://www.twitch.tv/klendigocci', 1);
})

exports.bot = bot
exports.config = config
exports.commands = {
  master: {},
  moderator: {},
  default: {},
  dm: {}
}

registerCommand = function (name, type, callback, aliases, description, usage) {
  exports.commands[type][name] = {}
  exports.commands[type][name]['aliases'] = aliases
  exports.commands[type][name]['description'] = description
  exports.commands[type][name]['usage'] = usage
  exports.commands[type][name]['process'] = callback
}

var loadScript = (path, reload) => {
  var req = require(path)
  if (reload) {
    console.log('Reloaded script at ' + path)
  } else {
    console.log('Script loaded at ' + path)
  }
}
exports.registerCommand = registerCommand
exports.loadScript = loadScript

var commands = fs.readdirSync('./commands/')
commands.forEach(script => {
  if (script.substring(script.length - 3, script.length) === '.js') {
    exports.loadScript('./commands/' + script)
  }
})

var modules = fs.readdirSync('./modules/')
modules.forEach(script => {
  if (script.substring(script.length - 3, script.length) === '.js') {
    loadScript('./modules/' + script)
  }
})

bot.login(process.env.BOT_TOKEN)<commit_msg>:zap: Changes for testing<commit_after>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const yaml = require('js-yaml')
const config = require('./config')
const dotenv = require('dotenv')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online');
  bot.user.setActivity('Generating Code');
})

exports.bot = bot
exports.config = config
exports.commands = {
  master: {},
  moderator: {},
  default: {},
  dm: {}
}

registerCommand = function (name, type, callback, aliases, description, usage) {
  exports.commands[type][name] = {}
  exports.commands[type][name]['aliases'] = aliases
  exports.commands[type][name]['description'] = description
  exports.commands[type][name]['usage'] = usage
  exports.commands[type][name]['process'] = callback
}

var loadScript = (path, reload) => {
  var req = require(path)
  if (reload) {
    console.log('Reloaded script at ' + path)
  } else {
    console.log('Script loaded at ' + path)
  }
}
exports.registerCommand = registerCommand
exports.loadScript = loadScript

var commands = fs.readdirSync('./commands/')
commands.forEach(script => {
  if (script.substring(script.length - 3, script.length) === '.js') {
    exports.loadScript('./commands/' + script)
  }
})

var modules = fs.readdirSync('./modules/')
modules.forEach(script => {
  if (script.substring(script.length - 3, script.length) === '.js') {
    loadScript('./modules/' + script)
  }
})

bot.login(process.env.BOT_TOKEN)<|endoftext|>


<commit_before>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const math = require('mathjs')
const config = require('./config')
const dotenv = require('dotenv')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
  console.log('Subiex is ready')
})

function isCommand(str, message) {
	return message.content.toLowerCase().startsWith(config.prefix + str)
}

/*bot.on('message', (message) =>  {
	if(message.content.startsWith(config.prefix))
	{
			try {
				switch (message.content) {
					case config.prefix + 'report':
						message.reply('I am online and working!')
	    				var time = Date.now()
	   					message.channel.send('Pew').then(m => m.edit('PING TOOK : **' + (Date.now() - time) + '** ms'))
	    				message.channel.send('This report was sent in :```' + new Date() + '```');
						break;
					case config.prefix + 'help':
						message.reply('Help goes here ...')
						break;
					case config.prefix + 'hello':
						message.channel.send('Hello there ' + message.author.username)
						break;

					default:
						message.reply('**INVALID COMMAND**')
				}

			}
			catch(ex) {console.log('The error is at switch statement : ' + ex.stack)}
	}
})*/

bot.on('message', (message) => {
	var args = message.content.split(/[ ]+/)

	if(isCommand('lorem', message)) {

		if(args.length === 1 || args.length > 2)
		{
			message.reply('Please define a argument for lorem command , ```Usage : lorem [paragraphs number]```');
		}
		else if(args.length === 2)
		{
			message.channel.send('Lorem ipsum text ready to paste')
			var text = generateLoremText(args[1])
			message.reply('```' + text + '```')
		}
	}
})

////////////////////////////////////////////////////LOREM IPSUM GENERATOR TEST///////
try
{
var loremText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti, sunt laborum eum adipisci odio doloribus sit officia expedita. Nihil porro hic, sint voluptate unde accusantium molestias tenetur, laudantium reprehenderit amet dolore voluptas? Laudantium sunt autem aliquam nesciunt maxime nostrum ipsum alias doloribus. Numquam animi veniam impedit recusandae, deserunt facere. Debitis.";
var points = [',', '.', '?', '!', '?!']

function getRandom(min, max) {
	return Math.random() * (max - min) + min
}

function generateLoremText(num) {
	var wordsArray = []

	for (var i = 0; i < num; i++) {

		wordsArray[i] += loremText.toLowerCase().split(' ')
	}
	var word

	for (var i = 0; i < num; i++) {
		if(i === 1)
		{
			word += "Lorem"
			word += " ipsum "
		}

		if (i > 2) {
			var wArray = []
			wArray = wordsArray.join(' ')
			word += wArray[getRandom(2, num)]
			var rand = getRandom(1, 25)
			if (rand === 10)
			{
				word += points[getRandom(0, points.length)]
			}
		}
	}

	return word;
}
}
catch(ex) {
console.log('Error at lorem ipsum generator ' + ex.stack)
}
/////////////////////////////////////////////

bot.login(process.env.BOT_TOKEN)<commit_msg>fixStuffagain<commit_after>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const math = require('mathjs')
const config = require('./config')
const dotenv = require('dotenv')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
  console.log('Subiex is ready')
})

function isCommand(str, message) {
	return message.content.toLowerCase().startsWith(config.prefix + str)
}

/*bot.on('message', (message) =>  {
	if(message.content.startsWith(config.prefix))
	{
			try {
				switch (message.content) {
					case config.prefix + 'report':
						message.reply('I am online and working!')
	    				var time = Date.now()
	   					message.channel.send('Pew').then(m => m.edit('PING TOOK : **' + (Date.now() - time) + '** ms'))
	    				message.channel.send('This report was sent in :```' + new Date() + '```');
						break;
					case config.prefix + 'help':
						message.reply('Help goes here ...')
						break;
					case config.prefix + 'hello':
						message.channel.send('Hello there ' + message.author.username)
						break;

					default:
						message.reply('**INVALID COMMAND**')
				}

			}
			catch(ex) {console.log('The error is at switch statement : ' + ex.stack)}
	}
})*/

bot.on('message', (message) => {
	var args = message.content.split(/[ ]+/)

	if(isCommand('lorem', message)) {

		if(args.length === 1 || args.length > 2)
		{
			message.reply('Please define a argument for lorem command , ```Usage : lorem [paragraphs number]```');
		}
		else if(args.length === 2)
		{
			message.channel.send('Lorem ipsum text ready to paste')
			var text = generateLoremText(args[1])
			message.reply('```' + text + '```')
		}
	}
})

////////////////////////////////////////////////////LOREM IPSUM GENERATOR TEST///////
try
{
var loremText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti, sunt laborum eum adipisci odio doloribus sit officia expedita. Nihil porro hic, sint voluptate unde accusantium molestias tenetur, laudantium reprehenderit amet dolore voluptas? Laudantium sunt autem aliquam nesciunt maxime nostrum ipsum alias doloribus. Numquam animi veniam impedit recusandae, deserunt facere. Debitis.";
var points = [',', '.', '?', '!', '?!']

function getRandom(min, max) {
	return Math.random() * (max - min) + min
}

function generateLoremText(num) {
	var wordsArray = []

	wordsArray = loremText.split(' ')

	var word

	for (var i = 0; i < num; i++) {
		if(i === 1)
		{
			word += "Lorem"
			word += " ipsum "
		}

		if (i > 2) {
			var wArray = []
			wArray = wordsArray.join(' ')
			word += wArray[getRandom(2, num)]
			var rand = getRandom(1, 10)
			if (rand === 10)
			{
				word += points[getRandom(0, points.length)]
			}
		}
	}

	return word;
}
}
catch(ex) {
console.log('Error at lorem ipsum generator ' + ex.stack)
}
/////////////////////////////////////////////

bot.login(process.env.BOT_TOKEN)<|endoftext|>


<commit_before>var Twit = require('twit');
var twitInfo = require('./config.js');

var twitter = new Twit(twitInfo);

function postTweet() {

  var tweet = {
    status: "I am a test tweet, numero " + r + " #bot"
  };

  twitter.post('statuses/update', tweet , function(err, data, response) {
    if (err) {
      console.log("5OMeTh1nG weNt wR0ng");
    } else {
      console.log("Tweet sucessful");
    }
  });
}

var useUpperCase = function(wordList) {
  var tempList = Object.keys(wordList).filter(function(word) {
    return word[0] >= "A" && word[0] <= "Z";
  });
  return tempList[~~(Math.random()*tempList.length)];
};

// Can return to later. Need to configure things so the end command takes the word list as a variable, not the sentence
// var findEndWord = function(wordList) {
//   var tempList = Object.keys(wordList).filter(function(word) {
//     return word[word.length - 1] === "." ;
//   });
//   var whatever =  tempList[~~(Math.random()*tempList.length)];
//   return whatever;
// };

// V. difficult to implement with current configuration.
// var setTweetLength = function(sentence) {
//   // var tweetLength = Math.floor(Math.random() * 120-101) + 100;
//   sentence.split("").length >= 120;
// }

var MarkovChain = require('markovchain')
  , fs = require('fs')
  , quotes = new MarkovChain(fs.readFileSync('./rabelais.txt', 'utf8'));
// end the sentence if, after 4 words, the next word is an end word
// or end after
// will continue to churn out sentences, only end it when it finds one that returns a truthy on the end
var sentence = quotes.start(useUpperCase).end(Math.floor((Math.random() * 3) + 6)).process() + ".";

// postTweet();
// second parameter is in miliseconds
// setInterval(postTweet, 1000*60*60*3);<commit_msg>Delete unnecessary code<commit_after>var Twit = require('twit');
var twitInfo = require('./config.js');

var twitter = new Twit(twitInfo);

function postTweet() {

  var tweet = {
    status: "I am a test tweet, numero " + r + " #bot"
  };

  twitter.post('statuses/update', tweet , function(err, data, response) {
    if (err) {
      console.log("5OMeTh1nG weNt wR0ng");
    } else {
      console.log("Tweet sucessful");
    }
  });
}

var useUpperCase = function(wordList) {
  var tempList = Object.keys(wordList).filter(function(word) {
    return word[0] >= "A" && word[0] <= "Z";
  });
  return tempList[~~(Math.random()*tempList.length)];
};

var MarkovChain = require('markovchain')
  , fs = require('fs')
  , quotes = new MarkovChain(fs.readFileSync('./rabelais.txt', 'utf8'));

var sentence = quotes.start(useUpperCase).end(Math.floor((Math.random() * 3) + 6)).process() + ".";

// postTweet();
// second parameter is in miliseconds
// setInterval(postTweet, 1000*60*60*3);<|endoftext|>


<commit_before>/*
	MSS-Discord
	Copyright (C) 2017 moustacheminer.com

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

//Get the Discord API Key.
console.log(process.argv[2]);
if (process.argv[2]) {
	var api = process.argv[2];
} else {
	console.log("Usage:\nnode bot.js <Discord API Key>");
	process.exit(1);
}

//Declare the Discord and client constants used to set up the Discord bot
const Discord = require("discord.js");
const client = new Discord.Client();

//ytdl-core for !play
const yt = require('ytdl-core');

//fs to open the wav file
const fs = require('fs');

//exec for the DECtalk API
const child_process = require('child_process');

//Login to Discord's Bot API Service
client.login(api);

//Declare the playlist and stream variables
//playlist[guild][position in playlist]
var playlist = [];
//stream[guild]
var stream = [];

//Set the running game and the avatar for the bot.
client.on('ready', function() {
	console.log("Successfully connected to Discord!");
	client.user.setGame("ask for >>   !help");
	client.user.setAvatar("http://moustacheminer.com/dickbutt.jpg");
});

client.on('message', message => {

	try {
		//Stop checking if the message is from a bot - Don't repeat the !ping Pong!
		if(message.author.bot) return;

		let input = message.content.replace( /\n/g, " " ).split(" ");

		//Set the username of the bot as MSS
		if (message.guild) {
			message.guild.member(client.user).setNickname('MSS');
		} else {
			//If the bot is not in the server, stop doing shit - It's too dangerous.
			return richSend(message, "Error", "You are not allowed to send commands via Direct Messaging.", "#FF0000");
		}

		//Send help detials. Need to use the E-zed richSend someday
		if (input[0] === '!help') {
			richSend(message, "Moustacheminer Server Services", "Help is at hand, at the official MSS Discord Server @ https://discord.gg/hPw5gEt", "#FF9999", "http://i.imgur.com/h2JkYGm.jpg", "https://discord.gg/hPw5gEt");
		} else if (input[0] === '!play') {
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;
			//Check if the user is inside a voice channel
			if (!voiceChannel) {
				return richSend(message, input[0], "Please be in a voice channel before using the " + input[0] + " command", "#FFFF00");
			}

			if (youtubeCheck(input[1])) {
				yt.getInfo(input[1], function(err, info) {
					if (!info) {
						return richSend(message, "!play", "Please send a valid YouTube URL", "#FF0000");
					}

					playlistAdd(message, "youtube", input[1], info["title"], info["thumbnail_url"]);
				});

			} else {
				console.log(input[1]);
			}
		} else if (input[0] === '!skip') {
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;
			//Check if the user is inside a voice channel
			if (!voiceChannel.connection) {
				return richSend(message, "!stop", "There is no bot running in your current voice channel", "#FF0000");
			}

			stream[message.guild].destroy();
		} else if (input[0] === '!stop') {
			playlistClear(message);
		} else if (input[0].toLowerCase().split('').filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('') === "cirletn"){
			//Remove all repeated characters and check if it matches 'cirletn'
			return richSend(message, "Circletine", "CCCCCCCCCCCIIIIIIIIIIIIIIIIIRRRRRRRRRRRRRRRRRRRRRRRRCCCCCCCCCCCCCCCCCCCCCCLLLLLLLLLLLLLLLLLLEEEEEEEEEEEEEEETTTTTTTTTTTTTTTTTTIIIIIIIIIIIIIINNNNNNNNNNNNNNEEEEEEEEEEE", "#FFFFFF");
		} else if (message.content === 'sexual tension') {
			//Send a fancy image.
			return richSend(message, "sexual tension", "sexual tension", "#FF9999", "http://moustacheminer.com/download/sexualtension2.png");
		} else if (input[0] === '!dec') {
			let dec = message.content.substring(5).replace("\n", " ");
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;

			//Check if the user is inside a voice channel
			if (!voiceChannel) {
				return richSend(message, "!dec", "Please be in a voice channel before using the !dec command", "#FFFF00");
			}

			var file = Math.floor(Math.random() * 9999);
			child_process.execFile('say', ['-w', 'C:\\MOUSTACHEMINER\\NodeJS\\MSS-Discord\\DEC\\' + file + '.wav', dec]);
			playlistAdd(message, "file", 'C:\\MOUSTACHEMINER\\NodeJS\\MSS-Discord\\DEC\\' + file + '.wav', "DecTalk Input");
		} else if (input[0] === '!error') {
			throw new Error("A error was PURPOSELY thrown for the excitement of mathematicians.");
		}
	} catch(err) {
		console.log(err.stack);
		//Catch those errors!
		richSend(message, "This is a Parker Square of an error.", "A fatal error was encountered:\nKeep Calm. A singing banana has been deployed to fix the error. In the meantime, try folding a piece of A4 paper 8 times.", "#FF0000", "http://moustacheminer.com/home/img/ffs.jpg", "https://discord.gg/ZW7GGGH");
	}

});

//Provide an easy wrapper for Discord and Discord API's and Discord.js' RichEmbed feature
function richSend(message, subheading, description, colour, img, url) {
	if (!url) {
		var url = "http://moustacheminer.com/w/mss";
	}

	var embed = new Discord.RichEmbed()
		.setTitle(subheading)
		.setAuthor("MSS", 'http://moustacheminer.com/dickbutt.jpg')
		.setColor(colour)
		.setDescription(description)
		.setFooter('moustacheminer.com server services', '')
		.setTimestamp()
		.setURL(url)
		.setImage(img);

	message.channel.sendEmbed(embed, "", { disableEveryone: true });
}

function playlistAdd(message, type, url, title, thumb_url) {
	if (!thumb_url) {
		thumb_url = "http://i48.tinypic.com/260v86c.png";
	}

	richSend(message, "!play", "Added " + title + " to playlist", "#00FF00");
	playlist[message.guild] = playlist[message.guild] || [];
	playlist[message.guild].push(JSON.stringify({type: type, url: url, title: title, thumb_url: thumb_url}));
	if (!message.member.voiceChannel.connection) {
		playSound(message);
	}
}

function playlistClear(message) {
	//Check if the person has permission to stop the music
	if (!(message.channel.permissionsFor(message.member).hasPermission("ADMINISTRATOR") || message.author.id === "190519304972664832")) {
		return richSend(message, "!stop", "You do not have permission to stop the bot.", "#FF0000");
	}

	//Get the voice channel
	let voiceChannel = message.member.voiceChannel;

	//If the person is in the voice channel, stop the bot in that channel
	if (voiceChannel && voiceChannel.connection) {
		richSend(message, "!stop", "Stopped playing music in the channel.", "#00FF00");
		return voiceChannel.leave();
		playlist[message.guild] = [];
	} else {
		return richSend(message, "!stop", "There is no bot running in your current voice channel", "#FF0000");
	}
}

function playSound(message) {
	var voiceChannel = message.member.voiceChannel;
	var current;

	voiceChannel.join()
	.then(connnection => {
		var looper = function() {
			if (playlist[message.guild].length > 0) {
				playlistPlay(message);
				const dispatcher = connnection.playStream(stream[message.guild]);
				dispatcher.on('end', () => {
					looper();
				});
			} else {
				voiceChannel.leave();
				return;
			}
		}
		looper();
	});
}

function playlistPlay(message) {
	var voiceChannel = message.member.voiceChannel;
	if (playlist[message.guild].length > 0) {
		current = JSON.parse(playlist[message.guild].shift());
		richSend(message, "Now playing:", current["title"], "#00FF00", current["thumb_url"], current["url"]);
		if (current["type"] === "youtube") {
			stream[message.guild] = yt(current["url"], {audioonly: true});
		} else if (current["type"] === "file") {
			stream[message.guild] = stream = fs.createReadStream(current["url"])
		}
	} else {
		voiceChannel.leave();
		return;
	}
}

/**
 * JavaScript function to match (and return) the video Id
 * of any valid Youtube Url, given as input string.
 * @author: Stephan Schmitz <eyecatchup@gmail.com>
 * @url: http://stackoverflow.com/a/10315969/624466
 */
function youtubeCheck(url) {
  var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  return (url.match(p)) ? RegExp.$1 : false;
}
<commit_msg>Fully cleared playlist on exit<commit_after>/*
	MSS-Discord
	Copyright (C) 2017 moustacheminer.com

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

//Get the Discord API Key.
console.log(process.argv[2]);
if (process.argv[2]) {
	var api = process.argv[2];
} else {
	console.log("Usage:\nnode bot.js <Discord API Key>");
	process.exit(1);
}

//Declare the Discord and client constants used to set up the Discord bot
const Discord = require("discord.js");
const client = new Discord.Client();

//ytdl-core for !play
const yt = require('ytdl-core');

//fs to open the wav file
const fs = require('fs');

//exec for the DECtalk API
const child_process = require('child_process');

//Login to Discord's Bot API Service
client.login(api);

//Declare the playlist and stream variables
//playlist[guild][position in playlist]
var playlist = [];
//stream[guild]
var stream = [];

//Set the running game and the avatar for the bot.
client.on('ready', function() {
	console.log("Successfully connected to Discord!");
	client.user.setGame("ask for >>   !help");
	client.user.setAvatar("http://moustacheminer.com/dickbutt.jpg");
});

client.on('message', message => {

	try {
		//Stop checking if the message is from a bot - Don't repeat the !ping Pong!
		if(message.author.bot) return;

		let input = message.content.replace( /\n/g, " " ).split(" ");

		//Set the username of the bot as MSS
		if (message.guild) {
			message.guild.member(client.user).setNickname('Moustacheminer Server Services');
		} else {
			//If the bot is not in the server, stop doing shit - It's too dangerous.
			return richSend(message, "Error", "You are not allowed to send commands via Direct Messaging.", "#FF0000");
		}

		//Send help detials. Need to use the E-zed richSend someday
		if (input[0] === '!help') {
			richSend(message, "Moustacheminer Server Services", "Help is at hand, at the official MSS Discord Server @ https://discord.gg/hPw5gEt", "#FF9999", "http://i.imgur.com/h2JkYGm.jpg", "https://discord.gg/hPw5gEt");
		} else if (input[0] === '!play') {
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;
			//Check if the user is inside a voice channel
			if (!voiceChannel) return richSend(message, input[0], "Please be in a voice channel before using the " + input[0] + " command", "#FFFF00");
			if (!input[1]) return richSend(message, input[0], "Please insert a VALID url.", "#FF0000");

			if (youtubeCheck(input[1])) {
				yt.getInfo(input[1], function(err, info) {
					if (!info) return richSend(message, "!play", "Please send a valid YouTube URL", "#FF0000");
					if (info["length_seconds"] > 3600 && isAdmin(message)) return;
					playlistAdd(message, "youtube", input[1], info["title"], info["thumbnail_url"]);
				});
			} else {
				console.log(input[1]);
				richSend(message, input[0], "The URL is currently NOT supported by Moustacheminer Server Services.", "#FF0000");
			}
		} else if (input[0] === '!skip') {
			if (!isAdmin(message)) return;
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;
			//Check if the user is inside a voice channel
			if (!voiceChannel.connection) {
				return richSend(message, "!stop", "There is no bot running in your current voice channel", "#FF0000");
			}

			stream[message.guild].destroy();
		} else if (input[0] === '!stop') {
			if (!isAdmin(message)) return;
			playlistClear(message);
		} else if (input[0] === '!dec') {
			let dec = message.content.substring(5).replace("\n", " ");
			//Get the voice channel that it's going to play to.
			let voiceChannel = message.member.voiceChannel;

			//Check if the user is inside a voice channel
			if (!voiceChannel) {
				return richSend(message, "!dec", "Please be in a voice channel before using the !dec command", "#FFFF00");
			}

			var file = Math.floor(Math.random() * 9999);
			child_process.execFile('say', ['-w', 'C:\\MOUSTACHEMINER\\NodeJS\\MSS-Discord\\DEC\\' + file + '.wav', dec]);
			playlistAdd(message, "file", 'C:\\MOUSTACHEMINER\\NodeJS\\MSS-Discord\\DEC\\' + file + '.wav', "DecTalk Input");
		} else if (input[0] === '!error') {
			if (!isAdmin(message)) return;
			throw new Error("A error was PURPOSELY thrown for the excitement of mathematicians.");
		}
	} catch(err) {
		console.log(err.stack);
		//Catch those errors!
		richSend(message, "This is a Parker Square of an error.", "A fatal error was encountered:\n```\n" + err.stack + "\n```\nA singing banana has been deployed to fix the error. In the meantime, try folding a piece of A4 paper 8 times.", "#FF0000", "http://moustacheminer.com/home/img/ffs.jpg", "https://discord.gg/hPw5gEt");
	}

});

//Provide an easy wrapper for Discord and Discord API's and Discord.js' RichEmbed feature
function richSend(message, subheading, description, colour, img, url) {
	if (!url) {
		var url = "http://moustacheminer.com/w/mss";
	}

	var embed = new Discord.RichEmbed()
		.setTitle(subheading)
		.setAuthor("MSS", 'http://moustacheminer.com/dickbutt.jpg')
		.setColor(colour)
		.setDescription(description)
		.setFooter('moustacheminer.com server services', '')
		.setTimestamp()
		.setURL(url)
		.setImage(img);

	message.channel.sendEmbed(embed, "", { disableEveryone: true });
}

function playlistAdd(message, type, url, title, thumb_url) {
	if (!thumb_url) {
		thumb_url = "http://i48.tinypic.com/260v86c.png";
	}

	richSend(message, "!play", "Added " + title + " to playlist", "#00FF00");
	playlist[message.guild] = playlist[message.guild] || [];
	playlist[message.guild].push(JSON.stringify({type: type, url: url, title: title, thumb_url: thumb_url}));
	if (!message.member.voiceChannel.connection) {
		playSound(message);
	}
}

function playlistClear(message) {
	//Get the voice channel
	let voiceChannel = message.member.voiceChannel;

	//If the person is in the voice channel, stop the bot in that channel
	if (voiceChannel && voiceChannel.connection) {
		richSend(message, "!stop", "Stopped playing music in the channel.", "#00FF00");
		voiceChannel.leave();
		playlist[message.guild] = [];
		stream[message.guild].destroy();
		return;
	} else {
		return richSend(message, "!stop", "There is no bot running in your current voice channel", "#FF0000");
	}
}

function playSound(message) {
	var voiceChannel = message.member.voiceChannel;
	var current;

	voiceChannel.join()
	.then(connnection => {
		var looper = function() {
			playlistPlay(message);
			const dispatcher = connnection.playStream(stream[message.guild]);
			dispatcher.on('end', () => {
				looper();
			});
		}
		looper();
	});
}

function playlistPlay(message) {
	var voiceChannel = message.member.voiceChannel;
	if (playlist[message.guild].length > 0) {
		current = JSON.parse(playlist[message.guild].shift());
		richSend(message, "Now playing:", current["title"], "#00FF00", current["thumb_url"], current["url"]);
		if (current["type"] === "youtube") {
			stream[message.guild] = yt(current["url"], {audioonly: true});
		} else if (current["type"] === "file") {
			stream[message.guild] = stream = fs.createReadStream(current["url"]);
		}
	} else {
		voiceChannel.leave();
		playlist[message.guild] = [];
		stream[message.guild].destroy();
		return;
	}
}

/**
 * JavaScript function to match (and return) the video Id
 * of any valid Youtube Url, given as input string.
 * @author: Stephan Schmitz <eyecatchup@gmail.com>
 * @url: http://stackoverflow.com/a/10315969/624466
 */
function youtubeCheck(url) {
  var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  return (url.match(p)) ? RegExp.$1 : false;
}

function isAdmin(message) {
	if (message.channel.permissionsFor(message.member).hasPermission("ADMINISTRATOR") || message.author.id === "190519304972664832") {
		return true;
	} else {
		richSend(message, "!stop", "You do not have permission to run this command.", "#FF0000");
		return false;
	}
}<|endoftext|>


<commit_before>// https://github.com/octokit/core.js#readme
const { Octokit } = require('@octokit/core');
const octokit = new Octokit({auth: process.env.GITHUB});
const constants = require('./constants.json');
const markdown = require('./audits/markdown.js');
// const psi = require('./audits/psi.js');
// const dom = require('./audits/dom.js');
const instructions = require('./instructions.json');
const words = require('./words.json');

// The keys of this object match the names of the relevant GitHub webhook event
// that we're responding to.
const actions = {
  // Pull request was opened.
  opened: data => {
    audit(data.number);
  },
  // A new comment was created on the pull request.
  created: data => {
    // TODO(kaycebasques): Check if it was Netlify and only re-run audit if so.
    audit(data.issue.number);
  },
  // A comment on the pull request was edited.
  edited: data => {
    audit(data.issue.number)
  },
  // Some of the code in the pull request changed.
  synchronize: data => {
    audit(data.number);
  }
};

const audit = async number => {
  // Store data about the pull request.
  let data = {
    files: {},
    number
  };
  // Get the files that are affected by the pull request.
  let files = [];
  let response;
  let page = 1;
  do {
    response = await octokit.request({
      method: 'GET',
      url: `/repos/googlechrome/web.dev/pulls/${number}/files?page=${page}`
    });
    files = files.concat(response.data);
    page += 1;
  } while (response.data.length === 30);
  // Check for new content, modified content, or images.
  // TODO(kaycebasques): Refactor to first gather content files. Then filter for modified or added.
  const newContent =
      files.filter(file => file.status === constants.files.added &&
          file.filename.toLowerCase().endsWith('.md'));
  const modifiedContent =
      files.filter(file => file.status === constants.files.modified &&
          file.filename.toLowerCase().endsWith('.md'));

  const images =
      files.filter(file => file.filename.toLowerCase().endsWith('.png') ||
          file.filename.toLowerCase().endsWith('.jpg'));
  // Bail if the PR doesn't touch any content files.
  if (newContent.length === 0 && modifiedContent.length === 0) return;

  // Function for converting Markdown files that the PR is creating/editing into URLs.
  const getStagingUrl = (number, path) => {
    const s1 = path.substring(0, path.lastIndexOf('/'));
    const s2 = s1.substring(s1.lastIndexOf('/') + 1);
    return `https://deploy-preview-${number}--web-dev-staging.netlify.app/${s2}/`;
  };

  // Store data about the new or modified content.
  if (newContent.length > 0) {
    newContent.forEach(file => {
      data.files[file.filename] = {
        status: constants.files.added,
        url: getStagingUrl(number, file.filename),
        raw: file.raw_url,
        audits: {}
      };
    });
  }
  if (modifiedContent.length > 0) {
    modifiedContent.forEach(file => {
      data.files[file.filename] = {
        status: constants.files.modified,
        url: getStagingUrl(number, file.filename),
        raw: file.raw_url,
        audits: {}
      };
    });
  }

  // Audit the files.
  for (const path in data.files) {
    const file = data.files[path];
    file.audits.markdown = await markdown.audit(file.raw, path);
  }

  // Get the comments on the pull request.
  const comments = await octokit.request({
    accept: 'application/vnd.github.v3+json',
    method: 'GET',
    url: `/repos/googlechrome/web.dev/issues/${number}/comments`
  });
  // Check for the auto-generated staging URLs comment.
  const shouldShowStagingUrls =
      comments.data.filter(comment => comment.body.includes(constants.comments.staging)).length > 0;

  // Function for creating the automated comment.
  const createComment = (data, showStagingUrls) => {
    const createStagingUrlsContent = data => {
      let comment = '## Staging URLs\n\n';
      comment += 'For your convenience, here are direct links (on our staging site) to the content you created or updated:\n\n';
      for (const path in data.files) {
        const file = data.files[path];
        comment += `* ${file.url}\n`;
      }
      return comment;
    };
    const createFileContent = (pathname, data) => {
      let content = `### \`${pathname}\`\n\n`;
      let sentinel = true;
      for (const key in data.audits.markdown) {
        const audit = data.audits.markdown[key];
        if (!audit.pass) {
          if (key === 'words') {
            content += `* ${instructions[key]}\n`;
            for (const word in data.audits.markdown[key]) {
              if (word === 'pass') continue;
              content += `  * ${words[word].instruction} Affected lines: ${data.audits.markdown[key][word].join(', ')}\n`;
            }
          } else {
            content += `* ${instructions[key]} Affected lines: ${audit.lines.join(', ')}\n`;
          }
          sentinel = false;
        }
      }
      if (sentinel) content += '* This file passed all of our automated Markdown audits.\n\n';
      return content;
    };
    let comment = 'Hello! This is an automated review by our custom [reviewbot](https://github.com/kaycebasques/reviewbot). It updates automatically when code or GitHub comments in this pull request are created or updated.\n\n';
    if (process.env.DEV) comment += 'THIS IS A DEVELOPMENT BUILD OF REVIEWBOT.\n\n';
    if (showStagingUrls) comment += createStagingUrlsContent(data);
    comment += '## Requested changes\n\n';
    comment += 'If there are any common problems with the content files you created or modified, they will be listed here.\n\n';
    for (const path in data.files) {
      comment += createFileContent(path, data.files[path]);
    }
    comment += `<!-- Comment ID: ${constants.comments.reviewbot} -->`;
    return comment;
  };

  async function updatePullRequest() {
    // Create the comment if it doesn't exist.
    if (reviewBotComment.length === 0) {
      await octokit.request({
        accept: 'application/vnd.github.v3+json',
        method: 'POST',
        url: `/repos/googlechrome/web.dev/issues/${data.number}/comments`,
        body: createComment(data, shouldShowStagingUrls)
      });
    }
    // Otherwise just update it.
    if (reviewBotComment.length === 1) {
      await octokit.request({
        accept: 'application/vnd.github.v3+json',
        method: 'PATCH',
        url: `/repos/googlechrome/web.dev/issues/comments/${reviewBotComment[0].id}`,
        body: createComment(data, shouldShowStagingUrls)
      });
    }
  }

  // Check for the auto-generated reviewbot comment.
  const reviewBotComment = comments.data.filter(comment => {
    return comment.body.includes(constants.comments.reviewbot);
  });

  // Check for the auto-generated reviewbot comment.
  const devComment = comments.data.filter(comment => {
    return comment.body.includes(constants.comments.dev);
  });

  if (devComment && !process.env.DEV) {
    // Do nothing because we have indicated (through devComment)
    // that we're using this PR for development/debugging. And
    // since process.env.DEV is false it means this is the production
    // version of reviewbot. We don't want the production reviewbot
    // interfering with our development/debugging PR.
  }

  if (devComment && process.env.DEV) {
    // It's a dev/debug PR, but we're running the DEV version of reviewbot.
    // Therefore we should update the PR in order to test our changes.
    updatePullRequest();
  }

  if (!devComment) {
    // It's not a dev/debug PR. The production version of reviewbot
    // should update the PR.
    updatePullRequest();
  }

  // Return the final data. Only for debugging purposes.
  return data;
};

module.exports = {
  actions,
  audit
}<commit_msg>Attempted fixes for dev/debug logic<commit_after>// https://github.com/octokit/core.js#readme
const { Octokit } = require('@octokit/core');
const octokit = new Octokit({auth: process.env.GITHUB});
const constants = require('./constants.json');
const markdown = require('./audits/markdown.js');
// const psi = require('./audits/psi.js');
// const dom = require('./audits/dom.js');
const instructions = require('./instructions.json');
const words = require('./words.json');

// The keys of this object match the names of the relevant GitHub webhook event
// that we're responding to.
const actions = {
  // Pull request was opened.
  opened: data => {
    audit(data.number);
  },
  // A new comment was created on the pull request.
  created: data => {
    if (!data.issue) return;
    audit(data.issue.number);
  },
  // A comment on the pull request was edited.
  edited: data => {
    if (!data.issue) return;
    audit(data.issue.number)
  },
  // Some of the code in the pull request changed.
  synchronize: data => {
    audit(data.number);
  }
};

const audit = async number => {
  // Store data about the pull request.
  let data = {
    files: {},
    number
  };
  // Get the files that are affected by the pull request.
  let files = [];
  let response;
  let page = 1;
  do {
    response = await octokit.request({
      method: 'GET',
      url: `/repos/googlechrome/web.dev/pulls/${number}/files?page=${page}`
    });
    files = files.concat(response.data);
    page += 1;
  } while (response.data.length === 30);
  // Check for new content, modified content, or images.
  // TODO(kaycebasques): Refactor to first gather content files. Then filter for modified or added.
  const newContent =
      files.filter(file => file.status === constants.files.added &&
          file.filename.toLowerCase().endsWith('.md'));
  const modifiedContent =
      files.filter(file => file.status === constants.files.modified &&
          file.filename.toLowerCase().endsWith('.md'));

  const images =
      files.filter(file => file.filename.toLowerCase().endsWith('.png') ||
          file.filename.toLowerCase().endsWith('.jpg'));
  // Bail if the PR doesn't touch any content files.
  if (newContent.length === 0 && modifiedContent.length === 0) return;

  // Function for converting Markdown files that the PR is creating/editing into URLs.
  const getStagingUrl = (number, path) => {
    const s1 = path.substring(0, path.lastIndexOf('/'));
    const s2 = s1.substring(s1.lastIndexOf('/') + 1);
    return `https://deploy-preview-${number}--web-dev-staging.netlify.app/${s2}/`;
  };

  // Store data about the new or modified content.
  if (newContent.length > 0) {
    newContent.forEach(file => {
      data.files[file.filename] = {
        status: constants.files.added,
        url: getStagingUrl(number, file.filename),
        raw: file.raw_url,
        audits: {}
      };
    });
  }
  if (modifiedContent.length > 0) {
    modifiedContent.forEach(file => {
      data.files[file.filename] = {
        status: constants.files.modified,
        url: getStagingUrl(number, file.filename),
        raw: file.raw_url,
        audits: {}
      };
    });
  }

  // Audit the files.
  for (const path in data.files) {
    const file = data.files[path];
    file.audits.markdown = await markdown.audit(file.raw, path);
  }

  // Get the comments on the pull request.
  const comments = await octokit.request({
    accept: 'application/vnd.github.v3+json',
    method: 'GET',
    url: `/repos/googlechrome/web.dev/issues/${number}/comments`
  });
  // Check for the auto-generated staging URLs comment.
  const shouldShowStagingUrls =
      comments.data.filter(comment => comment.body.includes(constants.comments.staging)).length > 0;

  // Function for creating the automated comment.
  const createComment = (data, showStagingUrls) => {
    const createStagingUrlsContent = data => {
      let comment = '## Staging URLs\n\n';
      comment += 'For your convenience, here are direct links (on our staging site) to the content you created or updated:\n\n';
      for (const path in data.files) {
        const file = data.files[path];
        comment += `* ${file.url}\n`;
      }
      return comment;
    };
    const createFileContent = (pathname, data) => {
      let content = `### \`${pathname}\`\n\n`;
      let sentinel = true;
      for (const key in data.audits.markdown) {
        const audit = data.audits.markdown[key];
        if (!audit.pass) {
          if (key === 'words') {
            content += `* ${instructions[key]}\n`;
            for (const word in data.audits.markdown[key]) {
              if (word === 'pass') continue;
              content += `  * ${words[word].instruction} Affected lines: ${data.audits.markdown[key][word].join(', ')}\n`;
            }
          } else {
            content += `* ${instructions[key]} Affected lines: ${audit.lines.join(', ')}\n`;
          }
          sentinel = false;
        }
      }
      if (sentinel) content += '* This file passed all of our automated Markdown audits.\n\n';
      return content;
    };
    let comment = 'Hello! This is an automated review by our custom [reviewbot](https://github.com/kaycebasques/reviewbot). It updates automatically when code or GitHub comments in this pull request are created or updated.\n\n';
    if (process.env.DEV) comment += 'THIS IS A DEVELOPMENT BUILD OF REVIEWBOT.\n\n';
    if (showStagingUrls) comment += createStagingUrlsContent(data);
    comment += '## Requested changes\n\n';
    comment += 'If there are any common problems with the content files you created or modified, they will be listed here.\n\n';
    for (const path in data.files) {
      comment += createFileContent(path, data.files[path]);
    }
    comment += `<!-- Comment ID: ${constants.comments.reviewbot} -->`;
    return comment;
  };

  async function updatePullRequest() {
    // Create the comment if it doesn't exist.
    if (reviewBotComment.length === 0) {
      await octokit.request({
        accept: 'application/vnd.github.v3+json',
        method: 'POST',
        url: `/repos/googlechrome/web.dev/issues/${data.number}/comments`,
        body: createComment(data, shouldShowStagingUrls)
      });
    }
    // Otherwise just update it.
    if (reviewBotComment.length === 1) {
      await octokit.request({
        accept: 'application/vnd.github.v3+json',
        method: 'PATCH',
        url: `/repos/googlechrome/web.dev/issues/comments/${reviewBotComment[0].id}`,
        body: createComment(data, shouldShowStagingUrls)
      });
    }
  }

  // Check for the auto-generated reviewbot comment.
  const reviewBotComment = comments.data.filter(comment => {
    return comment.body.includes(constants.comments.reviewbot);
  });

  // Check for the auto-generated reviewbot comment.
  const devComment = comments.data.filter(comment => {
    return comment.body.includes(constants.comments.dev);
  }).length > 0;

  if (devComment && !process.env.DEV) {
    // Do nothing because we have indicated (through devComment)
    // that we're using this PR for development/debugging. And
    // since process.env.DEV is false it means this is the production
    // version of reviewbot. We don't want the production reviewbot
    // interfering with our development/debugging PR.
  }

  if (devComment && process.env.DEV) {
    // It's a dev/debug PR, but we're running the DEV version of reviewbot.
    // Therefore we should update the PR in order to test our changes.
    updatePullRequest();
  }

  if (!devComment) {
    // It's not a dev/debug PR. The production version of reviewbot
    // should update the PR.
    updatePullRequest();
  }

  // Return the final data. Only for debugging purposes.
  return data;
};

module.exports = {
  actions,
  audit
}<|endoftext|>