<commit_before>const Discord = require('discord.js');
const client = new Discord.Client();

const SteamCommunity = require('steamcommunity');
var community = new SteamCommunity();

const fs = require('fs');

var whoppl = JSON.parse(fs.readFileSync('./texts/whois.json').toString("utf-8"));

const hiddenppl = {
  "god": "me",
  "england": "my city"
};

var everyone = Object.keys(whoppl).join(", ");
var helpdocs = JSON.parse(fs.readFileSync('./texts/helpdocs.json').toString("utf-8"));
var jokes = (fs.readFileSync('./texts/jokes.txt').toString("utf-8").split("\n"));
for (let i = 0; i < jokes.length; i++) {
  while (jokes[i].includes("///"))
    jokes[i] = jokes[i].replace("///", "\n");
}

process.stdin.setEncoding('utf8');
var commands = {
  "UNKNOWN_COMMAND": function() {
    return "Unknown command. Type `help` for help.";
  },
  "reload": function() {
    whoppl = JSON.parse(fs.readFileSync('./texts/whois.json').toString("utf-8"));
    everyone = Object.keys(whoppl).join(", ");
    helpdocs = JSON.parse(fs.readFileSync('./texts/helpdocs.json').toString("utf-8"));
    jokes = (fs.readFileSync('./texts/jokes.txt').toString("utf-8").split("\n"));
    for (let i = 0; i < jokes.length; i++) {
      while (jokes[i].includes("///"))
        jokes[i] = jokes[i].replace("///", "\n");
    }
    return "Reloaded.";
  },
  "test": function() {
    console.log(jokes.join("\n"));
    return "yep";
  }
};
var anchorloc;
process.stdin.on('data', (text) => {
  var stuff;
  while (text.indexOf('\n') !== -1 || text.indexOf('\r') !== -1 || text.indexOf('  ') !== -1) {
    text = text.replace(/\n|\r|\t/, '').replace(/  /, ' ');
  }
  var args = text.split(' ');
  var command = args[0].toLowerCase();
  var trip = false;
  for (var key in commands) {
    if (key === command) {
      trip = true;
      stuff = commands[key](args[1], args[2], args[3]);
      if (Array.isArray(stuff)) {} else {
        console.log(stuff);
      }
    }
  }
  if (!trip) {
    stuff = commands.UNKNOWN_COMMAND();
    if (Array.isArray(stuff)) {
      for (var i = 0; i < stuff.length; i++) {
        console.log(stuff[i]);
      }
    } else {
      console.log(stuff);
    }
  }
});

function whois(person) {
  let trueppl = Object.assign({}, whoppl, hiddenppl);
  for (var key in trueppl) {
    if (person.toLowerCase() === key) {
      return person + " is " + trueppl[key];
    }
  }
}

client.on('ready', () => {
  console.log('Connected and initialized.');
});

function formatPrice(prices) {
  let ret = "";
  for (var i = 0; i < (prices.length < 5 ? prices.length : 5); i++) {
    ret += prices[i].market_hash_name + " costs $" + (prices[i].price / 100) + "\n";
  }
  return ret;
}

function getPrice(item, appid, cb) {
  community.marketSearch({
    query: item,
    appid
  }, (err, items) => {
    if (err) {
      cb(err.message);
    } else {
      cb(formatPrice(items));
    }
  });
}

function getImg(item, appid, cb, ecb) {
  if (item.toLowerCase() == "kairu") {
    cb("http://vignette1.wikia.nocookie.net/powerlisting/images/a/ad/Trap-image.png/revision/latest?cb=20160113212524");
    return;
  } else if (item.toLowerCase() == "livid") {
    cb("https://s.thestreet.com/files/tsc/v2008/photos/contrib/uploads/transoceanrig_600x400.jpg");
    return;
  } else if (item.toLowerCase() == "dank") {
    cb("http://st.motortrend.com/uploads/sites/10/2015/11/2015-nissan-juke-sl-suv-angular-front.png?interpolation=lanczos-none&fit=around|300;199");
    return;
  } else if (item.toLowerCase() == "yuna") {
    cb("http://i.imgur.com/5vDmod7.png");
    return;
  } else if (item.toLowerCase() == "abuse") {
    cb("https://cdn.discordapp.com/attachments/167586953061990400/364157623832150017/madman.png");
  }
  community.marketSearch({
    query: item,
    appid: appid
  }, (err, items) => {
    if (err) {
      ecb(err.message);
    } else {
      cb(items[0].image, items[0].market_hash_name);
    }
  });
}

function removeAll(str, rep) {
  while (str.includes(rep) === true) {
    str = str.replace(rep, "");
  }
  return str;
}

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function getRandomFromList(list) {
  return list[getRandomInt(0, list.length)];
}

function game(args) {

}

var lastsent = Date.now();

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

  if (message.author.bot === true) {
    return;
  }

  var loc = message.channel;
  var msg = removeAll(message.content, "?");

  let send = function(msg, opts) {
    if (lastsent + 1000 < Date.now()) {
      lastsent = Date.now();
      loc.send(msg, opts);
    } else {

    }
  };

  let sendimg = function(img, text) {
    send(text, {
      embed: new Discord.RichEmbed().setImage(img)
    });
  };

  let mroles = message.member.roles.array();
  let ismod = false;
  for (let i = 0; i < mroles.length; i++) {
    if (mroles[i].name.includes("Mod")) {
      ismod = true;
    }
  }

  if (msg.toLowerCase().includes("drakemoon.com/promo-code/")) {
    message.delete();
    return;
  }

  if (msg == "!info") {
    send("I'm a bot run by Charred. https://github.com/charredgrass/raocsgo-discord-bot");
  }
  if (msg == "!ping") {
    send("Pong.");
  }
  if (msg.toLowerCase().match(/([^a-zA-Z]|^)osu/)) {
    send("We get it, you're a weeb.");
  }
  if (msg.toLowerCase() === "!whatthefuck" || msg.toLowerCase() === "!what") {
    send("https://docs.google.com/document/d/1u0-YAZG7Rv7P9N94vKEGocvJccGlDvK2RZxWMcg8pDA/edit?usp=sharing");
  }
  if (msg.toLowerCase().includes("trap")) {
    send('Traps? Ask Kairu about our Grade A Traps today!');
  }
  if (msg.toLowerCase() === "who am i") {
    send("None of your business.");
  }
  if (msg.toLowerCase() === "what is love") {
    send("Something you'll never feel.");
  }
  if (msg.toLowerCase() === "who are you" || msg.toLowerCase() === "who is bot charred") {
    send("You're fucking retarded.");
    return;
  }
  if (msg.toLowerCase() === "who is 为什么" || msg.toLowerCase() === "who is weishenme") {
    send("\"为什么\"是小孩子");
    return;
  }
  if (msg.toLowerCase() === "who is your daddy") {
    send("Charred is my daddy");
    return;
  }
  if (msg.substring(0, "who is everyone".length).toLowerCase() === "who is everyone") {
    send(everyone + ", 为什么");
  }
  if (msg.substring(0, "who is ".length).toLowerCase() === "who is ") {
    send(whois(msg.substring("who is ".length)));
  }
  if (msg.toLowerCase().includes("what is gambl")) {
    send("gamble is bad");
  }
  if (msg.toLowerCase() === "!source" || msg.toLowerCase() === "!sauce") {
    send("https://github.com/charredgrass/raocsgo-discord-bot");
  }
  if (msg.toLowerCase() === "!source2") {
    send("never");
  }
  if (msg.substring(0, "!joke".length).toLowerCase() === "!joke") {
    if (msg.split(" ").length > 1) {
      let x = parseInt(msg.substring("!joke ".length));
      if (x && x - 1 < jokes.length) {
        if (x == 69) {
          // send("")
        } else if (x == 0) {
          send("People who think arrays start at 1");
        } else {
          send(jokes[x - 1]);
        }
      } else if (x && x != 69) {
        send("People who think the bot has an unlimited number of jokes.");
      }
    } else {
      send(getRandomFromList(jokes));
    }
  }
  if (msg.substring(0, "!anchorloc".length).toLowerCase() === "!anchorloc") {
    anchorloc = loc;
    message.delete();
  }
  if (msg.substring(0, "!proxy".length).toLowerCase() === "!proxy") {
    if (message.author.id == "154826263628873728") {
      let toSay = msg.substring("!proxy ".length);
      if (anchorloc) {
        anchorloc.send(toSay);
      }
    }
  }
  if (msg.substring(0, "!priceof ".length).toLowerCase() === "!priceof ") {
    getPrice(msg.substring("!priceof ".length), 730, send);
  }
  if (msg.substring(0, "!priceofdota ".length).toLowerCase() === "!priceofdota ") {
    getPrice(msg.substring("!priceofdota ".length), 570, send);
  }
  if (msg.substring(0, "!priceoftf ".length).toLowerCase() === "!priceoftf ") {
    getPrice(msg.substring("!priceoftf ".length), 440, send);
  }
  if (msg.substring(0, "!priceofpubg ".length).toLowerCase() === "!priceofpubg ") {
    getPrice(msg.substring("!priceofpubg ".length), 578080, send);
  }
  if (msg.substring(0, "!imgof ".length).toLowerCase() === "!imgof ") {
    getImg(msg.substring("!imgof ".length), 730, sendimg, send);
  }
  if (msg.substring(0, "!imgofpubg ".length).toLowerCase() === "!imgofpubg ") {
    getImg(msg.substring("!imgofpubg ".length), 578080, sendimg, send);
  }
  if (msg.substring(0, "!magic8 ".length).toLowerCase() === "!magic8 ") {
    var answers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"];
    send(getRandomFromList(answers));
  }
  if (msg.substring(0, "!help".length).toLowerCase() === "!help") {
    var preargs = (msg.substring("!help".length).split(" "));
    let args = [];
    for (var i = 0; i < preargs.length; i++) {
      if (preargs[i] === "") {
        //kill space
      } else {
        args.push(preargs[i]);
      }
    }
    if (args.length === 0) {
      send("Valid commands: !help, !what, !priceof, !imgof, who is [person], !magic8, !info\nType \"!help help\" for more specific help.");
      if (helpdocs[args[0]]) {
        send(helpdocs[args[0]]);
      }
    } else {
      send("Unknown command. Type \"!help\" for help.");
    }
  }
});

client.login(fs.readFileSync('./key.txt').toString("utf-8"));  send(helpdocs[args[0]]);
      }
    } else {
      send("Unknown command. Type \"!help\" for help.");
    }
  }
});

client.login(fs.readFileSync('./key.txt').toString("utf-8"));<commit_msg>idk what the fuck happened<commit_after>const Discord = require('discord.js');
const client = new Discord.Client();

const SteamCommunity = require('steamcommunity');
var community = new SteamCommunity();

const fs = require('fs');

var whoppl = JSON.parse(fs.readFileSync('./texts/whois.json').toString("utf-8"));

const hiddenppl = {
  "god": "me",
  "england": "my city"
};

var everyone = Object.keys(whoppl).join(", ");
var helpdocs = JSON.parse(fs.readFileSync('./texts/helpdocs.json').toString("utf-8"));
var jokes = (fs.readFileSync('./texts/jokes.txt').toString("utf-8").split("\n"));
for (let i = 0; i < jokes.length; i++) {
  while (jokes[i].includes("///"))
    jokes[i] = jokes[i].replace("///", "\n");
}

process.stdin.setEncoding('utf8');
var commands = {
  "UNKNOWN_COMMAND": function() {
    return "Unknown command. Type `help` for help.";
  },
  "reload": function() {
    whoppl = JSON.parse(fs.readFileSync('./texts/whois.json').toString("utf-8"));
    everyone = Object.keys(whoppl).join(", ");
    helpdocs = JSON.parse(fs.readFileSync('./texts/helpdocs.json').toString("utf-8"));
    jokes = (fs.readFileSync('./texts/jokes.txt').toString("utf-8").split("\n"));
    for (let i = 0; i < jokes.length; i++) {
      while (jokes[i].includes("///"))
        jokes[i] = jokes[i].replace("///", "\n");
    }
    return "Reloaded.";
  },
  "test": function() {
    console.log(jokes.join("\n"));
    return "yep";
  }
};
var anchorloc;
process.stdin.on('data', (text) => {
  var stuff;
  while (text.indexOf('\n') !== -1 || text.indexOf('\r') !== -1 || text.indexOf('  ') !== -1) {
    text = text.replace(/\n|\r|\t/, '').replace(/  /, ' ');
  }
  var args = text.split(' ');
  var command = args[0].toLowerCase();
  var trip = false;
  for (var key in commands) {
    if (key === command) {
      trip = true;
      stuff = commands[key](args[1], args[2], args[3]);
      if (Array.isArray(stuff)) {} else {
        console.log(stuff);
      }
    }
  }
  if (!trip) {
    stuff = commands.UNKNOWN_COMMAND();
    if (Array.isArray(stuff)) {
      for (var i = 0; i < stuff.length; i++) {
        console.log(stuff[i]);
      }
    } else {
      console.log(stuff);
    }
  }
});

function whois(person) {
  let trueppl = Object.assign({}, whoppl, hiddenppl);
  for (var key in trueppl) {
    if (person.toLowerCase() === key) {
      return person + " is " + trueppl[key];
    }
  }
}

client.on('ready', () => {
  console.log('Connected and initialized.');
});

function formatPrice(prices) {
  let ret = "";
  for (var i = 0; i < (prices.length < 5 ? prices.length : 5); i++) {
    ret += prices[i].market_hash_name + " costs $" + (prices[i].price / 100) + "\n";
  }
  return ret;
}

function getPrice(item, appid, cb) {
  community.marketSearch({
    query: item,
    appid
  }, (err, items) => {
    if (err) {
      cb(err.message);
    } else {
      cb(formatPrice(items));
    }
  });
}

function getImg(item, appid, cb, ecb) {
  if (item.toLowerCase() == "kairu") {
    cb("http://vignette1.wikia.nocookie.net/powerlisting/images/a/ad/Trap-image.png/revision/latest?cb=20160113212524");
    return;
  } else if (item.toLowerCase() == "livid") {
    cb("https://s.thestreet.com/files/tsc/v2008/photos/contrib/uploads/transoceanrig_600x400.jpg");
    return;
  } else if (item.toLowerCase() == "dank") {
    cb("http://st.motortrend.com/uploads/sites/10/2015/11/2015-nissan-juke-sl-suv-angular-front.png?interpolation=lanczos-none&fit=around|300;199");
    return;
  } else if (item.toLowerCase() == "yuna") {
    cb("http://i.imgur.com/5vDmod7.png");
    return;
  } else if (item.toLowerCase() == "abuse") {
    cb("https://cdn.discordapp.com/attachments/167586953061990400/364157623832150017/madman.png");
  }
  community.marketSearch({
    query: item,
    appid: appid
  }, (err, items) => {
    if (err) {
      ecb(err.message);
    } else {
      cb(items[0].image, items[0].market_hash_name);
    }
  });
}

function removeAll(str, rep) {
  while (str.includes(rep) === true) {
    str = str.replace(rep, "");
  }
  return str;
}

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function getRandomFromList(list) {
  return list[getRandomInt(0, list.length)];
}

function game(args) {

}

var lastsent = Date.now();

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

  if (message.author.bot === true) {
    return;
  }

  var loc = message.channel;
  var msg = removeAll(message.content, "?");

  let send = function(msg, opts) {
    if (lastsent + 1000 < Date.now()) {
      lastsent = Date.now();
      loc.send(msg, opts);
    } else {

    }
  };

  let sendimg = function(img, text) {
    send(text, {
      embed: new Discord.RichEmbed().setImage(img)
    });
  };

  let mroles = message.member.roles.array();
  let ismod = false;
  for (let i = 0; i < mroles.length; i++) {
    if (mroles[i].name.includes("Mod")) {
      ismod = true;
    }
  }

  if (msg.toLowerCase().includes("drakemoon.com/promo-code/")) {
    message.delete();
    return;
  }

  if (msg == "!info") {
    send("I'm a bot run by Charred. https://github.com/charredgrass/raocsgo-discord-bot");
  }
  if (msg == "!ping") {
    send("Pong.");
  }
  if (msg.toLowerCase().match(/([^a-zA-Z]|^)osu/)) {
    send("We get it, you're a weeb.");
  }
  if (msg.toLowerCase() === "!whatthefuck" || msg.toLowerCase() === "!what") {
    send("https://docs.google.com/document/d/1u0-YAZG7Rv7P9N94vKEGocvJccGlDvK2RZxWMcg8pDA/edit?usp=sharing");
  }
  if (msg.toLowerCase().includes("trap")) {
    send('Traps? Ask Kairu about our Grade A Traps today!');
  }
  if (msg.toLowerCase() === "who am i") {
    send("None of your business.");
  }
  if (msg.toLowerCase() === "what is love") {
    send("Something you'll never feel.");
  }
  if (msg.toLowerCase() === "who are you" || msg.toLowerCase() === "who is bot charred") {
    send("You're fucking retarded.");
    return;
  }
  if (msg.toLowerCase() === "who is 为什么" || msg.toLowerCase() === "who is weishenme") {
    send("\"为什么\"是小孩子");
    return;
  }
  if (msg.toLowerCase() === "who is your daddy") {
    send("Charred is my daddy");
    return;
  }
  if (msg.substring(0, "who is everyone".length).toLowerCase() === "who is everyone") {
    send(everyone + ", 为什么");
  }
  if (msg.substring(0, "who is ".length).toLowerCase() === "who is ") {
    send(whois(msg.substring("who is ".length)));
  }
  if (msg.toLowerCase().includes("what is gambl")) {
    send("gamble is bad");
  }
  if (msg.toLowerCase() === "!source" || msg.toLowerCase() === "!sauce") {
    send("https://github.com/charredgrass/raocsgo-discord-bot");
  }
  if (msg.toLowerCase() === "!source2") {
    send("never");
  }
  if (msg.substring(0, "!joke".length).toLowerCase() === "!joke") {
    if (msg.split(" ").length > 1) {
      let x = parseInt(msg.substring("!joke ".length));
      if (x && x - 1 < jokes.length) {
        if (x == 69) {
          // send("")
        } else if (x == 0) {
          send("People who think arrays start at 1");
        } else {
          send(jokes[x - 1]);
        }
      } else if (x && x != 69) {
        send("People who think the bot has an unlimited number of jokes.");
      }
    } else {
      send(getRandomFromList(jokes));
    }
  }
  if (msg.substring(0, "!anchorloc".length).toLowerCase() === "!anchorloc") {
    anchorloc = loc;
    message.delete();
  }
  if (msg.substring(0, "!proxy".length).toLowerCase() === "!proxy") {
    if (message.author.id == "154826263628873728") {
      let toSay = msg.substring("!proxy ".length);
      if (anchorloc) {
        anchorloc.send(toSay);
      }
    }
  }
  if (msg.substring(0, "!priceof ".length).toLowerCase() === "!priceof ") {
    getPrice(msg.substring("!priceof ".length), 730, send);
  }
  if (msg.substring(0, "!priceofdota ".length).toLowerCase() === "!priceofdota ") {
    getPrice(msg.substring("!priceofdota ".length), 570, send);
  }
  if (msg.substring(0, "!priceoftf ".length).toLowerCase() === "!priceoftf ") {
    getPrice(msg.substring("!priceoftf ".length), 440, send);
  }
  if (msg.substring(0, "!priceofpubg ".length).toLowerCase() === "!priceofpubg ") {
    getPrice(msg.substring("!priceofpubg ".length), 578080, send);
  }
  if (msg.substring(0, "!imgof ".length).toLowerCase() === "!imgof ") {
    getImg(msg.substring("!imgof ".length), 730, sendimg, send);
  }
  if (msg.substring(0, "!imgofpubg ".length).toLowerCase() === "!imgofpubg ") {
    getImg(msg.substring("!imgofpubg ".length), 578080, sendimg, send);
  }
  if (msg.substring(0, "!magic8 ".length).toLowerCase() === "!magic8 ") {
    var answers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"];
    send(getRandomFromList(answers));
  }
  if (msg.substring(0, "!help".length).toLowerCase() === "!help") {
    var preargs = (msg.substring("!help".length).split(" "));
    let args = [];
    for (var i = 0; i < preargs.length; i++) {
      if (preargs[i] === "") {
        //kill space
      } else {
        args.push(preargs[i]);
      }
    }
    if (args.length === 0) {
      send("Valid commands: !help, !what, !priceof, !imgof, who is [person], !magic8, !info\nType \"!help help\" for more specific help.");
      if (helpdocs[args[0]]) {
        send(helpdocs[args[0]]);
      }
    } else {
      send("Unknown command. Type \"!help\" for help.");
    }
  }
});<|endoftext|>


<commit_before>const Discord = require('discord.js');
const client = new Discord.Client();
const weather = require('weather-js');
//const mysql = require('mysql');
const sql = require("sqlite");
sql.open("./score.sqlite");

//

client.config = require('./config.json');
client.log = require('./functions/log.js');

//

client.commands = new Discord.Collection();

//

client.commands.set('ping', require('./commands/ping.js'));
client.commands.set('falar', require('./commands/falar.js'));
client.commands.set('ajuda', require('./commands/ajuda.js'));
client.commands.set('limpar', require('./commands/limpar.js'));
client.commands.set('ban', require('./commands/ban.js'));
client.commands.set('kick', require('./commands/kick.js'));
client.commands.set('unban', require('./commands/unban.js'));
client.commands.set('roll', require('./commands/roll.js'));
client.commands.set('bot', require('./commands/conversaBot.js'));
client.commands.set('morra', require('./commands/conversaMorra.js'));
client.commands.set('soma', require('./commands/calcularSoma.js'));
client.commands.set('sub', require('./commands/calcularSub.js'));
client.commands.set('mult', require('./commands/calcularMult.js'));
client.commands.set('div', require('./commands/calcularDiv.js'));
client.commands.set('fsalvos', require('./commands/canalSalvos.js'));
client.commands.set('fprincipal', require('./commands/canalPrincipal.js'));
client.commands.set('resp', require('./commands/resp.js'));
client.commands.set('playinitiald', require('./commands/radioPlayInitialD.js'));
client.commands.set('playmoe', require('./commands/radioPlayMoe.js'));
client.commands.set('playanimenfo', require('./commands/radioPlayAnimeNfo.js'));
client.commands.set('stop', require('./commands/radioStop.js'));
client.commands.set('userinfo', require('./commands/userinfo.js'));
client.commands.set('serverinfo', require('./commands/serverinfo.js'));
client.commands.set('tempo', require('./commands/tempo.js'));
client.commands.set('afk', require('./commands/joinAway.js'));
client.commands.set('level', require('./commands/levelXp.js'));
client.commands.set('pontos', require('./commands/levelPoints.js'));

//

//mysql Heroku connect database
//var con;
//if(process.env.DATABASE_URL) { con = mysql.createConnection(process.env.DATABASE_URL); }

//

client.on('message', message => {
  sql.get(`SELECT * FROM scores WHERE userId ="${message.author.id}"`).then(row => {
    if (!row) {
      sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);
    } else {
      let curLevel = Math.floor(0.1 * Math.sqrt(row.points + 1));
      if (curLevel > row.level) {
        row.level = curLevel;
        sql.run(`UPDATE scores SET points = ${row.points + 1}, level = ${row.level} WHERE userId = ${message.author.id}`);
        message.reply(`Ding! Parabéns! Você subiu de level. O seu level atual é **${curLevel}**!`);
      }
      sql.run(`UPDATE scores SET points = ${row.points + 1} WHERE userId = ${message.author.id}`);
    }
  }).catch(() => {
    console.error;
    sql.run("CREATE TABLE IF NOT EXISTS scores (userId TEXT, points INTEGER, level INTEGER)").then(() => {
      sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);
    });
  });
  require('./events/message.js')(client, message, sql) });

//READY
client.on('ready', () => { var channel = client.channels.get('167715230082662401'); channel.sendMessage("**O BoT está online!**").then(msg => {msg.delete(60000)}); require('./events/ready.js')(client) });

//GUILD
client.on('guildCreate', guild => require('./events/guildCreate.js')(client, guild));

//MEMBRO
//client.on('guildMemberAdd', member => require('./events/guildMemberAdd.js')(client, member));
client.on('guildMemberAdd', (member, message, channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Seja bem vindo(a) '+member.user.username+'!').then(msg => {msg.delete(60000)}) } );
client.on('guildMemberRemove', (member, message, channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Adeus '+member.user.username+'!').then(msg => {msg.delete(60000)}) } );
client.on('guildMemberUpdate', (oldMember, newMember) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('O usuário '+member.user.username+' atualizou os seus dados!').then(msg => {msg.delete(60000)}) } );
client.on('messageReactionAdd', (reaction, user) => require('./events/messageReactionAdd.js')(client, reaction, user));

//CANAL
client.on('channelCreate', (channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma nova **sala de conversa** foi **criada**!').then(msg => {msg.delete(60000)}) } );
client.on('channelDelete', (channel, guild) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma **sala de conversa** foi **deletada**!').then(msg => {msg.delete(60000)}) } );
client.on('channelPinsUpdate', (channel, time) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma nova mensagem foi **fixada** em '+time+'!').then(msg => {msg.delete(60000)}) } );
client.on('channelUpdate', (channel, oldChannel, newChannel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A **sala de conversa** '+oldChannel+' foi atualizada!').then(msg => {msg.delete(60000)}) } );

//

/*client.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
if(oldUserChannel === undefined && newUserChannel !== undefined) {
// usuario entra no canal BOT manda MSG
} else if(newUserChannel === undefined){
// usuario sai no canal BOT manda MSG
}});*/

//

//Heroku connect token
//bot.login(config.token)
client.login(process.env.BOT_TOKEN);<commit_msg><commit_after>const Discord = require('discord.js');
const client = new Discord.Client();
const weather = require('weather-js');
//const mysql = require('mysql');
const sql = require("sqlite");
sql.open("./score.sqlite");

//

client.config = require('./config.json');
client.log = require('./functions/log.js');

//

client.commands = new Discord.Collection();

//

client.commands.set('ping', require('./commands/ping.js'));
client.commands.set('falar', require('./commands/falar.js'));
client.commands.set('ajuda', require('./commands/ajuda.js'));
client.commands.set('limpar', require('./commands/limpar.js'));
client.commands.set('ban', require('./commands/ban.js'));
client.commands.set('kick', require('./commands/kick.js'));
client.commands.set('unban', require('./commands/unban.js'));
client.commands.set('roll', require('./commands/roll.js'));
client.commands.set('bot', require('./commands/conversaBot.js'));
client.commands.set('morra', require('./commands/conversaMorra.js'));
client.commands.set('soma', require('./commands/calcularSoma.js'));
client.commands.set('sub', require('./commands/calcularSub.js'));
client.commands.set('mult', require('./commands/calcularMult.js'));
client.commands.set('div', require('./commands/calcularDiv.js'));
client.commands.set('fsalvos', require('./commands/canalSalvos.js'));
client.commands.set('fprincipal', require('./commands/canalPrincipal.js'));
client.commands.set('resp', require('./commands/resp.js'));
client.commands.set('playinitiald', require('./commands/radioPlayInitialD.js'));
client.commands.set('playmoe', require('./commands/radioPlayMoe.js'));
client.commands.set('playanimenfo', require('./commands/radioPlayAnimeNfo.js'));
client.commands.set('stop', require('./commands/radioStop.js'));
client.commands.set('userinfo', require('./commands/userinfo.js'));
client.commands.set('serverinfo', require('./commands/serverinfo.js'));
client.commands.set('tempo', require('./commands/tempo.js'));
client.commands.set('afk', require('./commands/joinAway.js'));
client.commands.set('level', require('./commands/levelXp.js'));
client.commands.set('pontos', require('./commands/levelPoints.js'));

//

//mysql Heroku connect database
//var con;
//if(process.env.DATABASE_URL) { con = mysql.createConnection(process.env.DATABASE_URL); }

//

client.on('message', message => {
  sql.get(`SELECT * FROM scores WHERE userId ="${message.author.id}"`).then(row => {
    if (!row) {
      sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);
    } else {
      let curLevel = Math.floor(0.1 * Math.sqrt(row.points + 1));
      if (curLevel > row.level) {
        row.level = curLevel;
        sql.run(`UPDATE scores SET points = ${row.points + 1}, level = ${row.level} WHERE userId = ${message.author.id}`);
        message.reply(`Ding! Parabéns! Você subiu de level. O seu level atual é **${curLevel}**!`);
      }
      sql.run(`UPDATE scores SET points = ${row.points + 1} WHERE userId = ${message.author.id}`);
    }
  }).catch(() => {
    console.error;
    sql.run("CREATE TABLE IF NOT EXISTS scores (userId TEXT, points INTEGER, level INTEGER)").then(() => {
      sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);
    });
  });
  require('./events/message.js')(client, message, sql) });

//READY
client.on('ready', () => { var channel = client.channels.get('167715230082662401'); channel.sendMessage("**O BoT está online!**").then(msg => {msg.delete(60000)}); require('./events/ready.js')(client) });

//GUILD
client.on('guildCreate', guild => require('./events/guildCreate.js')(client, guild));

//MEMBRO
//client.on('guildMemberAdd', member => require('./events/guildMemberAdd.js')(client, member));
client.on('guildMemberAdd', (member, message, channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Seja bem vindo(a) '+member.user.username+'!').then(msg => {msg.delete(60000)}) } );
client.on('guildMemberRemove', (member, message, channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Adeus '+member.user.username+'!').then(msg => {msg.delete(60000)}) } );
client.on('guildMemberUpdate', (oldMember, newMember) => { var channel = client.channels.get('167715230082662401'); newMember.channel.sendMessage('O usuário '+member.user.username+' atualizou os seus dados!').then(msg => {msg.delete(60000)}) } );
client.on('messageReactionAdd', (reaction, user) => require('./events/messageReactionAdd.js')(client, reaction, user));

//CANAL
client.on('channelCreate', (channel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma nova **sala de conversa** foi **criada**!').then(msg => {msg.delete(60000)}) } );
client.on('channelDelete', (channel, guild) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma **sala de conversa** foi **deletada**!').then(msg => {msg.delete(60000)}) } );
client.on('channelPinsUpdate', (channel, time) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('Uma nova mensagem foi **fixada** em '+time+'!').then(msg => {msg.delete(60000)}) } );
client.on('channelUpdate', (channel, oldChannel, newChannel) => { var channel = client.channels.get('167715230082662401'); channel.sendMessage('A **sala de conversa** '+oldChannel+' foi atualizada!').then(msg => {msg.delete(60000)}) } );

//

/*client.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
if(oldUserChannel === undefined && newUserChannel !== undefined) {
// usuario entra no canal BOT manda MSG
} else if(newUserChannel === undefined){
// usuario sai no canal BOT manda MSG
}});*/

//

//Heroku connect token
//bot.login(config.token)
client.login(process.env.BOT_TOKEN);<|endoftext|>


<commit_before>var axios = require('axios');
var fs = require('fs');
var markov = require('./vendor/node-markov.js');
var m = markov(1);
m.readExternal(fs.readFileSync('data/scifi.json').toString());

var instance = axios.create({
  baseURL: 'http://rhymebrain.com/',
  timeout: 10000,
  headers: {'X-Custom-Header': 'foobar'}
});

var botsong = {
  onMessage: function(session) {
    var wordToRhyme = lastWord(session.message.text);
    return instance.get('/talk?function=getRhymes&word=' + wordToRhyme)
    .then(function (response) {

      var scoredArray = [];
      scoredArray = arrayWithOnlyScoredAbove(scoredArray, response.data, 300);
      scoredArray = arrayWithOnlyScoredAbove(scoredArray, response.data, 250);
      scoredArray = arrayWithOnlyScoredAbove(scoredArray, response.data, 200);

      for (var i = 0 ; i < scoredArray.length; i++ ) {
        var item = scoredArray[i];
        var responseText = buildResponseText(item.word);
        if (responseText) {
          return responseText;
        }
      }

      return 'I can\'t come up with anything that rhymes with '  + wordToRhyme;

      // if (scoredArray.length > 0) {
      //   var item = scoredArray[Math.floor(Math.random()*scoredArray.length)];
      //   return m.respond(item.word).join(' ') + ' ' + item.word;
      //   // return 'hey that rhymes with ' + item.word;
      // } else {
      //   return 'I can\'t come up with anything that rhymes with '  + wordToRhyme;
      // }
    })
    .catch(function (response) {
      console.log(response);
      return 'Error';
    });

  }
};

module.exports = botsong;

function lastWord(words) {
    var n = words.split(" ");
    return n[n.length - 1];
}

function buildResponseText(word) {
  var key = m.search(word.toLowerCase());
  if (!key) {
    return undefined;
  }

  var responseText = m.backward(key, 10).join(' ') + ' ' + word;
  responseText = responseText.charAt(0).toUpperCase() + responseText.slice(1);

  return responseText;
}

function arrayWithOnlyScoredAbove(scoredArray, allData, score) {
  if (scoredArray.length == 0)
  {
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].score >= score)
      {
        scoredArray.push(allData[i]);
      }
    }
  }
  return scoredArray;
}
<commit_msg>try to conform to input length on replies<commit_after>var axios = require('axios');
var fs = require('fs');
var markov = require('./vendor/node-markov.js');
var m = markov(1);
m.readExternal(fs.readFileSync('data/scifi.json').toString());

var instance = axios.create({
  baseURL: 'http://rhymebrain.com/',
  timeout: 10000,
  headers: {'X-Custom-Header': 'foobar'}
});

var botsong = {
  onMessage: function(session) {
    var wordToRhyme = lastWord(session.message.text);
    return instance.get('/talk?function=getRhymes&word=' + wordToRhyme)
    .then(function (response) {

      var scoredArray = [];
      scoredArray = arrayWithOnlyScoredAbove(scoredArray, response.data, 300);
      scoredArray = arrayWithOnlyScoredAbove(scoredArray, response.data, 250);
      scoredArray = arrayWithOnlyScoredAbove(scoredArray, response.data, 200);

	  var textLenght = session.message.text.length

      for (var i = 0 ; i < scoredArray.length; i++ ) {
        var item = scoredArray[i];
        var responseText = buildResponseText(item.word, textLenght);
        if (responseText) {
          return responseText;
        }
      }

      return 'I can\'t come up with anything that rhymes with '  + wordToRhyme;

      // if (scoredArray.length > 0) {
      //   var item = scoredArray[Math.floor(Math.random()*scoredArray.length)];
      //   return m.respond(item.word).join(' ') + ' ' + item.word;
      //   // return 'hey that rhymes with ' + item.word;
      // } else {
      //   return 'I can\'t come up with anything that rhymes with '  + wordToRhyme;
      // }
    })
    .catch(function (response) {
      console.log(response);
      return 'Error';
    });

  }
};

module.exports = botsong;

function lastWord(words) {
    var n = words.split(" ");
    return n[n.length - 1];
}

function buildResponseText(word, length) {
  var key = m.search(word.toLowerCase());
  if (!key) {
    return undefined;
  }

  var responseText = m.backward(key, 10).join(' ') + ' ' + word;

  var textArray = responseText.split(" ");
  var finalText = "";

  var i = textArray.length;
  while (i > 0 ) {
  	i = i - 1;
  	finalText = textArray[i] + " " + finalText
  	if (finalText.length >= length)
  	{
  		break
  	}
  }

  responseText = finalText
  responseText = responseText.charAt(0).toUpperCase() + responseText.slice(1);

  return responseText;
}

function arrayWithOnlyScoredAbove(scoredArray, allData, score) {
  if (scoredArray.length == 0)
  {
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].score >= score)
      {
        scoredArray.push(allData[i]);
      }
    }
  }
  return scoredArray;
}
<|endoftext|>


<commit_before>/* Require modules */

var nodeTelegramBot = require('node-telegram-bot')
    , config = require('./config.json')
    , request = require("request")
    , cheerio = require("cheerio");

/* Functions */

/**
 * Uses the request module to return the body of a web page
 * @param  {string}   url
 * @param  {callback} callback
 * @return {string}
 */

function getWebContent(url, callback){
  request({
    uri: url,
  }, function(error, response, body) {
    callback(body);
  });
}

/* Logic */

var recipeURL = 'http://www.random-recipes.com/index.php?page=index&filter=true';

var bot = new nodeTelegramBot({
  token: config.token
})
.on('message', function (message) {
  /* Process "/dinner" command */
  if (message.text == "/dinner" || message.text == "/dinner@" + config.botname) {
    console.log(message);
    getWebContent(recipeURL, function(data){
      // Parse DOM and recipe informations
      var $ = cheerio.load(data)
          , recipeName = $(".recipe-name-title").text()
          , recipeURL = 'http://www.random-recipes.com/' + $(".recipe-name").attr('href');
      // Send bot reply
      bot.sendMessage({
          chat_id: message.chat.id,
          text: 'What about "' + recipeName + '"? ' + recipeURL
      });
    });
  }
})
.start();
<commit_msg>Improve output<commit_after>/* Require modules */

var nodeTelegramBot = require('node-telegram-bot')
    , config = require('./config.json')
    , request = require("request")
    , cheerio = require("cheerio");

/* Functions */

String.prototype.repeat= function(n){
    n= n || 1;
    return Array(n+1).join(this);
}

/**
 * Uses the request module to return the body of a web page
 * @param  {string}   url
 * @param  {callback} callback
 * @return {string}
 */

function getWebContent(url, callback){
  request({
    uri: url,
  }, function(error, response, body) {
    callback(body);
  });
}

/* Logic */

var recipeURL = 'http://www.random-recipes.com/index.php?page=index&filter=true';

var bot = new nodeTelegramBot({
  token: config.token
})
.on('message', function (message) {
  /* Process "/dinner" command */
  if (message.text == "/dinner" || message.text == "/dinner@" + config.botname) {
    console.log(message);
    getWebContent(recipeURL, function(data){
      // Parse DOM and recipe informations
      var $ = cheerio.load(data)
          , name = $(".recipe-name-title").text()
          , starsFull = $('.stars').children('.star-image-pos').length
          , starsEmpty = $('.stars').children('.star-image').length
          , ratings = $('.rating-text').text().replace(' Ratings', '')
          , prepTime = $('.stats-td-right').eq(0).text().trim()
          , cookTime = $('.stats-td-right').eq(1).text().trim()
          , servings = $('.stats-td-right').eq(2).text().trim()
          , author = $('.stats-td-right').eq(5).text().trim()
          , linkURL = 'http://www.random-recipes.com/' + $(".recipe-name").attr('href');

      // Send bot reply
      bot.sendMessage({
          chat_id: message.chat.id,
          text: 'What about "' + name + '"? \n' + linkURL + '\n' +
                '⚒ ' + prepTime + ' prep time' + '\n' +
                '🔥 ' + cookTime + ' cook time' + '\n' +
                '🍽 ' + servings + ' servings' + '\n' +
                '📄 added by ' + author + '\n' +
                '★'.repeat(starsFull) + '☆'.repeat(starsEmpty) + '(' + ratings + ' ratings)' + '\n'
      });
    });
  }
})
.start();
<|endoftext|>


<commit_before>/*
  Developed by Astrydax, aka Royalcrown28 for vampwood
  For Custom Discord Bots please email me at Astrydax@gmail.com
*/
const Discord = require("discord.js");
const config = require("./config.json");
const fs = require('fs');
const jsonfile = require('jsonfile');
const chalk = require("chalk");
const bot = new Discord.Client();
const schedule = require('node-schedule');
var print = require("./modules/printValues.js").print;
var destiny = require("./modules/destiny.js").destiny;
var crit = require("./modules/crit.js").crit;
var shipcrit = require("./modules/crit.js").shipcrit;
var help = require("./modules/help.js").help;
var char = require("./modules/char.js").char;
var roll = require("./modules/roll.js").roll;
var polyhedral = require("./modules/dice.js").polyhedral;
var admin = require("./modules/admin.js").admin;
var init = require("./modules/init.js").init;
var reroll = require("./modules/reroll.js").reroll;
var version = require("./package.json").version;
var poly = require("./modules/poly.js").poly;
var gleepglop = require("./modules/misc.js").gleepglop;
var obligation = require("./modules/obligation.js").obligation;
var statUpdate = require("./modules/misc.js").statUpdate;

bot.login(config.token);
require('events').EventEmitter.defaultMaxListeners = 0;
//init destinyBalance
var destinyBalance = jsonfile.readFileSync(`.${config.dataPath}/data/destinyBalance.json`);

//Init the diceResult
var diceResult = jsonfile.readFileSync(`.${config.dataPath}/data/diceResult.json`);

//init characterStatus
var characterStatus = jsonfile.readFileSync(`.${config.dataPath}/data/characterStatus.json`);

//init initiativeOrder
var initiativeOrder = jsonfile.readFileSync(`.${config.dataPath}/data/initiativeOrder.json`);

//init stats
var botStats = jsonfile.readFileSync(`.${config.dataPath}/data/botStats.json`);

var channelEmoji = jsonfile.readFileSync(`.${config.dataPath}/data/channelEmoji.json`);

//Called When bot becomes functional
bot.on("ready", () => {
  console.log(`Bot version ${version}`);
  console.log(`Logged in as ${bot.user.username}!`);
  let dailyJob = schedule.scheduleJob({hour: 08, minute: 00, second: 00}, () => {
    botStats = statUpdate(botStats, bot);
  });
});

//Called whenever a users send a message to the server
bot.on("message", message => {
  //Ignore messages sent by the bot
  if (message.author.bot) return;
  //Ignore messages that dont start with the command symbol
  if (!message.content.includes(config.prefix)) return;
  //establish which emoji to use
  var channel = message.channel.id;

  if (message.channel.permissionsFor(bot.user).has('USE_EXTERNAL_EMOJIS') != true) {
    message.channel.send(`Please enable \'Use External Emoji\' for ${bot.user.username}`);
    return;
  }
  //Seperate and create a list of parameters. A space in the message denotes a new parameter
  if (!message.content.startsWith(config.prefix)) {
    var params = message.content.split(" ");
    for (var i=0; params.length>i; i++) {
      if (params[i].startsWith(config.prefix)) break;
    }
    params = params.slice(i);
  } else var params = message.content.split(" ");

  //create command
  if (params.length == 0) return;

  var command = params[0].toLowerCase().toString().slice(1);
  params = params.slice(1);

  if (command.startsWith('d') && (command.length > 1) && (command != 'destiny')) {
    var sides = command.replace(/\D/g, "");
    command = 'polyhedral';
  }
  //init the descriptor string to an empty string
  var desc = "";
  var beg, end = 0;
  var begF, endF = false;
  for (var i = 0; i < params.length; i++) {
    if (params[i].includes('"')) {
      if (!begF) {
        beg = i;
        end = i;
        begF = true;
      } else if (begF && !endF) {
        end = i;
        endF = true;
      }
    }
  }
  //remove the text field arguments from the list of parameters before checking for dice.
  for (i = beg; i <= end; i++) {
    desc += " " + params[i];
  }
  var spliceAmnt = end + 1 - beg;
  params.splice(beg, spliceAmnt);
  //remove Quotes from descriptor
  desc = desc.replace(/['"]+/g, '');

  //set the rest of params to lowercase
  if (params != undefined) {
    params = params.filter(Boolean);
    for (var i = 0; i < params.length; i++) {
      params[i] = params[i].toLowerCase();
    }
  }
  console.log("@" + message.author.username + " " + message.createdAt);
  console.log(command + " " + params + " " + desc);

//************************COMMANDS START HERE************************

if (message.channel.type == "dm" || message.channel.type == "text") {

  switch (command) {
    //Ver command
    case "ver":
      message.channel.send(bot.user.username + ": version: " + version);
      break;
    //Character Tracker
    case "char":
      botStats.daily.char++;
      char(params, characterStatus, message);
      break;
    // help module
    case "help":
      botStats.daily.help++;
      help(params, message);
      break;
    case "gleepglop":
    case "species":
      botStats.daily.species++;
      gleepglop(message);
      break;
    case "polyhedral":
      botStats.daily.d++;
      polyhedral(sides, params, message);
      break;
    case "poly":
      botStats.daily.poly++;
      poly(params, message);
      break;
    }
  }

if (message.channel.type == "text") {

  switch (command) {
    //!crit command
    case "crit":
      botStats.daily.crit++;
      crit(params, message, bot, channelEmoji);
      break;
    //!shipcrit command
    case "shipcrit":
      botStats.daily.shipcrit++;
      shipcrit(params, message, bot, channelEmoji);
      break;
    //Destiny Point Module
    case "destiny":
    case "d":
      botStats.daily.destiny++;
      destiny(params, destinyBalance, message, config, bot, channelEmoji);
      break;
      // Roll the dice command
    case "roll":
    case "r":
      botStats.daily.roll++;
      roll(params, diceResult, message, config, desc, bot, channelEmoji);
      break;
    case "reroll":
    case "rr":
      botStats.daily.reroll++;
      reroll(params, diceResult, message, config, desc, bot, channelEmoji);
      break;
    case "init":
    case "i":
      botStats.daily.init++;
      init(params, initiativeOrder, message, diceResult, config, desc, bot, channelEmoji);
      break;
    case "obligation":
    case "o":
      botStats.daily.obligation++;
      obligation(params, characterStatus, message);
      break;
    case "swrpg":
    case "genesys":
      channelEmoji[channel] = command;
      jsonfile.writeFile(`.${config.dataPath}/data/channelEmoji.json`, channelEmoji);
      message.channel.send(`${bot.user.username} will now use ${command} dice`);
      break;
  }
}
  if (message.author.id == config.adminID) {
    admin(command, message, botStats);
  }
  jsonfile.writeFile(`.${config.dataPath}/data/botStats.json`, botStats);

process.on("unhandledRejection", err => {
  console.error("Uncaught Promise Error: \n" + err.stack);
});
});
<commit_msg>maybe this?<commit_after>/*
  Developed by Astrydax, aka Royalcrown28 for vampwood
  For Custom Discord Bots please email me at Astrydax@gmail.com
*/
const Discord = require("discord.js");
const config = require("./config.json");
const fs = require('fs');
const jsonfile = require('jsonfile');
const chalk = require("chalk");
const bot = new Discord.Client();
const schedule = require('node-schedule');
var print = require("./modules/printValues.js").print;
var destiny = require("./modules/destiny.js").destiny;
var crit = require("./modules/crit.js").crit;
var shipcrit = require("./modules/crit.js").shipcrit;
var help = require("./modules/help.js").help;
var char = require("./modules/char.js").char;
var roll = require("./modules/roll.js").roll;
var polyhedral = require("./modules/dice.js").polyhedral;
var admin = require("./modules/admin.js").admin;
var init = require("./modules/init.js").init;
var reroll = require("./modules/reroll.js").reroll;
var version = require("./package.json").version;
var poly = require("./modules/poly.js").poly;
var gleepglop = require("./modules/misc.js").gleepglop;
var obligation = require("./modules/obligation.js").obligation;
var statUpdate = require("./modules/misc.js").statUpdate;

bot.login(config.token);
require('events').EventEmitter.defaultMaxListeners = 0;
//init destinyBalance
var destinyBalance = jsonfile.readFileSync(`.${config.dataPath}/data/destinyBalance.json`);

//Init the diceResult
var diceResult = jsonfile.readFileSync(`.${config.dataPath}/data/diceResult.json`);

//init characterStatus
var characterStatus = jsonfile.readFileSync(`.${config.dataPath}/data/characterStatus.json`);

//init initiativeOrder
var initiativeOrder = jsonfile.readFileSync(`.${config.dataPath}/data/initiativeOrder.json`);

//init stats
var botStats = jsonfile.readFileSync(`.${config.dataPath}/data/botStats.json`);

var channelEmoji = jsonfile.readFileSync(`.${config.dataPath}/data/channelEmoji.json`);

//Called When bot becomes functional
bot.on("ready", () => {
  console.log(`Bot version ${version}`);
  console.log(`Logged in as ${bot.user.username}!`);
  let dailyJob = schedule.scheduleJob({hour: 08, minute: 00, second: 00}, () => {
    botStats = statUpdate(botStats, bot);
  });
});

//Called whenever a users send a message to the server
bot.on("message", message => {
  //Ignore messages sent by the bot
  if (message.author.bot) return;
  //Ignore messages that dont start with the command symbol
  if (!message.content.includes(config.prefix)) return;
  //establish which emoji to use

  if (message.channel.permissionsFor(bot.user).has('USE_EXTERNAL_EMOJIS') != true) {
    message.channel.send(`Please enable \'Use External Emoji\' for ${bot.user.username}`);
    return;
  }
  //Seperate and create a list of parameters. A space in the message denotes a new parameter
  if (!message.content.startsWith(config.prefix)) {
    var params = message.content.split(" ");
    for (var i=0; params.length>i; i++) {
      if (params[i].startsWith(config.prefix)) break;
    }
    params = params.slice(i);
  } else var params = message.content.split(" ");

  //create command
  if (params.length == 0) return;

  var command = params[0].toLowerCase().toString().slice(1);
  params = params.slice(1);

  if (command.startsWith('d') && (command.length > 1) && (command != 'destiny')) {
    var sides = command.replace(/\D/g, "");
    command = 'polyhedral';
  }
  //init the descriptor string to an empty string
  var desc = "";
  var beg, end = 0;
  var begF, endF = false;
  for (var i = 0; i < params.length; i++) {
    if (params[i].includes('"')) {
      if (!begF) {
        beg = i;
        end = i;
        begF = true;
      } else if (begF && !endF) {
        end = i;
        endF = true;
      }
    }
  }
  //remove the text field arguments from the list of parameters before checking for dice.
  for (i = beg; i <= end; i++) {
    desc += " " + params[i];
  }
  var spliceAmnt = end + 1 - beg;
  params.splice(beg, spliceAmnt);
  //remove Quotes from descriptor
  desc = desc.replace(/['"]+/g, '');

  //set the rest of params to lowercase
  if (params != undefined) {
    params = params.filter(Boolean);
    for (var i = 0; i < params.length; i++) {
      params[i] = params[i].toLowerCase();
    }
  }
  console.log("@" + message.author.username + " " + message.createdAt);
  console.log(command + " " + params + " " + desc);

//************************COMMANDS START HERE************************

if (message.channel.type == "dm" || message.channel.type == "text") {

  switch (command) {
    //Ver command
    case "ver":
      message.channel.send(bot.user.username + ": version: " + version);
      break;
    //Character Tracker
    case "char":
      botStats.daily.char++;
      char(params, characterStatus, message);
      break;
    // help module
    case "help":
      botStats.daily.help++;
      help(params, message);
      break;
    case "gleepglop":
    case "species":
      botStats.daily.species++;
      gleepglop(message);
      break;
    case "polyhedral":
      botStats.daily.d++;
      polyhedral(sides, params, message);
      break;
    case "poly":
      botStats.daily.poly++;
      poly(params, message);
      break;
    }
  }

if (message.channel.type == "text") {

  switch (command) {
    //!crit command
    case "crit":
      botStats.daily.crit++;
      crit(params, message, bot, channelEmoji);
      break;
    //!shipcrit command
    case "shipcrit":
      botStats.daily.shipcrit++;
      shipcrit(params, message, bot, channelEmoji);
      break;
    //Destiny Point Module
    case "destiny":
    case "d":
      botStats.daily.destiny++;
      destiny(params, destinyBalance, message, config, bot, channelEmoji);
      break;
      // Roll the dice command
    case "roll":
    case "r":
      botStats.daily.roll++;
      roll(params, diceResult, message, config, desc, bot, channelEmoji);
      break;
    case "reroll":
    case "rr":
      botStats.daily.reroll++;
      reroll(params, diceResult, message, config, desc, bot, channelEmoji);
      break;
    case "init":
    case "i":
      botStats.daily.init++;
      init(params, initiativeOrder, message, diceResult, config, desc, bot, channelEmoji);
      break;
    case "obligation":
    case "o":
      botStats.daily.obligation++;
      obligation(params, characterStatus, message);
      break;
    case "swrpg":
    case "genesys":
      channelEmoji[message.channel.id] = command;
      jsonfile.writeFile(`.${config.dataPath}/data/channelEmoji.json`, channelEmoji);
      message.channel.send(`${bot.user.username} will now use ${command} dice`);
      break;
  }
}
  if (message.author.id == config.adminID) {
    admin(command, message, botStats);
  }
  jsonfile.writeFile(`.${config.dataPath}/data/botStats.json`, botStats);

process.on("unhandledRejection", err => {
  console.error("Uncaught Promise Error: \n" + err.stack);
});
});
<|endoftext|>


<commit_before>require('dotenv').config({path:__dirname+'/token.env'});
/*
  A ping pong bot, whenever you send "ping", it replies "pong".
*/

// Import the discord.js module
const Discord = require('discord.js');

// Create an instance of a Discord client
const client = new Discord.Client();

// The token of your bot - https://discordapp.com/developers/applications/me
const token = process.env.TOKEN;

//Command prefix
var prefix = ".";

//Command List
var command_list = {roll: performRolls};

//dice rolling function
var dice = function(num, sides, mod) {
  let rolls = [];
  function add(a, b) {
      return a + b;
  }
  for (i = 0; i < num; i++) {
      rolls.push(Math.ceil(Math.random() * sides));
  }
  return {results: rolls, total: rolls.reduce(add, 0) + mod};
};

var performRolls = function(params){
  //TODO: Get NUM, SIDES and MOD from the params
  let rolls = roll(num, sides, mod);
  return "ROLLS: "+ rolls.results + "\n RESULT:" + rolls.total;
}

// The ready event is vital, it means that your bot will only start reacting to information
// from Discord _after_ ready is emitted
client.on('ready', () => {
  console.log('I am ready!');
  //console.log(client.channels);
  client.channels.find("name", "sigil").send('Hai Everyone! ^_^');
});

// Create an event listener for messages
client.on('message', message => {
  // If the message is "ping"
  if (message.content === 'ping') {
    // Send "pong" to the same channel
    message.channel.send('pong');
  }
  if (message.content === 'We need..') {
    message.channel.send('CAPTAIN THEORYCRAFT!');
  }
  if (message.content === 'I got a crit'){
    message.channel.send('Yay! ^_^');
  }
  if (message.content === 'D20-Chan is cute') {
    message.channel.send('Teehee ^-^');
  }
  if (message.content === '_hugs D20-Chan_'){
    message.channel.send('-^_^-');
  }

  if( message.content[0] === prefix){
    ///TODO: SEND PARAMS TO FUNCTION
  }
});

/* if (message.content === '~roll')
    //find the first number in the string, pass as num
    //find the second number, pass as side
     message.channel.send(dice(num, side)); */

// Log our bot in
client.login(token);<commit_msg>Encapsulation of rolling function<commit_after>require('dotenv').config({path:__dirname+'/token.env'});
/*
  A ping pong bot, whenever you send "ping", it replies "pong".
*/

// Import the discord.js module
const Discord = require('discord.js');

// Create an instance of a Discord client
const client = new Discord.Client();

// The token of your bot - https://discordapp.com/developers/applications/me
const token = process.env.TOKEN;

//Command prefix
var prefix = ".";

//dice rolling function
var dice = function(num, sides, mod) {
  let rolls = [];
  function add(a, b) {
      return a + b;
  }
  for (i = 0; i < num; i++) {
      rolls.push(Math.ceil(Math.random() * sides));
  }
  return {results: rolls, total: rolls.reduce(add, 0) + mod};
};

var performRolls = function(commandContent){
    let num = commandContent.split("d")[0];
    let sides,
        mod;
  if (commandContent.indexOf("+")){
     sides = commandContent.split("d")[1].split("+")[0];
     mod = commandContent.split("d")[1].split("+")[1];
  }
  else if (commandContent.indexOf("-")){
     sides = commandContent.split("d")[1].split("-")[0];
     mod = commandContent.split("d")[1].split("-")[1]; //need to redo parseInt so this is minus
  }
  else {
     sides = commandContent.split("d")[1];
     mod = 0;
  }
  num = parseInt(num);
  sides = parseInt(sides);
  mod = parseInt(mod);
  let rolls = dice(num, sides, mod);
  return "ROLLS: "+ rolls.results + "\n RESULT:" + rolls.total;
}

//Command List
var commandList = {roll: performRolls};

// The ready event is vital, it means that your bot will only start reacting to information
// from Discord _after_ ready is emitted
client.on('ready', () => {
  console.log('I am ready!');
  //console.log(client.channels);
//  client.channels.find("name", "sigil").send('Hai Everyone! ^_^');
});

// Create an event listener for messages
client.on('message', message => {
  // If the message is "ping"
  if (message.content === 'ping') {
    // Send "pong" to the same channel
    message.channel.send('pong');
  }
  if (message.content.toLowerCase === 'we need...') {
    message.channel.send('CAPTAIN THEORYCRAFT!');
  }
  if (message.content.toLowerCase === 'i got a crit'){
    message.channel.send('Yay! ^_^');
  }
  if (message.content.toLowerCase === 'd20-chan is cute') {
    message.channel.send('Teehee ^-^');
  }
  if (message.content.toLowerCase === '_hugs d20-chan_'){
    message.channel.send('-^_^-');
  }

  if(message.content[0] === prefix){
    message.content.toLowerCase();
    let commandName = message.content.substr(1).split(" ")[0];
    let commandContent = message.content.substr(1).split(" ")[1];
    console.log(commandList); //returns {roll: [function: performRolls]}
    console.log(commandName); //works properly..
    console.log(commandList.commandName); //this is undefined for some reason....
  }
});

// Log our bot in
client.login(token);<|endoftext|>


<commit_before>const MessageHandler = require('discord-message-handler');
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = ">"

const JOSH = "292971521159200768";
const WILLY = "259209114268336129";
client.on("debug", console.log);
client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}!`);
});

client.on('message', message => {
  let channel = message.channel;

  if (message.content.startsWith(prefix + 'status')) {

  message.channel.send({embed: {
      color: 1290103,
      author: {
        name: client.user.username,
        icon_url: client.user.avatarURL
      },
      title: 'Bot status',

      description: '`Working.`',
      fields: [{
          name: 'System status:',
          value: '**__All systems and modules functioning properly__**'
        },
        {
          name: 'Packet time:',
          value: `\`${Date.now() - message.createdTimestamp} ms\``
        },
  {
          name: 'Uptime:',
          value: `\`${process.uptime()} seconds\``
        },
        {
          name: 'Avatar:',
          value: 'https://images-ext-1.discordapp.net/.eJwFwW0OwiAMANC7cABavgZdYjxLLUyX6EYA92PGu--9n_q2t5rVa4zaZwDJm85rl71lrlXL_gE-eHDr4Eya0BGhjc4FStFDoMUbEhaPjyRIJTKXYHMwU0Qk0nV73vt6lptFn9T_AohLIRY.DAP1B8BhF5M5YeVpwoK2kW_ov0c'
        },
      ],
      timestamp: new Date(),
      footer: {
        icon_url: client.user.avatarURL,
        text: 'Bot Status'
      }
    }
  });
   }

  else if (message.content === prefix + 'Sinbadx')
     channel.send('The one, the only!');

  else if (message.content === prefix + 'MeaningOfLife')
    message.reply('**42.**')

  else if (message.content === prefix + 'Xena')
    message.channel.send('Do not touch my master!');

  else if (message.content === prefix + 'Pixel')
    message.channel.send('Pixelate that. - Pixel, 2k17');

  else if (message.content === prefix + 'Trig')
    message.channel.send('**TRIGGERED!**');

  else if (message.content === prefix + 'ArX')
    message.channel.send('Run for your lives!! ArX will kill us all!');

  else if (message.content === prefix + 'Hi')
    message.channel.send('Hoi!');

  else if (message.content === prefix + 'Dreams')
    message.channel.send('Dreams will come true, just wait and see.');

  else if (message.content === prefix + 'Umi')
    message.channel.send('Credits go to my teacher, Umi.');

  else if (message.content === prefix + 'Willy')
    message.channel.send('Co-owner of Donuts. Special thanks.');

  else if (message.content === prefix + 'Embeds')
    message.channel.send('If you want embed magic without selfbot Download the app here: https://gitlab.com/garantiertnicht/DiscordEmbed/tags/0.5.2-rc  Make sure you have Java, if you have not, download here: www.java.com  Insert your credentials (Username and Password). Do not put in your token, only username and password. Have fun with the embeds ;)');

  else if (message.content.startsWith(prefix + 'Warm'))
    message.channel.send('Looks like someone is getting warmed again. -.- *Warms*');

  else if (message.content.startsWith(prefix + 'Abooses'))
    message.channel.send('*Abooses*');

  else if (message.content.startsWith(prefix + 'welcome'))
      if (message.member.hasPermission("ADMINISTRATOR"))
    message.channel.send(`${message.guild.roles.get('305302877641900052')} Welcome to Sinbadx Knights! **If you would like to get verified and be able to speak in the other channels, please answer the following questions!**\n1. How did you hear about this server?\n2. Why did you join this server?\n3. Do you promise to read <#297263352252727296>?\n4. What is your favorite diep.io tank?\nMake sure you send your answers in this channel. (Do not message them)`);
    else message.reply('You do not have the required permission.')

  else if (message.content.startsWith(prefix + 'help'))
	  message.channel.send (`**Commands:**\n >Spreadsheet\n >Xena\n >ArX\n >Sinbadx\n >Trig\n >MeaningOfLife\n >Umi\n >Willy\n >Embeds\n >Dreams\n >Hi\n >Warm\n >Pixel\n >Abooses\n >XenaCorrupt`);

  else if (message.content.startsWith(prefix + 'clear'))
      if (message.member.hasPermission("MANAGE_MESSAGES"))
      channel.bulkDelete(1,2,3,4,50)
    else message.reply('You do not have the required permission.')

  else if (message.content.startsWith(prefix + 'Spreadsheet'))
    message.channel.send ('The spreadsheet can be found at this site: https://docs.google.com/spreadsheets/d/18HlGT-Ys2Z5mFTD18QZeFgnVQunf1LqT5VxnddDnbuw/edit?usp=sharing ');

  else if (message.content === prefix + 'XenaCorrupt')
    message.channel.send('You may fall from the sky, you may fall from a tree. But the best way to fall, is in love with me. <3');

  else if(message.content.startsWith(prefix + 's')){
    if(message.author.id == JOSH || msg.author.id == WILLY){
      channel.send(msg.content.split(' ').slice(1).join(' '));
      message.delete();
    }
  }

 });

client.login(process.env.TOKEN);
<commit_msg>started anew<commit_after>const MessageHandler = require('discord-message-handler');
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = ">"

const JOSH = "292971521159200768";
const WILLY = "259209114268336129";
client.on("debug", console.log);
client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}!`);
});

client.on('message', message => {
    if (message.author.bot) return;
    MessageHandler.handleMessage(message);
});
MessageHandler.whenMessageStartsWith(prefix+"help").then(message=>{message.reply('Commands:\n >Spreadsheet\n >Xena\n >ArX\n >Sinbadx\n >Trig\n >MeaningOfLife\n >Umi\n >Willy\n >Embeds\n >Dreams\n >Hi\n >Warm\n >Pixel\n >Abooses\n >XenaCorrupt');
});
MessageHandler.whenMessageStartsWith(prefix+"welcome").then(message=>{
  member.hasPermission("ADMINISTRATOR")
  message.channel.send(`${message.guild.roles.get('305302877641900052')} Welcome to Sinbadx Knights! **If you would like to get verified and be able to speak in the other channels, please answer the following questions!**\n1. How did you hear about this server?\n2. Why did you join this server?\n3. Do you promise to read <#297263352252727296>?\n4. What is your favorite diep.io tank?\nMake sure you send your answers in this channel. (Do not message them)`);
  else msg.reply('You do not have the permission: ADMINISTRATOR')
});
client.login(process.env.TOKEN);
<|endoftext|>


<commit_before>var Discord = require('discord.io');
var winston = require('winston');

var main = require('./index.js');
var config = main.config;
var keys = main.keys;

/**** Bot Initialization ****/
var bot = new Discord.Client({
    autorun: false,
    token: keys.discord,
});

winston.info('Connecting...');
bot.connect();
module.exports = bot;

bot.active = () => {
    return bot.connected && bot.presenceStatus == "online";
};

// Make a temporary channel name with the flag additions
bot.createTemporaryChannelName = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return config.entries[guild_id].tempChannelNameFlag + name;
    }
    else {
        return name + config.entries[guild_id].tempChannelNameFlag;
    }
}
// Remove the temporary flag addition from a name to get just the rest
bot.scrubTemporaryFlag = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return name.substring(config.entries[guild_id].tempChannelNameFlag.length + 1);
    }
    else {
        return name.substring(0, name.length - config.entries[guild_id].tempChannelNameFlag.length);
    }
}

// Check if name is a temporary channel
bot.isChannelTemporary = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return name.startsWith(config.entries[guild_id].tempChannelNameFlag);
    }
    else {
        return name.endsWith(config.entries[guild_id].tempChannelNameFlag);
    }
}

bot.createTemporaryChannel = (name, guildID, callback) => {
    bot.createChannel({
        serverID: guildID,
        name: bot.createTemporaryChannelName(name, guildID),
        type: 'voice',
    }, (err,res) => {
        if (err) {
            if (err.statusCode == undefined || err.statusCode != 403) { // Don't have permission
                winston.error('Error creating temporary channel:', err);
            }

            if(callback)callback(err);

        }
        else {
            // Set permissions
            var perm = config.entries[guildID].tempChannelPermissions;
            if (perm && perm.user && perm.role) {
                var count = Object.keys(perm.user).length + Object.keys(perm.role).length;
                var complete = (error) => {
                    count --;
                    if (count == 0 || error) {
                        if(callback) callback(error);
                    }
                }

                Object.keys(perm.user).forEach(uid => {
                    bot._req('post', Discord.Endpoints.CHANNEL(res.id) + '/permissions/' + uid, {
                        type: 'member',
                        id: uid,
                        allow: perm.user[uid].allow,
                        deny: perm.user[uid].deny,
                    }, (err, res) => {
                        complete(err);
                    })
                });
                Object.keys(perm.role).forEach(rid => {
                    bot._req('put', Discord.Endpoints.CHANNEL(res.id) + '/permissions/' + rid, {
                        type: 'role',
                        id: rid,
                        allow: perm.role[rid].allow,
                        deny: perm.role[rid].deny,
                    }, (err, res) => {
                        complete(err);
                    })
                });
            }

            else if (callback) callback();
        }
    });

    // TODO info and permissions
};

bot.listOfUsersByGames = {}; // { serverID: { gameName: [userID, userID] } }
bot.listOfTempChannels = {}; // channelID: age
bot.everyoneRoles = {}; // serverID: role_ID of @everyone

bot.on('ready', (evt) => {
    winston.info('Logged in as %s - %s', bot.username, bot.id);
    winston.info("Go to https://discordapp.com/api/oauth2/authorize?client_id=" + bot.id + "&scope=bot&permissions=0 to add bot to a server");
    checkTemporaryChannels();
    bot.tempCheckInterval = setInterval(checkTemporaryChannels, config.global.tempChannelCheckInterval);

    // Check users in game to add to list
    Object.keys(bot.servers).forEach(gid => {
        if (!config.entries[gid].autoCreateByGame) return;
        bot.listOfUsersByGames[gid] = {};
        var server = bot.servers[gid];
        Object.keys(server.members).forEach(uid => {
            var user = server.members[uid];
            if (user.game && user.status == 'online') {
                if (bot.inRoles(server, user.roles, config.entries[gid].autoCreateByGameRoles)) {
                    if (bot.listOfUsersByGames[gid][user.game.name] == undefined)
                        bot.listOfUsersByGames[gid][user.game.name] = [];

                    bot.listOfUsersByGames[gid][user.game.name].push(uid);
                }
            }
        });

        checkCommonGames(gid);
    });

});

bot.on('disconnect', () => {
    winston.info('Disconnected');

    if (config.global.autoReconnect) {
        winston.info('Reconnecting in', config.global.autoReconnectInterval/1000, 'seconds');
        setTimeout(()=>bot.connect(), config.global.autoReconnectInterval)
    }
});

bot.on('any', (evt) => {
    // We are joining a server
    // Also fires on already-joined servers when starting up
    if (evt.t == 'GUILD_CREATE') {
        // Check if config entry exists for this server
        // If it doesn't, create one based off default

        if (!config.entries[evt.d.id]){
            config.createNew(evt.d.id, evt.d.name);
        }

        winston.info("Added to server", evt.d.name);
    }

    // We are leaving a server
    else if(evt.t == 'GUILD_DELETE') {
        // Maybe delete config, probably not
        winston.info("Removed from server", evt.d.name);
    }
});

/**** Command Initialization ****/
var normalizedPath = require("path").join(__dirname, "cmds");
var cmds = [];
require("fs").readdirSync(normalizedPath).forEach(function(file) {
    if (file.endsWith('.js')){
        var Clazz = require('./cmds/' + file);
        cmds.push( new Clazz(bot, config) );
    }
});

/**** Command handling ****/
bot.on('message', (user, userID, channelID, msg, evt) => {

    // Check if metioning us
    var mentioned = evt.d.mentions.some(m => m.id == bot.id );
    // Remove the mention for ease parsing command
    if (mentioned && msg.startsWith('<@' + bot.id + '>')) {
        msg = msg.substring( ('<@' + bot.id + '>').length + 1 );
    }

    var channel = bot.channels[evt.d.channel_id]
    if (channel == undefined) return; // Is a direct message, don't do anything

    var lower = msg.toLowerCase();
    var server = bot.servers[channel.guild_id];
    cmds.some(cmd => {
        if (lower.startsWith(config.entries[channel.guild_id].commandPrefix + cmd.command)) {
            if (cmd.checkUserPermissions(userID, server)){
                cmd.onCommandEntered(msg, user, userID, channel.guild_id, evt.d.channel_id); // @TODO rewrite cmds to take objects sensibly?
            }
            else {
                bot.sendMessage({
                    to: channelID,
                    message: user + ": You do not have permission to execute that command",
                });
            }

            return true;
        }
        return false;
    });
});

/**** Auto-channel creation ****/
bot.on('presence', (user, uid, status, game, evt) => {
    Object.keys(bot.servers).forEach(guild_id => {
      var server = bot.servers[guild_id];
      if(!config.entries[guild_id].autoCreateByGame) return;

      if (bot.listOfUsersByGames[guild_id] == undefined)
          bot.listOfUsersByGames[guild_id] = {};
      var serverListOfUsersByGames = bot.listOfUsersByGames[guild_id];

      if (server.members[uid]) {

          // First check if user is allowed to cause temp game channels
          if (bot.inRoles(server, evt.d.roles, config.entries[guild_id].autoCreateByGameRoles)) {
              var game = evt.d.game;
              // Add user to game list if playing game
              if (game != null) {

                  // Check if game is exempt
                  if (config.entries[guild_id].exemptAutoCreateGames.indexOf(game.name) !== -1) return;

                  if(!serverListOfUsersByGames[game.name]) serverListOfUsersByGames[game.name] = [];
                  serverListOfUsersByGames[game.name].push(uid);
                  checkCommonGames(guild_id);
              }

              // User not playing game, remove
              else if (game == null || status != 'online') {
                  Object.keys(serverListOfUsersByGames).forEach(gameName => {
                      var userList = serverListOfUsersByGames[gameName];
                      if (userList.indexOf(uid) >= 0) {
                          userList.splice(userList.indexOf(uid), 1);
                      }
                  });
              }

          }

      }
    });
});

function getNumberOfUsersPlayingGame(gameName, guildID){
    if (!bot.listOfUsersByGames[guildID]) return 0;
    if (!bot.listOfUsersByGames[guildID][gameName]) return 0;
    // Update list to only include online members
    var arr = bot.listOfUsersByGames[guildID][gameName];
    arr = bot.listOfUsersByGames[guildID][gameName] = arr.filter(uid => {
      var member = bot.servers[guildID].members[uid];
      return member.status == 'online';
    });

    return bot.listOfUsersByGames[guildID][gameName].length;
}

function checkCommonGames(serverID) {
    if (!config.entries[serverID].autoCreateByGame) return;

    Object.keys(bot.listOfUsersByGames[serverID]).forEach(gameName => {
        // There is at least autoCreateByGameCommon people playing this game
        if (getNumberOfUsersPlayingGame(gameName, serverID) >= config.entries[serverID].autoCreateByGameCommon) {

            // Check if there is already a channel
            var filter = Object.keys(bot.servers[serverID].channels).filter(cid => {
                var channel = bot.channels[cid];
                return channel.name.indexOf(gameName) !== -1;
            });
            if (filter.length == 0)  {
                bot.createTemporaryChannel(' ' + gameName, serverID);
            }
        }
    });
}

/**** Temporary-channel destruction ****/

function checkTemporaryChannels() {
    if (bot && bot.active()) {

        Object.keys(bot.channels).map(chanID => {
            var channel = bot.channels[chanID];
            var guild_id = channel.guild_id;

            // Check if is temp channel
            if (channel.type == 'voice' && bot.isChannelTemporary(channel.name, guild_id)) {
                // Add to age
                if (bot.listOfTempChannels[chanID] != undefined) {
                    // check number of users
                    if (Object.keys(channel.members).length == 0) {

                        // Check to see if game was created for common-games
                        if (config.entries[guild_id].autoCreateByGame) {
                            var gameName = bot.scrubTemporaryFlag(channel.name, guild_id);
                            if (getNumberOfUsersPlayingGame(gameName, guild_id) >= config.entries[guild_id].autoCreateByGameCommon) {
                                bot.listOfTempChannels[chanID] = 0;
                                return;
                            }
                        }

                        bot.listOfTempChannels[chanID] += config.global.tempChannelCheckInterval;
                        if (bot.listOfTempChannels[chanID] >= config.entries[guild_id].tempChannelTimeout) {
                            bot.deleteChannel(chanID, (err, res) => {
                                if (err && (!err.statusCode || err.statusCode != 403))
                                    winston.error('Error deleting temporary channel:', err);
                            });
                            delete bot.listOfTempChannels[chanID];
                        }
                    }
                    else {
                        bot.listOfTempChannels[chanID] = 0;
                    }
                }
                else
                    bot.listOfTempChannels[chanID] = 0;
            }
        });
    }
};

// Checks if any of the roles in roleIDs is in the list of roles
// Second param is comma-delimted string
bot.inRoles = function(server, roleIDs, roles) {
    for(var i = 0; i < roleIDs.length; i++ ){
        var roleID = roleIDs[i];
        var filter = roles.filter(r => roleID == r);
        if (filter.length > 0) return true;
    }
    return false;
};

function hasPermission(bit, perm) {
    return ((perm >> bit) & 1) == 1;
}

bot.isAdministrator = function(guild_id, user_id) {
    var server = bot.servers[guild_id];
    var member = server.members[user_id];
    if (member) {
        for (var i in Object.keys(member.roles)) {
            var role = server.roles[member.roles[i]];
            if ( hasPermission(Discord.Permissions.GENERAL_ADMINISTRATOR, role._permissions) )
                return true;
        }
    }

    return false;
};

bot.isGlobalAdministrator = function (user_id) {
    return config.global.administrators.indexOf(user_id) != -1;
};

<commit_msg>Fix for random crashing<commit_after>var Discord = require('discord.io');
var winston = require('winston');

var main = require('./index.js');
var config = main.config;
var keys = main.keys;

/**** Bot Initialization ****/
var bot = new Discord.Client({
    autorun: false,
    token: keys.discord,
});

winston.info('Connecting...');
bot.connect();
module.exports = bot;

bot.active = () => {
    return bot.connected && bot.presenceStatus == "online";
};

// Make a temporary channel name with the flag additions
bot.createTemporaryChannelName = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return config.entries[guild_id].tempChannelNameFlag + name;
    }
    else {
        return name + config.entries[guild_id].tempChannelNameFlag;
    }
}
// Remove the temporary flag addition from a name to get just the rest
bot.scrubTemporaryFlag = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return name.substring(config.entries[guild_id].tempChannelNameFlag.length + 1);
    }
    else {
        return name.substring(0, name.length - config.entries[guild_id].tempChannelNameFlag.length);
    }
}

// Check if name is a temporary channel
bot.isChannelTemporary = (name, guild_id) => {
    if (config.entries[guild_id].tempChannelFlagLocation == 'start') {
        return name.startsWith(config.entries[guild_id].tempChannelNameFlag);
    }
    else {
        return name.endsWith(config.entries[guild_id].tempChannelNameFlag);
    }
}

bot.createTemporaryChannel = (name, guildID, callback) => {
    bot.createChannel({
        serverID: guildID,
        name: bot.createTemporaryChannelName(name, guildID),
        type: 'voice',
    }, (err,res) => {
        if (err) {
            if (err.statusCode == undefined || err.statusCode != 403) { // Don't have permission
                winston.error('Error creating temporary channel:', err);
            }

            if(callback)callback(err);

        }
        else {
            // Set permissions
            var perm = config.entries[guildID].tempChannelPermissions;
            if (perm && perm.user && perm.role) {
                var count = Object.keys(perm.user).length + Object.keys(perm.role).length;
                var complete = (error) => {
                    count --;
                    if (count == 0 || error) {
                        if(callback) callback(error);
                    }
                }

                Object.keys(perm.user).forEach(uid => {
                    bot._req('post', Discord.Endpoints.CHANNEL(res.id) + '/permissions/' + uid, {
                        type: 'member',
                        id: uid,
                        allow: perm.user[uid].allow,
                        deny: perm.user[uid].deny,
                    }, (err, res) => {
                        complete(err);
                    })
                });
                Object.keys(perm.role).forEach(rid => {
                    bot._req('put', Discord.Endpoints.CHANNEL(res.id) + '/permissions/' + rid, {
                        type: 'role',
                        id: rid,
                        allow: perm.role[rid].allow,
                        deny: perm.role[rid].deny,
                    }, (err, res) => {
                        complete(err);
                    })
                });
            }

            else if (callback) callback();
        }
    });

    // TODO info and permissions
};

bot.listOfUsersByGames = {}; // { serverID: { gameName: [userID, userID] } }
bot.listOfTempChannels = {}; // channelID: age
bot.everyoneRoles = {}; // serverID: role_ID of @everyone

bot.on('ready', (evt) => {
    winston.info('Logged in as %s - %s', bot.username, bot.id);
    winston.info("Go to https://discordapp.com/api/oauth2/authorize?client_id=" + bot.id + "&scope=bot&permissions=0 to add bot to a server");
    checkTemporaryChannels();
    bot.tempCheckInterval = setInterval(checkTemporaryChannels, config.global.tempChannelCheckInterval);

    // Check users in game to add to list
    Object.keys(bot.servers).forEach(gid => {
        if (!config.entries[gid].autoCreateByGame) return;
        bot.listOfUsersByGames[gid] = {};
        var server = bot.servers[gid];
        if (server.members == undefined) return;
        Object.keys(server.members).forEach(uid => {
            var user = server.members[uid];
            if (user.game && user.status == 'online') {
                if (bot.inRoles(server, user.roles, config.entries[gid].autoCreateByGameRoles)) {
                    if (bot.listOfUsersByGames[gid][user.game.name] == undefined)
                        bot.listOfUsersByGames[gid][user.game.name] = [];

                    bot.listOfUsersByGames[gid][user.game.name].push(uid);
                }
            }
        });

        checkCommonGames(gid);
    });

});

bot.on('disconnect', (err, code) => {
    winston.info('Disconnected Err:', err, 'Code:', code);

    if (config.global.autoReconnect) {
        winston.info('Reconnecting in', config.global.autoReconnectInterval/1000, 'seconds');
        setTimeout(()=>bot.connect(), config.global.autoReconnectInterval)
    }
});

bot.on('any', (evt) => {
    // We are joining a server
    // Also fires on already-joined servers when starting up
    if (evt.t == 'GUILD_CREATE') {
        // Check if config entry exists for this server
        // If it doesn't, create one based off default

        if (!config.entries[evt.d.id]){
            config.createNew(evt.d.id, evt.d.name);
        }

        winston.info("Added to server", evt.d.name);
    }

    // We are leaving a server
    else if(evt.t == 'GUILD_DELETE') {
        // Maybe delete config, probably not
        winston.info("Removed from server", evt.d.name);
    }
});

/**** Command Initialization ****/
var normalizedPath = require("path").join(__dirname, "cmds");
var cmds = [];
require("fs").readdirSync(normalizedPath).forEach(function(file) {
    if (file.endsWith('.js')){
        var Clazz = require('./cmds/' + file);
        cmds.push( new Clazz(bot, config) );
    }
});

/**** Command handling ****/
bot.on('message', (user, userID, channelID, msg, evt) => {

    // Check if metioning us
    var mentioned = evt.d.mentions.some(m => m.id == bot.id );
    // Remove the mention for ease parsing command
    if (mentioned && msg.startsWith('<@' + bot.id + '>')) {
        msg = msg.substring( ('<@' + bot.id + '>').length + 1 );
    }

    var channel = bot.channels[evt.d.channel_id]
    if (channel == undefined) return; // Is a direct message, don't do anything

    var lower = msg.toLowerCase();
    var server = bot.servers[channel.guild_id];
    cmds.some(cmd => {
        if (lower.startsWith(config.entries[channel.guild_id].commandPrefix + cmd.command)) {
            if (cmd.checkUserPermissions(userID, server)){
                cmd.onCommandEntered(msg, user, userID, channel.guild_id, evt.d.channel_id); // @TODO rewrite cmds to take objects sensibly?
            }
            else {
                bot.sendMessage({
                    to: channelID,
                    message: user + ": You do not have permission to execute that command",
                });
            }

            return true;
        }
        return false;
    });
});

/**** Auto-channel creation ****/
bot.on('presence', (user, uid, status, game, evt) => {
    Object.keys(bot.servers).forEach(guild_id => {
      var server = bot.servers[guild_id];
      if(!config.entries[guild_id].autoCreateByGame || server.members == undefined) return;

      if (bot.listOfUsersByGames[guild_id] == undefined)
          bot.listOfUsersByGames[guild_id] = {};
      var serverListOfUsersByGames = bot.listOfUsersByGames[guild_id];

      if (server.members[uid]) {

          // First check if user is allowed to cause temp game channels
          if (bot.inRoles(server, evt.d.roles, config.entries[guild_id].autoCreateByGameRoles)) {
              var game = evt.d.game;
              // Add user to game list if playing game
              if (game != null) {

                  // Check if game is exempt
                  if (config.entries[guild_id].exemptAutoCreateGames.indexOf(game.name) !== -1) return;

                  if(!serverListOfUsersByGames[game.name]) serverListOfUsersByGames[game.name] = [];
                  serverListOfUsersByGames[game.name].push(uid);
                  checkCommonGames(guild_id);
              }

              // User not playing game, remove
              else if (game == null || status != 'online') {
                  Object.keys(serverListOfUsersByGames).forEach(gameName => {
                      var userList = serverListOfUsersByGames[gameName];
                      if (userList.indexOf(uid) >= 0) {
                          userList.splice(userList.indexOf(uid), 1);
                      }
                  });
              }

          }

      }
    });
});

function getNumberOfUsersPlayingGame(gameName, guildID){
    if (!bot.listOfUsersByGames[guildID]) return 0;
    if (!bot.listOfUsersByGames[guildID][gameName]) return 0;
    // Update list to only include online members
    var arr = bot.listOfUsersByGames[guildID][gameName];
    arr = bot.listOfUsersByGames[guildID][gameName] = arr.filter(uid => {
      var member = bot.servers[guildID].members[uid];
      return member.status == 'online';
    });

    return bot.listOfUsersByGames[guildID][gameName].length;
}

function checkCommonGames(serverID) {
    if (!config.entries[serverID].autoCreateByGame) return;

    Object.keys(bot.listOfUsersByGames[serverID]).forEach(gameName => {
        // There is at least autoCreateByGameCommon people playing this game
        if (getNumberOfUsersPlayingGame(gameName, serverID) >= config.entries[serverID].autoCreateByGameCommon) {

            // Check if there is already a channel
            var filter = Object.keys(bot.servers[serverID].channels).filter(cid => {
                var channel = bot.channels[cid];
                return channel.name.indexOf(gameName) !== -1;
            });
            if (filter.length == 0)  {
                bot.createTemporaryChannel(' ' + gameName, serverID);
            }
        }
    });
}

/**** Temporary-channel destruction ****/

function checkTemporaryChannels() {
    if (bot && bot.active()) {

        Object.keys(bot.channels).map(chanID => {
            var channel = bot.channels[chanID];
            var guild_id = channel.guild_id;

            // Check if is temp channel
            if (channel.type == 'voice' && bot.isChannelTemporary(channel.name, guild_id)) {
                // Add to age
                if (bot.listOfTempChannels[chanID] != undefined) {
                    // check number of users
                    if (Object.keys(channel.members).length == 0) {

                        // Check to see if game was created for common-games
                        if (config.entries[guild_id].autoCreateByGame) {
                            var gameName = bot.scrubTemporaryFlag(channel.name, guild_id);
                            if (getNumberOfUsersPlayingGame(gameName, guild_id) >= config.entries[guild_id].autoCreateByGameCommon) {
                                bot.listOfTempChannels[chanID] = 0;
                                return;
                            }
                        }

                        bot.listOfTempChannels[chanID] += config.global.tempChannelCheckInterval;
                        if (bot.listOfTempChannels[chanID] >= config.entries[guild_id].tempChannelTimeout) {
                            bot.deleteChannel(chanID, (err, res) => {
                                if (err && (!err.statusCode || err.statusCode != 403))
                                    winston.error('Error deleting temporary channel:', err);
                            });
                            delete bot.listOfTempChannels[chanID];
                        }
                    }
                    else {
                        bot.listOfTempChannels[chanID] = 0;
                    }
                }
                else
                    bot.listOfTempChannels[chanID] = 0;
            }
        });
    }
};

// Checks if any of the roles in roleIDs is in the list of roles
// Second param is comma-delimted string
bot.inRoles = function(server, roleIDs, roles) {
    for(var i = 0; i < roleIDs.length; i++ ){
        var roleID = roleIDs[i];
        var filter = roles.filter(r => roleID == r);
        if (filter.length > 0) return true;
    }
    return false;
};

function hasPermission(bit, perm) {
    return ((perm >> bit) & 1) == 1;
}

bot.isAdministrator = function(guild_id, user_id) {
    var server = bot.servers[guild_id];
    var member = server.members[user_id];
    if (member) {
        for (var i in Object.keys(member.roles)) {
            var role = server.roles[member.roles[i]];
            if ( hasPermission(Discord.Permissions.GENERAL_ADMINISTRATOR, role._permissions) )
                return true;
        }
    }

    return false;
};

bot.isGlobalAdministrator = function (user_id) {
    return config.global.administrators.indexOf(user_id) != -1;
};

<|endoftext|>


<commit_before>var net = require('net'),
irc = {},
config = require('./config'),
redis_lib = require('redis'),
redis = redis_lib.createClient();

irc.socket = new net.Socket();

irc.socket.on('data', function(data) {
    data = data.split('\n');
    for (var i = 0; i < data.length; i++) {
	console.log('RECV -', data[i]);
	if (data !== '') {
	    irc.handle(data[i].slice(0, -1));
	}
    }
});

irc.socket.on('connect', function() {
    console.log('Established connection...');

    irc.on(/^PING :(.+)$/i, function(info) {
	irc.raw('PONG :' + info[1]);
    });

    irc.on(/^:(.*?)!.*?PRIVMSG (#?\w+) :(.*)$/, function(info) {
	message = {
	    channel: info[2],
	    sender: info[1],
	    message: info[3],
	}
	redis.publish('in', JSON.stringify(message));
    });

    irc.input = redis_lib.createClient();
    irc.input.subscribe('out');
    irc.input.on('message', function(channel, message) {
	msg = JSON.parse(message)
	irc.message(msg.channel, msg.message);
    });

    setTimeout(function() {
	irc.raw('NICK ' + config.user.nick);
	irc.raw('USER ' + config.user.user + ' 8 * :' + config.user.real);
	setTimeout(function() {
	    for (var i in config.chans) {
		irc.join(i, config.chans[i]);
	    }
	}, 2000);
    }, 1000);
});

irc.socket.setEncoding('ascii');
irc.socket.setNoDelay();
irc.socket.connect(config.server.port, config.server.addr);

//handles incoming messages
irc.handle = function(data) {
    var i, info;
    for (i = 0; i < irc.listeners.length; i++) {
	info = irc.listeners[i][0].exec(data);
	if (info) {
	    irc.listeners[i][1](info, data);
	    if (irc.listeners[i][2]) {
		irc.listeners.splice(i, 1);
	    }
	}
    }
};

irc.join = function(channel, password) {
    irc.raw('JOIN #' + channel + ' ' + password);
};

irc.message = function(channel, message) {
    console.log('MSG - ' + channel + ' : ' + message);
    irc.raw('PRIVMSG ' + channel + ' :' + message);
};

irc.listeners = [];
irc.on = function(data, callback) {
    irc.listeners.push([data, callback, false]);
};

irc.on_once = function(data, callback) {
    irc.listeners.push([data, callback, true]);
};

irc.raw = function(data) {
    irc.socket.write(data + '\n', 'ascii', function() {
	console.log('SENT -', data);
    });
};<commit_msg>code cleanup<commit_after>var net = require('net'),
irc = {},
config = require('./config'),
redis_lib = require('redis'),
redis = redis_lib.createClient();

irc.socket = new net.Socket();

irc.socket.on('data', function(data) {
    data = data.split('\n');
    for (var i = 0; i < data.length; i++) {
	console.log('RECV -', data[i]);
	if (data !== '') {
	    irc.handle(data[i].slice(0, -1));
	}
    }
});

irc.socket.on('connect', function() {
    console.log('Established connection...');

    irc.on(/^PING :(.+)$/i, function(info) {
	irc.raw('PONG :' + info[1]);
    });

    irc.on(/^:(.*?)!.*?PRIVMSG (#?\w+) :(.*)$/, function(info) {
	message = {
	    channel: info[2],
	    sender: info[1],
	    message: info[3]
	};
	redis.publish('in', JSON.stringify(message));
    });

    irc.input = redis_lib.createClient();
    irc.input.subscribe('out');
    irc.input.on('message', function(channel, message) {
	msg = JSON.parse(message);
	irc.message(msg.channel, msg.message);
    });

    setTimeout(function() {
	irc.raw('NICK ' + config.user.nick);
	irc.raw('USER ' + config.user.user + ' 8 * :' + config.user.real);
	setTimeout(function() {
	    for (var i in config.chans) {
		irc.join(i, config.chans[i]);
	    }
	}, 2000);
    }, 1000);
});

irc.socket.setEncoding('ascii');
irc.socket.setNoDelay();
irc.socket.connect(config.server.port, config.server.addr);

//handles incoming messages
irc.handle = function(data) {
    var i, info;
    for (i = 0; i < irc.listeners.length; i++) {
	info = irc.listeners[i][0].exec(data);
	if (info) {
	    irc.listeners[i][1](info, data);
	    if (irc.listeners[i][2]) {
		irc.listeners.splice(i, 1);
	    }
	}
    }
};

irc.join = function(channel, password) {
    irc.raw('JOIN #' + channel + ' ' + password);
};

irc.message = function(channel, message) {
    console.log('MSG - ' + channel + ' : ' + message);
    irc.raw('PRIVMSG ' + channel + ' :' + message);
};

irc.listeners = [];
irc.on = function(data, callback) {
    irc.listeners.push([data, callback, false]);
};

irc.on_once = function(data, callback) {
    irc.listeners.push([data, callback, true]);
};

irc.raw = function(data) {
    irc.socket.write(data + '\n', 'ascii', function() {
	console.log('SENT -', data);
    });
};
<|endoftext|>