<commit_before>const Discord = require('discord.js');
const bot = new Discord.Client();
const config = require("./config.json");

/******************************************************************
 *
 *  BoT ready
 *  Informa se o BoT realmente está online
 *  Mostra o gaming status atual do BoT
 *
 * ***************************************************************/
bot.on('ready', () =>
{//inicio
    bot.user.setGame('Hentai !escrava');
    console.log('A sua Escrava esta pronta!');
});//fim

/******************************************************************
 *
 *  Novo usuario adicionado
 *  Manda mensagem de boas vindas no chat para o novo usuario
 *
 * ***************************************************************/
bot.on("guildMemberAdd", member =>
{//inicio
    let guild = member.guild;
    guild.defaultChannel.sendMessage('Ola!, ${member.user}. Eu serei a sua escrava. Seja bem vindo(a). Se precisar de mim use o comando **!escrava** para me chamar. :revolving_hearts:');
});//fim

/******************************************************************
 *
 *  Novo usuario adicionado
 *  Log informativo no console
 *
 * ***************************************************************/
bot.on("guildCreate", guild =>
{//inicio
    console.log('Novo(a) usuário : ${guild.name}, foi adicionado por ${guild.owner.user.username}');
});//fim

/******************************************************************
 *
 *  Comando
 *  Prefixo = !
 *  Usado para enviar os comandos para o BoT
 *
 * ***************************************************************/
//inicio commando
bot.on('message', message =>
{ //inicio para prefixo comando
    if(message.author.bot) return;
    if(!message.content.startsWith(config.prefix)) return;

    let command = message.content.split(" ")[0];
    command = command.slice(config.prefix.length);

    let args = message.content.split(" ").slice(1);

    /******************************************************************
     *
     *  Calculos matemáticos
     *  Somar, Subtrair, Multiplicar, Dividr
     *  Qualquer um pode usar
     *
     * ***************************************************************/
    //somar
    /*if(command === "soma")    { let numArray = args.map(n=> parseInt(n));    let total = numArray.reduce( (p,c) => p+c);  message.channel.sendMessage(total);   }

    //subtrair
    if(command === "sub")   { let numArray = args.map(n=> parseInt(n));   let total = numArray.reduce( (p,c) => p-c);  message.channel.sendMessage(total);    }

    //multiplicar
    if(command === "mult")  { let numArray = args.map(n=> parseInt(n));  let total = numArray.reduce( (p,c) => p*c); message.channel.sendMessage(total);  }*/

    /******************************************************************
     *
     *  Comando Falar
     *  Usado para enviar mensagens em nome do BoT
     *  Apenas o Mestre pode usa-lo
     *
     * ***************************************************************/
    //Faz o bot dizer alguma coisa
    if(command === "falar")
    {//inicio
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {//inicio if
            message.channel.sendMessage(args.join(" "));
        }//fim if
        else
        {//inicio else
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts:");
        }//fim else
    }//fim

    /******************************************************************
     *
     *  Comando Ping
     *  Usado para mostrar o ping atual no servidor
     *  Qualquer um pode usar
     *
     * ***************************************************************/
    //ping
    if(command === "ping")
    {//inicio
        message.channel.sendMessage(`**Pong!** \`${Date.now() - message.createdTimestamp } ms\``);
    }//fim

    /******************************************************************
     *
     *  Comando Roll
     *  Usado para rolar um dado comum de 6 lados
     *  e obter um valor random entre esses números
     *  Qualquer um pode usar
     *
     * ***************************************************************/
    //roll
    if(command === "roll")
    {//inicio
        var roll = Math.floor(Math.random() * 6) + 1;
        message.reply("Você tirou " + roll);
    }//fim

    /******************************************************************
     *
     *  Comando Limpar / Purge / Clear
     *  Usado para limpar / apagar tudo que existe na tela
     *  Apenas o mestre pode usar
     *
     * ***************************************************************/
    //purge - deleta msg do servidor
    if(command === "limpar")
    {//inicio
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {//inicio if
            let messagecount = parseInt(args.join(' '));
            then(message.channel.bulkDelete(messages));
            message.channel.fetchMessages({limit: messagecount}).then(messages => message.channel.bulkDelete(messages));
        }//fim if
        else
        {//inicio else
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts:");
        }//fim else
    }//fim

    /******************************************************************
     *
     *  msg para outro canal
     *
     * ***************************************************************/

    //msg sala #salvos - id 269932626482167810 -------------------------------
    if(command === "salvar")
    {
        bot.channels.get('269932626482167810').sendMessage(args.join(" "));
    }

    //msg sala #supremosos - id 167715230082662401 -------------------------------
    if(command === "supremososfalar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            bot.channels.get('167715230082662401').sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts:");
        }
    }

    //msg sala #eventos id - 269005594462126080 -------------------------------
    if(command === "eventosfalar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            bot.channels.get('269005594462126080').sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts:");
        }
    }

    //msg sala #restrito id 269010915456843777 -------------------------------
    if(command === "restritofalar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            bot.channels.get('269010915456843777').sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts: ");
        }
    }

    //msg sala #admin id 269009554308726784 -------------------------------
    if(command === "adminfalar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            bot.channels.get('269009554308726784').sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts: ");
        }
    }

    /******************************************************************
     *
     *  banir
     *
     * ***************************************************************/
    //ban
    if(command === "ban")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            message.channel.sendMessage("Preparando para banir...");
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts: ");
        }
    }

    /******************************************************************
     *
     *  help
     *
     * ***************************************************************/
    //help
    if(command === "ajuda")
    {
        message.channel.sendMessage("Lista de comandos para mandar em mim. :revolving_hearts: \n"+
                                    "**!ajuda** - Listar todos os comandos liberados para usuários normais.\n"+
                                    "**!ping** - Mostra o seu ping atual.\n"+
                                    "**!roll** - Rolar um dado comum de 6 lados.\n"+
                                    "**!mover @nome canal** - (Hmm o meu mestre ainda está tendo problemas com esse código hihi)\n"+
                                    "**!salvar texto** - Salvar mensagens no canal **#salvos**\n"+
                                    "**O sistema de webhook** é Gerenciado pelo **Mestre.**\n");
    }

    /******************************************************************
     *
     *  conversar com o bot - escrava
     *
     * ***************************************************************/
    //conversar
    if(command === "morra")
    {
        message.reply("Morra você! Humn");
    }
    if ((command === "escrava") || (command === "Escrava"))
    {
        message.reply("Me chamou? Se precisar de algo use o comando !ajuda para saber como mandar em mim!");
    }

     /****/

    if (command === "mover")
    {
        if(message.mentions.users.size === 0)
        {
            return message.reply("Digite um nome correto para mover").catch(console.error);
        }
    }

    /*****/

/******************************************************************
 *
 *  Kickar Usuario - ONLY - mestre e admin
 *
 * ***************************************************************/
    if(command === "kick")
    {
        let modRole = message.guild.roles.find("name", "Mestre");

    if (!message.member.roles.has(modRole.id))
        {
            return message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts: ").catch(console.error);
        }

        if(message.mentions.users.size === 0)
        {
            return message.reply("Digite um nome correto para kickar").catch(console.error);
        }
        let kickMember = message.guild.member(message.mentions.users.first());
        if(!kickMember)
        {
            return message.reply("O usuário digitado não existe");
        }
        if (!message.guild.member(bot.user).hasPermission("KICK_MEMBERS"))
        {
            return message.reply("Eu não tenho permissão para kickar").catch(console.error);
        }
        kickMember.kick().then(member =>
        {
            message.reply('${member.user.username} foi kickado com sucesso. Morra :revolving_hearts: ').catch(console.error);
        }).catch(console.error)
    }

});//fim para prefixo commando

/******************************************************************
 *
 *  bot login e prefix ! - config.json
 *
 * ***************************************************************/
bot.login(config.token)<commit_msg>Added<commit_after>const Discord = require('discord.js');
const bot = new Discord.Client();
const config = require("./config.json");

/******************************************************************
 *
 *  BoT ready
 *  Informa se o BoT realmente está online
 *  Mostra o gaming status atual do BoT
 *
 * ***************************************************************/
bot.on('ready', () =>
{//inicio
    bot.user.setGame('Hentai !escrava');
    console.log('A sua Escrava esta pronta!');
});//fim

/******************************************************************
 *
 *  Novo usuario adicionado
 *  Manda mensagem de boas vindas no chat para o novo usuario
 *
 * ***************************************************************/
bot.on("guildMemberAdd", member =>
{//inicio
    let guild = member.guild;
    guild.defaultChannel.sendMessage('Ola!, ${member.user}. Eu serei a sua escrava. Seja bem vindo(a). Se precisar de mim use o comando **!escrava** para me chamar. :revolving_hearts:');
});//fim

/******************************************************************
 *
 *  Novo usuario adicionado
 *  Log informativo no console
 *
 * ***************************************************************/
bot.on("guildCreate", guild =>
{//inicio
    console.log('Novo(a) usuário : ${guild.name}, foi adicionado por ${guild.owner.user.username}');
});//fim

/******************************************************************
 *
 *  Comando
 *  Prefixo = !
 *  Usado para enviar os comandos para o BoT
 *
 * ***************************************************************/
//inicio commando
bot.on('message', message =>
{ //inicio para prefixo comando
    if(message.author.bot) return;
    if(!message.content.startsWith(config.prefix)) return;

    let command = message.content.split(" ")[0];
    command = command.slice(config.prefix.length);

    let args = message.content.split(" ").slice(1);

    /******************************************************************
     *
     *  Calculos matemáticos
     *  Somar, Subtrair, Multiplicar, Dividr
     *  Qualquer um pode usar
     *
     * ***************************************************************/
    //somar
    /*if(command === "soma")    { let numArray = args.map(n=> parseInt(n));    let total = numArray.reduce( (p,c) => p+c);  message.channel.sendMessage(total);   }

    //subtrair
    if(command === "sub")   { let numArray = args.map(n=> parseInt(n));   let total = numArray.reduce( (p,c) => p-c);  message.channel.sendMessage(total);    }

    //multiplicar
    if(command === "mult")  { let numArray = args.map(n=> parseInt(n));  let total = numArray.reduce( (p,c) => p*c); message.channel.sendMessage(total);  }*/

    /******************************************************************
     *
     *  Comando Falar
     *  Usado para enviar mensagens em nome do BoT
     *  Apenas o Mestre pode usa-lo
     *
     * ***************************************************************/
    //Faz o bot dizer alguma coisa
    if(command === "falar")
    {//inicio
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {//inicio if
            message.channel.sendMessage(args.join(" "));
        }//fim if
        else
        {//inicio else
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts:");
        }//fim else
    }//fim

    /******************************************************************
     *
     *  Comando Ping
     *  Usado para mostrar o ping atual no servidor
     *  Qualquer um pode usar
     *
     * ***************************************************************/
    //ping
    if(command === "ping")
    {//inicio
        message.channel.sendMessage(`**Pong!** \`${Date.now() - message.createdTimestamp } ms\``);
    }//fim

    /******************************************************************
     *
     *  Comando Roll
     *  Usado para rolar um dado comum de 6 lados
     *  e obter um valor random entre esses números
     *  Qualquer um pode usar
     *
     * ***************************************************************/
    //roll
    if(command === "roll")
    {//inicio
        var roll = Math.floor(Math.random() * 6) + 1;
        message.reply("Você tirou " + roll);
    }//fim

    /******************************************************************
     *
     *  Comando Limpar / Purge / Clear
     *  Usado para limpar / apagar tudo que existe na tela
     *  Apenas o mestre pode usar
     *
     * ***************************************************************/
    //purge - deleta msg do servidor
    if(command === "limpar")
    {//inicio
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {//inicio if
            let messagecount = parseInt(args.join(' '));
            message.channel.fetchMessages({limit: messagecount}).then(messages => message.channel.bulkDelete(messages));
        }//fim if
        else
        {//inicio else
            message.reply("Você não tem poder para usar este comando! Morra :heartpulse:");
        }//fim else
    }//fim

    /******************************************************************
     *
     *  msg para outro canal
     *
     * ***************************************************************/

    //msg sala #salvos - id 269932626482167810 -------------------------------
    if(command === "salvar")
    {
        bot.channels.get('269932626482167810').sendMessage(args.join(" "));
    }

    //msg sala #supremosos - id 167715230082662401 -------------------------------
    if(command === "supremososfalar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            bot.channels.get('167715230082662401').sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts:");
        }
    }

    //msg sala #eventos id - 269005594462126080 -------------------------------
    if(command === "eventosfalar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            bot.channels.get('269005594462126080').sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts:");
        }
    }

    //msg sala #restrito id 269010915456843777 -------------------------------
    if(command === "restritofalar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            bot.channels.get('269010915456843777').sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts: ");
        }
    }

    //msg sala #admin id 269009554308726784 -------------------------------
    if(command === "adminfalar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            bot.channels.get('269009554308726784').sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts: ");
        }
    }

    /******************************************************************
     *
     *  banir
     *
     * ***************************************************************/
    //ban
    if(command === "ban")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            message.channel.sendMessage("Preparando para banir...");
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts: ");
        }
    }

    /******************************************************************
     *
     *  help
     *
     * ***************************************************************/
    //help
    if(command === "ajuda")
    {
        message.channel.sendMessage("Lista de comandos para mandar em mim. :revolving_hearts: \n"+
                                    "**!ajuda** - Listar todos os comandos liberados para usuários normais.\n"+
                                    "**!ping** - Mostra o seu ping atual.\n"+
                                    "**!roll** - Rolar um dado comum de 6 lados.\n"+
                                    "**!mover @nome canal** - (Hmm o meu mestre ainda está tendo problemas com esse código hihi)\n"+
                                    "**!salvar texto** - Salvar mensagens no canal **#salvos**\n"+
                                    "**O sistema de webhook** é Gerenciado pelo **Mestre.**\n");
    }

    /******************************************************************
     *
     *  conversar com o bot - escrava
     *
     * ***************************************************************/
    //conversar
    if(command === "morra")
    {
        message.reply("Morra você! Humn");
    }
    if ((command === "escrava") || (command === "Escrava"))
    {
        message.reply("Me chamou? Se precisar de algo use o comando !ajuda para saber como mandar em mim!");
    }

     /****/

    if (command === "mover")
    {
        if(message.mentions.users.size === 0)
        {
            return message.reply("Digite um nome correto para mover").catch(console.error);
        }
    }

    /*****/

/******************************************************************
 *
 *  Kickar Usuario - ONLY - mestre e admin
 *
 * ***************************************************************/
    if(command === "kick")
    {
        let modRole = message.guild.roles.find("name", "Mestre");

    if (!message.member.roles.has(modRole.id))
        {
            return message.reply("Você não tem poder para usar este comando! Morra :revolving_hearts: ").catch(console.error);
        }

        if(message.mentions.users.size === 0)
        {
            return message.reply("Digite um nome correto para kickar").catch(console.error);
        }
        let kickMember = message.guild.member(message.mentions.users.first());
        if(!kickMember)
        {
            return message.reply("O usuário digitado não existe");
        }
        if (!message.guild.member(bot.user).hasPermission("KICK_MEMBERS"))
        {
            return message.reply("Eu não tenho permissão para kickar").catch(console.error);
        }
        kickMember.kick().then(member =>
        {
            message.reply('${member.user.username} foi kickado com sucesso. Morra :revolving_hearts: ').catch(console.error);
        }).catch(console.error)
    }

});//fim para prefixo commando

/******************************************************************
 *
 *  bot login e prefix ! - config.json
 *
 * ***************************************************************/
bot.login(config.token)<|endoftext|>


<commit_before>var redis_lib = require('redis');
var pub = redis_lib.createClient();
var sub = redis_lib.createClient();
var irc = require('irc');
var api = require('./services/lib/api');
var config = api.load_config('bot.json');

function server_config_for(idx) {
    var cfg = config.servers[idx]
    /* server-generic options */
	cfg.debug = config.options.debug;
	cfg.floodProtection = config.options.floodProtection;
	cfg.showErrors = config.options.debug;
	cfg.stripColors = config.options.stripColors;
	return cfg;
}

function output_version_1(message) {
    console.log('output_version_1');
    switch (message.type) {
    case 'privmsg':
	console.log('  privmsg');
	bot.say(message.data.to, message.data.message);
	break;
    case 'raw':
	console.log('  raw');
	bot.send(message.command);
	break;
    }
}

function setup() {
	var cfg = server_config_for(0)
	var bot = new irc.Client(cfg.hostname, cfg.nick, cfg);

	bot.addListener('message', function(nick, to, text, message) {
	    console.log(nick + ' said ' + text + ' to ' + to);
	    msg = {
		version: 1,
		type: 'privmsg',
		data: {
		    sender: nick,
		    channel: to,
		    message: text,
		},
	    };
	    pub.publish('in', JSON.stringify(msg));
	});

	var output_handlers = {
	    1: output_version_1,
	};

	sub.subscribe('out')
	sub.on('message', function(channel, message) {
	    msg = JSON.parse(message);
	    output_handlers[msg.version](msg)
	});
}

setup();<commit_msg>spacing fixes, let the user know the bot has started.<commit_after>var redis_lib = require('redis');
var pub = redis_lib.createClient();
var sub = redis_lib.createClient();
var irc = require('irc');
var api = require('./services/lib/api');
var config = api.load_config('bot.json');

function server_config_for(idx) {
    var cfg = config.servers[idx]
    /* server-generic options */
	cfg.debug = config.options.debug;
	cfg.floodProtection = config.options.floodProtection;
	cfg.showErrors = config.options.debug;
	cfg.stripColors = config.options.stripColors;
	return cfg;
}

function output_version_1(message) {
    switch (message.type) {
		case 'privmsg':
			console.log('  privmsg');
			bot.say(message.data.to, message.data.message);
		break;
		case 'raw':
			console.log('  raw');
			bot.send(message.command);
		break;
    }
}

function setup() {
	var cfg = server_config_for(0)
	console.log('irc server: '+cfg.hostname+' nick: '+cfg.nick)
	var bot = new irc.Client(cfg.hostname, cfg.nick, cfg);

	bot.addListener('message', function(nick, to, text, message) {
	    console.log(nick + ' said ' + text + ' to ' + to);
	    msg = {
			version: 1,
			type: 'privmsg',
			data: {
			    sender: nick,
			    channel: to,
			    message: text,
			},
	    };
	    pub.publish('in', JSON.stringify(msg));
	});

	var output_handlers = {
	    1: output_version_1,
	};

	sub.subscribe('out')
	sub.on('message', function(channel, message) {
	    msg = JSON.parse(message);
	    output_handlers[msg.version](msg)
	});
}

setup();<|endoftext|>


<commit_before>// bot.js

var request = require("request"),
    admin = require("./admin.js"),
    Slack = require("slack-client"),
    keys = require("./keys.js"),
    login = require("./login.js");
var Island = require("./db.js");

var api_token = keys.api_token,
    admin_token = keys.admin_token,
    slack = new Slack(api_token, true, true),
    island = {},
    mainland = {};

// initialize island
login(slack, island, mainland);

slack.on('message', function(message) {

    // Catch errors
    try {

	var channel = slack.getChannelGroupOrDMByID(message.channel);
	var user = slack.getUserByID(message.user);

	// Only listen to yoshis-story group
	if (message.channel == "G09PNS7TL") {

	    // Log message
	    if (message.type === 'message') {
		console.log("[#" + channel.name
			    + "] " + user.name
			    + " | " + message.text);
	    }

	    // Verifies if text represents player
	    var isUser = function(text) {
		if (island.hasOwnProperty(text)) {
		    return true;
		}
		if (mainland.hasOwnProperty(text)) {
		    return true;
		}
		return false;
	    };

	    // kicks user
	    var kickUser = function(person_id) {
		var DIALOGUES = ["_a screach was heard in the distance__",
				 "_they must atone for their sins__",
				 "_there was not a sound to be heard in the jungle_"];
		var r = Math.floor(Math.random() * 3);

		var requrl = "https://mgpublic.slack.com/api/groups.kick?token=" + admin_token + "&channel=G09PNS7TL&user=" + person_id;
		request(requrl, function (error, response, body) {
		    if (!error && response.statusCode == 200) {
			console.log(body);
		    }
		})
		channel.send(DIALOGUES(r));
		return true;
	    };

	    // invites user
	    var inviteUser = function(person_id) {
		var requrl = "https://mgpublic.slack.com/api/groups.invite?token=" + admin_token + "&channel=G09PNS7TL&user=" + person_id;
		request(requrl, function (error, response, body) {
		    if (!error && response.statusCode == 200) {
			console.log(body);
			channel.send(":yoshiegg: " + slack.getUserByID(person_id).name + " has been summoned :yoshiegg:");
		    }
		})
		return true;
	    };

	    // function - displays user's status
	    var status = function(text) {
		if (isUser(text)) {
		    if (!island.hasOwnProperty(text)) {
			channel.send(":yoshiegg: *" + text.split("").join(" ") + "* :yoshiegg:   [" + mainland[text][0].length + "/4]\n"
				     + "summons:  " + String(mainland[text][0]).split("").join(" "));
		    } else {
			var net = (island[text][1].length - island[text][0].length)
			channel.send(":yoshiegg: *" + text.split("").join(" ") + "* :yoshiegg:   [" + net + "/4]\n"
				     + "upvotes:  " + String(island[text][0]).split("").join(" ") + "\n"
				     + "downvotes:  " + String(island[text][1]).split("").join(" "));
		    }
		}
	    };

	    // function - writes to file
	    // someday *tear**tear*

	    // command - status
	    if (message.text.substring(0,6) == "status") {
		status(message.text.substring(7));
	    }

	    // command - upvote
	    if (message.text.substring(0,9) == ":randall:" && isUser(message.text.substring(10))) {

		// downvote user if they try to upvote bot
		if (message.text.substring(10,22) == "randall-bot") {
		    channel.send(user.name + " hahaha _no._");
		    if (island[user.name][1].indexOf("randall-bot", 0) == -1) {
			island[user.name][1].push("randall-bot");
			status(user.name);
		    }
		} else {

		    // submit upvote
		    if (island[message.text.substring(10)][0].indexOf(user.name, 0) == -1) {
			island[message.text.substring(10)][0].push(user.name);
		    }

		    // remove downvote if necessary
		    if (island[message.text.substring(10)][1].indexOf(user.name, 0) != -1) {
			island[message.text.substring(10)][1].splice(island[message.text.substring(10)][1].indexOf(user.name), 1);
		    }

		    // log upvote
		    console.log("[" + message.text.substring(10)  + "]  +1 from " + user.name);
		    console.log(">>> " + island[message.text.substring(10)]);
		    status(message.text.substring(10));
		}
	    }

	    // command - downvote
	    if (message.text.substring(0,7) == ":yoshi:" && isUser(message.text.substring(8))) {

		// downvote user if they try to downvote bot
		if (message.text.substring(8,20) == "randall-bot") {
		    channel.send(user.name + " hahaha _no._");
		    if (island[user.name][1].indexOf("randall-bot", 0) == -1) {
			island[user.name][1].push("randall-bot");
			status(user.name);
		    }
		} else {

		    // submit downvote
		    if (island[message.text.substring(8)][1].indexOf(user.name, 0) == -1) {
			island[message.text.substring(8)][1].push(user.name);
		    }

		    // remove upvote if necessary
		    if (island[message.text.substring(8)][0].indexOf(user.name, 0) != -1) {
			island[message.text.substring(8)][0].splice(island[message.text.substring(8)][0].indexOf(user.name), 1);
		    }

		    // log downvote
		    console.log("[" + message.text.substring(8)  + "]  -1 from " + user.name);
		    console.log(">>> " + island[message.text.substring(8)]);
		    status(message.text.substring(8));

		    // kick user off island
		    if (island[message.text.substring(8)][1].length - island[message.text.substring(8)][0].length >= 3) { //FIX THIS NUMBER
			console.log("[" + message.text.substring(8) + "]  has been voted off");
			channel.send(":yoshi::yoshi::yoshi::yoshiegg: " + message.text.substring(8) + " has been seized :yoshiegg::yoshi::yoshi::yoshi:");
			if (message.text.substring(8) == "durr") {
			    channel.send(":yoshi::yoshi::yoshi::yoshiegg: durr must atone for his sins :yoshiegg::yoshi::yoshi::yoshi:");
			    channel.send(":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|              ---> :randall: I got you, durr :randall:\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n");
			    island["durr"] = [[], [], "U081VGKU1"];
			} else {
			    mainland[message.text.substring(8)][0] = [];
			    island[message.text.substring(8)][0] = [];
			    island[message.text.substring(8)][1] = [];
			    kickUser(island[message.text.substring(8)][2]);
			    slack.getChannelOrGroupByID()
			}
		    }
		}
	    }

	    // command - summon
	    if (message.text.substring(0,10) == ":yoshiegg:") {
		if (isUser(message.text.substring(11))) {

		    // submit summon
		    if (mainland[message.text.substring(11)][0].indexOf(user.name, 0) == -1) {
			mainland[message.text.substring(11)][0].push(user.name);
		    }

		    // log summon
		    console.log("[" + message.text.substring(11)  + "]  summon from " + user.name);
		    console.log(">>> " + mainland[message.text.substring(11)]);
		    status(message.text.substring(11));

		    // perform summoning
		    if (mainland[message.text.substring(11)][0].length >= 4) { //FIX THIS NUMBER
			mainland[message.text.substring(11)][0] = []
			inviteUser(mainland[message.text.substring(11)][1]);
			island[message.text.substring(11)] = [[], [], mainland[message.text.substring(11)][1]]
			console.log("[" + message.text.substring(11) + "]  has been summoned");
		    }
		} else {

		    // add user to mainland if they recently joined
		    //if (slack.channels.C055V3V3A.members.hasOwnProperty(message.text.substring(11))) {
			//
		    //}
		}
	    }

	    // command - help
	    if (message.text == "help") {
		channel.send(""
			     + "UPVOTE:      `:randall: [username]`\n"
			     + "DOWNVOTE:    `:yoshi: [username]`\n"
			     + "SUMMON:      `:yoshiegg: [username]`\n"
			     + "VIEW STATUS: `status [username]`\n"
			     + "ROLL DICE:   `roll`");
	    }

	    // when user leaves group, reinvite them
	    if (message.text.indexOf("has left the group", 0) != -1) {
		if (island.hasOwnProperty(message.user)) {
		    inviteUser(message.user);
		}
		channel.send(":yoshi: " + slack.getUserByID(message.user).name);
	    }

	    // command - add
	    if (message.text.substring(0,3) == "add" && isUser(message.text.substring(4))) {
		channel.send("==> " + message.text.substring(4));
		channel.send("{ [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }");
		Island.addUser(message.text.substring(4),
			       island[message.text.substring(4)][2],
			       island[message.text.substring(4)][0],
			       island[message.text.substring(4)][1]);
		Island.findUser(message.text.substring(4));
	    }

	    // command - roll
	    if (message.text.substring(0,4) == "roll") {
		var fate = "";
		for (var i = 0; i < 2; i++) {
		    var roll = Math.floor(Math.random() * 6) + 1;
		    switch (roll) {
		    case 1:
			roll = ":one:";
			break;
		    case 2:
			roll = ":two:";
			break;
		    case 3:
			roll = ":three:";
			break;
		    case 4:
			roll = ":four:";
			break;
		    case 5:
			roll = ":five:"
			break;
		    case 6:
			roll = ":six:";
			break;
		    }
		    fate += " " + roll;
		}
		channel.send(user.name + fate);
	    }

	    // shameless self-promotion
	    if (message.text.toLowerCase().indexOf("face the falcon", 0) != -1) {
		channel.send("https://www.youtube.com/watch?v=YXPLysfBeag");
		console.log("Posted \"Face The Falcon\"");
	    }
	    if (message.text.toLowerCase().indexOf("embrace the falcon", 0) != -1) {
		channel.send("https://www.youtube.com/watch?v=fG982Lt-F7k");
		console.log("Posted \"Embrace The Falcon\"");
	    }

	    // command - "who is your daddy?"
	    if (message.text.toLowerCase().indexOf("who is your daddy?", 0) != -1) {
		if (user.name == "durr") {
		    channel.send("You're my daddy :randall:");
		} else {
		    channel.send("durr's my daddy :randall:");
		}
	    }
	}

	// global command - ?
	if (message.text == "?") {
	    channel.send("[" + slack.getUserByID(message.user).name.split("").join(" ") + "]"
			 + "\nuser ID: " + message.user
			 + "\nchannel ID: " + message.channel);
	}

    } catch (err) {}
});
<commit_msg>Production Build<commit_after>// bot.js

var request = require("request"),
    admin = require("./admin.js"),
    Slack = require("slack-client"),
    keys = require("./keys.js"),
    login = require("./login.js");
// var Island = require("./db.js");

var api_token = keys.api_token,
    admin_token = keys.admin_token,
    slack = new Slack(api_token, true, true),
    island = {},
    mainland = {};

// initialize island
login(slack, island, mainland);

slack.on('message', function(message) {

    // Catch errors
    try {

	var channel = slack.getChannelGroupOrDMByID(message.channel);
	var user = slack.getUserByID(message.user);

	// Only listen to yoshis-story group
	if (message.channel == "G09PNS7TL") {

	    // Log message
	    if (message.type === 'message') {
		console.log("[#" + channel.name
			    + "] " + user.name
			    + " | " + message.text);
	    }

	    // Verifies if text represents player
	    var isUser = function(text) {
		if (island.hasOwnProperty(text)) {
		    return true;
		}
		if (mainland.hasOwnProperty(text)) {
		    return true;
		}
		return false;
	    };

	    // kicks user
	    var kickUser = function(person_id) {
		var DIALOGUES = ["_a screach was heard in the distance__",
				 "_they must atone for their sins__",
				 "_there was not a sound to be heard in the jungle_"];
		var r = Math.floor(Math.random() * 3);

		var requrl = "https://mgpublic.slack.com/api/groups.kick?token=" + admin_token + "&channel=G09PNS7TL&user=" + person_id;
		request(requrl, function (error, response, body) {
		    if (!error && response.statusCode == 200) {
			console.log(body);
		    }
		})
		channel.send(DIALOGUES(r));
		return true;
	    };

	    // invites user
	    var inviteUser = function(person_id) {
		var requrl = "https://mgpublic.slack.com/api/groups.invite?token=" + admin_token + "&channel=G09PNS7TL&user=" + person_id;
		request(requrl, function (error, response, body) {
		    if (!error && response.statusCode == 200) {
			console.log(body);
			channel.send(":yoshiegg: " + slack.getUserByID(person_id).name + " has been summoned :yoshiegg:");
		    }
		})
		return true;
	    };

	    // function - displays user's status
	    var status = function(text) {
		if (isUser(text)) {
		    if (!island.hasOwnProperty(text)) {
			channel.send(":yoshiegg: *" + text.split("").join(" ") + "* :yoshiegg:   [" + mainland[text][0].length + "/3]\n"
				     + "summons:  " + String(mainland[text][0]).split("").join(" "));
		    } else {
			var net = (island[text][1].length - island[text][0].length)
			channel.send(":yoshiegg: *" + text.split("").join(" ") + "* :yoshiegg:   [" + net + "/5]\n"
				     + "upvotes:  " + String(island[text][0]).split("").join(" ") + "\n"
				     + "downvotes:  " + String(island[text][1]).split("").join(" "));
		    }
		}
	    };

	    // function - writes to file
	    // someday *tear**tear*

	    // command - status
	    if (message.text.substring(0,6) == "status") {
		status(message.text.substring(7));
	    }

	    // command - upvote
	    if (message.text.substring(0,9) == ":randall:" && isUser(message.text.substring(10))) {

		// downvote user if they try to upvote bot
		if (message.text.substring(10,22) == "randall-bot") {
		    channel.send(user.name + " hahaha _no._");
		    if (island[user.name][1].indexOf("randall-bot", 0) == -1) {
			island[user.name][1].push("randall-bot");
			status(user.name);
		    }
		} else {

		    // submit upvote
		    if (island[message.text.substring(10)][0].indexOf(user.name, 0) == -1) {
			island[message.text.substring(10)][0].push(user.name);
		    }

		    // remove downvote if necessary
		    if (island[message.text.substring(10)][1].indexOf(user.name, 0) != -1) {
			island[message.text.substring(10)][1].splice(island[message.text.substring(10)][1].indexOf(user.name), 1);
		    }

		    // log upvote
		    console.log("[" + message.text.substring(10)  + "]  +1 from " + user.name);
		    console.log(">>> " + island[message.text.substring(10)]);
		    status(message.text.substring(10));
		}
	    }

	    // command - downvote
	    if (message.text.substring(0,7) == ":yoshi:" && isUser(message.text.substring(8))) {

		// downvote user if they try to downvote bot
		if (message.text.substring(8,20) == "randall-bot") {
		    channel.send(user.name + " hahaha _no._");
		    if (island[user.name][1].indexOf("randall-bot", 0) == -1) {
			island[user.name][1].push("randall-bot");
			status(user.name);
		    }
		} else {

		    // submit downvote
		    if (island[message.text.substring(8)][1].indexOf(user.name, 0) == -1) {
			island[message.text.substring(8)][1].push(user.name);
		    }

		    // remove upvote if necessary
		    if (island[message.text.substring(8)][0].indexOf(user.name, 0) != -1) {
			island[message.text.substring(8)][0].splice(island[message.text.substring(8)][0].indexOf(user.name), 1);
		    }

		    // log downvote
		    console.log("[" + message.text.substring(8)  + "]  -1 from " + user.name);
		    console.log(">>> " + island[message.text.substring(8)]);
		    status(message.text.substring(8));

		    // kick user off island
		    if (island[message.text.substring(8)][1].length - island[message.text.substring(8)][0].length >= 5) { //FIX THIS NUMBER
			console.log("[" + message.text.substring(8) + "]  has been voted off");
			channel.send(":yoshi::yoshi::yoshi::yoshiegg: " + message.text.substring(8) + " has been seized :yoshiegg::yoshi::yoshi::yoshi:");
			if (message.text.substring(8) == "durr") {
			    channel.send(":yoshi::yoshi::yoshi::yoshiegg: durr must atone for his sins :yoshiegg::yoshi::yoshi::yoshi:");
			    channel.send(":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|              ---> :randall: I got you, durr :randall:\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n" +
					 ":yoshi::yoshi::yoshi::yoshi::yoshi::yoshi::yoshi:|\n");
			    island["durr"] = [[], [], "U081VGKU1"];
			} else {
			    mainland[message.text.substring(8)][0] = [];
			    island[message.text.substring(8)][0] = [];
			    island[message.text.substring(8)][1] = [];
			    kickUser(island[message.text.substring(8)][2]);
			    slack.getChannelOrGroupByID()
			}
		    }
		}
	    }

	    // command - summon
	    if (message.text.substring(0,10) == ":yoshiegg:") {
		if (isUser(message.text.substring(11))) {

		    // submit summon
		    if (mainland[message.text.substring(11)][0].indexOf(user.name, 0) == -1) {
			mainland[message.text.substring(11)][0].push(user.name);
		    }

		    // log summon
		    console.log("[" + message.text.substring(11)  + "]  summon from " + user.name);
		    console.log(">>> " + mainland[message.text.substring(11)]);
		    status(message.text.substring(11));

		    // perform summoning
		    if (mainland[message.text.substring(11)][0].length >= 3) { //FIX THIS NUMBER
			mainland[message.text.substring(11)][0] = []
			inviteUser(mainland[message.text.substring(11)][1]);
			island[message.text.substring(11)] = [[], [], mainland[message.text.substring(11)][1]]
			console.log("[" + message.text.substring(11) + "]  has been summoned");
		    }
		} else {

		    // add user to mainland if they recently joined
		    //if (slack.channels.C055V3V3A.members.hasOwnProperty(message.text.substring(11))) {
			//
		    //}
		}
	    }

	    // command - help
	    if (message.text == "help") {
		channel.send(""
			     + "UPVOTE:      `:randall: [username]`\n"
			     + "DOWNVOTE:    `:yoshi: [username]`\n"
			     + "SUMMON:      `:yoshiegg: [username]`\n"
			     + "VIEW STATUS: `status [username]`\n"
			     + "ROLL DICE:   `roll`");
	    }

	    // when user leaves group, reinvite them
	    if (message.text.indexOf("has left the group", 0) != -1) {
		if (island.hasOwnProperty(slack.getUserByID(message.user).name)) {
		    inviteUser(message.user);
		}
		channel.send(":yoshi: " + slack.getUserByID(message.user).name);
	    }

	    // command - add
	    if (message.text.substring(0,3) == "add" && isUser(message.text.substring(4))) {
		channel.send("==> " + message.text.substring(4));
		channel.send("{ [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }");
		Island.addUser(message.text.substring(4),
			       island[message.text.substring(4)][2],
			       island[message.text.substring(4)][0],
			       island[message.text.substring(4)][1]);
		Island.findUser(message.text.substring(4));
	    }

	    // command - roll
	    if (message.text.substring(0,4) == "roll") {
		var fate = "";
		for (var i = 0; i < 2; i++) {
		    var roll = Math.floor(Math.random() * 6) + 1;
		    switch (roll) {
		    case 1:
			roll = ":one:";
			break;
		    case 2:
			roll = ":two:";
			break;
		    case 3:
			roll = ":three:";
			break;
		    case 4:
			roll = ":four:";
			break;
		    case 5:
			roll = ":five:"
			break;
		    case 6:
			roll = ":six:";
			break;
		    }
		    fate += " " + roll;
		}
		channel.send(user.name + fate);
	    }

	    // shameless self-promotion
	    if (message.text.toLowerCase().indexOf("face the falcon", 0) != -1) {
		channel.send("https://www.youtube.com/watch?v=YXPLysfBeag");
		console.log("Posted \"Face The Falcon\"");
	    }
	    if (message.text.toLowerCase().indexOf("embrace the falcon", 0) != -1) {
		channel.send("https://www.youtube.com/watch?v=fG982Lt-F7k");
		console.log("Posted \"Embrace The Falcon\"");
	    }

	    // command - "who is your daddy?"
	    if (message.text.toLowerCase().indexOf("who is your daddy?", 0) != -1) {
		if (user.name == "durr") {
		    channel.send("You're my daddy :randall:");
		} else {
		    channel.send("durr's my daddy :randall:");
		}
	    }
	}

	// global command - ?
	if (message.text == "?") {
	    channel.send("[" + slack.getUserByID(message.user).name.split("").join(" ") + "]"
			 + "\nuser ID: " + message.user
			 + "\nchannel ID: " + message.channel);
	}

    } catch (err) {}
});
<|endoftext|>


<commit_before>var split = require('split')
var GameMap = require('./map/Map.js')
var SuperRegion = require('./map/SuperRegion.js')
var Region = require('./map/Region.js')
var PossibleOwners = require('./map/PossibleOwners.js')

module.exports = initBot

function initBot(input, output) {
  return new Bot(input, output)
}

/**
 * Main class
 * Initializes a map instance and an empty settings object
 */
function Bot (input, output) {
  if (!(this instanceof Bot)) {
    return new Bot(input, output)
  }

  // Will have a stream in real life, but might not have one in testing
  if (input) {
    input.pipe(split()).on('data', this.processLine.bind(this))
  }

  this.output = output

  // initialize options object
  this.options = {}

  // initialize map
  this.map = new GameMap()
}

Bot.prototype.processLine = function processLine (data) {
  // stop if line doesn't contain anything
  if (data.length === 0) {
    return
  }

  var lineParts = data.trim().split(' ')

  // stop if lineParts doesn't contain anything
  if (lineParts.length === 0) {
    return
  }
  this.processCommand(lineParts.shift(), lineParts)

}

Bot.prototype.processCommand = function processCommand (command, data) {
  // var start = process.hrtime()
  switch (command) {
    case 'settings':
      this.processSetting(data.shift(), data)
      break

    default:
      var camelCommand = toCamelCase(command)

      if (camelCommand in this) {
        var response = this[camelCommand](data)

        if (response && response.length > 0) {
          this.output.write(response + '\n')
        }
      } else {
        process.stderr.write(
          'Unable to execute command: ' + camelCommand + ' with data: ' + data + '\n'
        )
      }
  }
  // var end = process.hrtime(start)
  // process.stderr.write('turn took: ' + ((end[0] * 1e6) + (end[1] / 1e3)) + 'μs\n')
}

Bot.prototype.processSetting = function processSetting (setting, value) {
  switch (setting) {
    case 'max_rounds':
    case 'starting_armies':
    case 'starting_pick_amount':
    case 'time_per_move':
    case 'timebank':
      this.options[setting] = parseInt(value[0], 10)
      break
    case 'starting_regions':
      this.options[setting] = value
      break
    default:
      this.options[setting] = value[0]
  }
}

Bot.prototype.setupMap = function setupMap (data) {
  var command = toCamelCase('setup_' + data.shift())

  if (command in this) {
    this[command](data)
  } else {
    process.stderr.write(
      'Unable to understand command: ' + command + ', with data: ' + data
    )
  }
}

/**
 * Bot.setupSuperRegions
 * Initializes all super regions and assigns their bonuses
 *
 * @param Array data
 */
Bot.prototype.setupSuperRegions = function setupSuperRegions (data) {
  var i,
    continentId,
    continentBonus

  // loop through data in pairs of two
  for (i = 0; i + 1 < data.length; i += 2) {
    // get continent id
    continentId = parseInt(data[i], 10)

    // get continent bonus
    continentBonus = parseInt(data[i + 1], 10)

    // store content in continents object
    this.map.superRegions[continentId] = new SuperRegion(continentId, continentBonus)
  }
}

/**
 * Bot.setupRegions
 * Initializes all regions and sets their superRegions
 *
 * @param Array data
 */
Bot.prototype.setupRegions = function setupRegions (data) {
  var i,
    regionId,
    continent

  // loop through data in pairs of two
  for (i = 0; i + 1 < data.length; i += 2) {
    // get region id
    regionId = parseInt(data[i], 10)

    // get continent id
    continent = this.map.getSuperRegionById(parseInt(data[i + 1], 10))

    // store region in regions object
    this.map.regions[regionId] = new Region(regionId, continent)
  }
}

/**
 * Bot.setupNeighbors
 * Is used to update each regions neighbors according to data
 *
 * @param Array data
 */
Bot.prototype.setupNeighbors = function setupNeighbors (data) {
  var i,
    j,
    region,
    regionId,
    neighbor,
    neighborIds

  // loop through data in pairs of two
  for (i = 0; i + 1 < data.length; i += 2) {
    // get region by id
    regionId = parseInt(data[i], 10)
    region = this.map.getRegionById(regionId)

    // strip the string of brackets and convert to array
    neighborIds = data[i + 1].replace('[', '').replace(']', '').split(',')

    for (j = 0; j < neighborIds.length; j++) {
      // get the neighbor by Id
      var neigborId = parseInt(neighborIds[j], 10)
      neighbor = this.map.getRegionById(neigborId)

      // connect region with its neighbor
      neighbor.neighbors.push(region)
      region.neighbors.push(neighbor)
    }
  }
}

/**
 * Bot.setupWastelands
 * Is used to set the amount of armies on the wastelands
 *
 * @param Array data
 */
Bot.prototype.setupWastelands = function setupWastelands (data) {
  for (var i = 0; i < data.length; ++i) {
    var region = this.map.getRegionById(parseInt(data[i], 10))

    // this really shouldn't be hard coded
    region.troopCount = 6
    region.superRegion.wastelands++
  }
}

/**
 * Bot.updateMap
 * Is used to update our map every round
 *
 * @param Array data
 */
Bot.prototype.updateMap = function updateMap (data) {
  var botName = this.options.your_bot
  // loop through data in sets of three
  var handled = []
  for (var i = 0; i < data.length; i += 3) {
    // get region by id
    var regionId = parseInt(data[i], 10)
    handled.push(regionId)
    var region = this.map.getRegionById(regionId)

    // update region owner
    region.owner = data[i + 1]

    // update troopcount
    region.troopCount = parseInt(data[i + 2], 10)
  }

  var regions = this.map.getRegions()
  for (var j = 0; j < regions.length; ++j) {
    var mapRegion = regions[j]
    if (handled.indexOf(mapRegion.id) === -1 && mapRegion.owner === botName) {
      mapRegion.owner = this.options.opponent_bot
    }
  }
}

/**
 * Bot.pickStartingRegion
 * Is used to select initial starting regions.
 *
 * @param Array data
 * @return String
 */
Bot.prototype.pickStartingRegion = function pickStartingRegion (data) {
  // drop the time left
  data.shift()

  return this.rankRegions(data)[0]
}

Bot.prototype.rankRegions = function rankRegions (regionIds) {
  var bot = this

  var ranking = regionIds.map(function regionIdToRanking (regionId, index) {
    var region = bot.map.getRegionById(parseInt(regionId, 10))
    var value = 100
    value -= region.superRegion.wastelands * 10
    value -= Object.keys(region.superRegion.regions).length * 5
    value += region.superRegion.bonus * 3
    return {index: index, value: value, region: regionId}
  })

  ranking.sort(function sortByValue (a, b) {
    return b.value - a.value
  })

  var result = ranking.map(function buildResult (e) {
    return regionIds[e.index]
  })

  return result
}

/**
 * Bot.go
 * Calls placeArmies or attackTransfer depending on first item in data
 *
 * @param Array data
 * @return string
 */
Bot.prototype.go = function go (data) {
  var command = toCamelCase(data.shift())
  if (!(command in this)) {
    process.stderr.write(
      'Unable to understand command: ' + command + ', with data: ' + data
    )
  }

  return this[command](data)
}

/**
 * Bot.placeArmies
 * Is used to place troops. Currently places each army on a random region
 *
 * @param Array data
 * @return string
 */
Bot.prototype.placeArmies = function placeArmies () {
  var region
  var parsedPlacements = ''
  var placements = []
  var regionIndex = 0
  var troopsRemaining = parseInt(this.options.starting_armies, 10)
  var ownedRegions = this.map.getOwnedRegions(this.options.your_bot)
  var enemyRegions = this.map.getOwnedRegions(this.options.opponent_bot)
  var inNeed = []
  var enemy
  var neighboringEnemy
  var placing = 0

  ownedRegions.sort(function sortRegions (a, b) {
    var aValue = a.filterNeighbors(PossibleOwners.NEUTRAL).length
    var bValue = b.filterNeighbors(PossibleOwners.NEUTRAL).length
    return bValue - aValue
  })

  for (var i = 0; i < enemyRegions.length; ++i) {
    enemy = enemyRegions[i]
    neighboringEnemy = enemy.filterNeighbors(this.options.your_bot)
    for (var j = 0; j < neighboringEnemy.length; ++j) {
      var myRegion = neighboringEnemy[j]
      if (inNeed.indexOf(myRegion) === -1) {
        inNeed.push(neighboringEnemy[j])
      }
    }
  }

  inNeed.sort(function sortInNeed (a, b) {
    var aValue = a.filterNeighbors(PossibleOwners.NEUTRAL).length
    var bValue = b.filterNeighbors(PossibleOwners.NEUTRAL).length
    return bValue - aValue
  })

  while (troopsRemaining > 0) {
    if (inNeed.length >= 1) {
      region = inNeed[0]
      placing = Math.floor(troopsRemaining * 0.8)
      placements.push([region.id, placing])

      region.troopCount += placing
      troopsRemaining -= placing
      inNeed = []
      continue
    }

    if (troopsRemaining >= 2) {
      placing = 2
    } else {
      placing = 1
    }

    region = ownedRegions[regionIndex]

    // place a single army
    placements.push([region.id, placing])

    region.troopCount += placing
    troopsRemaining -= placing
    regionIndex = (regionIndex + 1) % ownedRegions.length
  }

  // parse the placements
  for (var k = 0; k < placements.length; k++) {
    parsedPlacements += (
      this.options.your_bot +
      ' place_armies ' +
      placements[k].join(' ')
    )

    if (k < placements.length - 1) {
      parsedPlacements += ', '
    }
  }

  return parsedPlacements
}

function sortByAttackOrder(name, a, b) {
  // default value for enemy
  var aValue = 2
  var bValue = 2
  if (a.owner === name) {
    // self worth no points
    aValue = 0
  } else if (a.owner === PossibleOwners.NEUTRAL) {
    // neutral worth less than enemy
    aValue = 1
  }
  if (b.owner === name) {
    // self worth no points
    bValue = 0
  } else if (b.owner === PossibleOwners.NEUTRAL) {
    // neutral worth less than enemy
    bValue = 1
  }
  // descending order
  return bValue - aValue
}

function sortByMoveOrder(name, a, b) {
  var aValue = 0
  aValue += a.filterNeighbors(name).length * 3
  aValue += a.filterNeighbors(PossibleOwners.NEUTRAL).length
  var bValue = 0
  bValue += b.filterNeighbors(name).length * 3
  bValue += b.filterNeighbors(PossibleOwners.NEUTRAL).length
  return bValue - aValue
}

Bot.prototype.attackTransfer = function attackTransfer () {
  var moves = []
  var ownedRegions = this.map.getOwnedRegions(this.options.your_bot)
  var n
  var targetRegion

  for (var i = 0; i < ownedRegions.length; i++) {
    var region = ownedRegions[i]
    var neighbors = region.neighbors.slice()

    neighbors.sort(sortByMoveOrder.bind(this.options.opponent_bot))
    // transfer troops to neighboring friendly region if troopCount > 1
    var anyNeutral = region.anyNeighbors(PossibleOwners.NEUTRAL)
    var anyEnemy = region.anyNeighbors(this.options.opponent_bot)
    if (region.troopCount > 1 && !anyNeutral && !anyEnemy) {
      for (n in neighbors) {
        // continue with the next iteration if n is a property of the neighbors array,
        // instead of an item in the array
        if (!region.neighbors.hasOwnProperty(n)) {
          continue
        }

        // set the target region
        targetRegion = region.neighbors[n]

        // transfer all available troops if target region is owned by bot
        if (this.options.your_bot === targetRegion.owner) {
          moves.push([region.id, targetRegion.id, region.troopCount - 1])
          region.troopCount = 1
          break
        }
      }
    }

    neighbors.sort(sortByAttackOrder.bind(this.options.your_name))
    // attack neighboring enemy / neutral region if troopCount > 6
    if (region.troopCount >= 4) {
      // shuffle the neighbours for some randomness
      for (var j = 0; j < neighbors.length; ++j) {
        // set the target region
        targetRegion = region.neighbors[j]

        // attack with all available troops if target region is not owned by bot
        if (this.options.your_bot !== targetRegion.owner) {
          if (region.troopCount > (targetRegion.troopCount * (10 / 7))) {
            moves.push([region.id, targetRegion.id, region.troopCount - 1])
            region.troopCount = 1
            break
          }
        }
      }
    }
  }

  // Return 'No moves' if no moves are made
  if (moves.length === 0) {
    return 'No moves'
  }
  var parsedMoves = ''
  // Else parse the moves
  for (i = 0; i < moves.length; i++) {
    parsedMoves += this.options.your_bot + ' attack/transfer ' + moves[i].join(' ')

    if (i < moves.length - 1) {
      parsedMoves += ','
    }
  }

  return parsedMoves
}

/**
 * Bot.opponentMoves
 * Can be used to parse the opponent_moves data, isn't used in the starter bot
 *
 * @param Array data
 */
Bot.prototype.opponentMoves = function opponentMoves (data) {
  process.stderr.write('opponentMoves:' + data + '\n')
}

Bot.prototype.setupOpponentStartingRegions = function setupOpponentStartingRegions(data) {
  process.stderr.write('setupOpponentStartingRegions:' + data + '\n')
}

function toCamelCase (input) {
  return input.replace('/', '_').replace(/_[a-z]/g, function replacer (match) {
    return match.toUpperCase().replace('_', '')
  })
}
<commit_msg>bind is silly<commit_after>var split = require('split')
var GameMap = require('./map/Map.js')
var SuperRegion = require('./map/SuperRegion.js')
var Region = require('./map/Region.js')
var PossibleOwners = require('./map/PossibleOwners.js')

module.exports = initBot

function initBot(input, output) {
  return new Bot(input, output)
}

/**
 * Main class
 * Initializes a map instance and an empty settings object
 */
function Bot (input, output) {
  if (!(this instanceof Bot)) {
    return new Bot(input, output)
  }

  // Will have a stream in real life, but might not have one in testing
  if (input) {
    input.pipe(split()).on('data', this.processLine.bind(this))
  }

  this.output = output

  // initialize options object
  this.options = {}

  // initialize map
  this.map = new GameMap()
}

Bot.prototype.processLine = function processLine (data) {
  // stop if line doesn't contain anything
  if (data.length === 0) {
    return
  }

  var lineParts = data.trim().split(' ')

  // stop if lineParts doesn't contain anything
  if (lineParts.length === 0) {
    return
  }
  this.processCommand(lineParts.shift(), lineParts)

}

Bot.prototype.processCommand = function processCommand (command, data) {
  // var start = process.hrtime()
  switch (command) {
    case 'settings':
      this.processSetting(data.shift(), data)
      break

    default:
      var camelCommand = toCamelCase(command)

      if (camelCommand in this) {
        var response = this[camelCommand](data)

        if (response && response.length > 0) {
          this.output.write(response + '\n')
        }
      } else {
        process.stderr.write(
          'Unable to execute command: ' + camelCommand + ' with data: ' + data + '\n'
        )
      }
  }
  // var end = process.hrtime(start)
  // process.stderr.write('turn took: ' + ((end[0] * 1e6) + (end[1] / 1e3)) + 'μs\n')
}

Bot.prototype.processSetting = function processSetting (setting, value) {
  switch (setting) {
    case 'max_rounds':
    case 'starting_armies':
    case 'starting_pick_amount':
    case 'time_per_move':
    case 'timebank':
      this.options[setting] = parseInt(value[0], 10)
      break
    case 'starting_regions':
      this.options[setting] = value
      break
    default:
      this.options[setting] = value[0]
  }
}

Bot.prototype.setupMap = function setupMap (data) {
  var command = toCamelCase('setup_' + data.shift())

  if (command in this) {
    this[command](data)
  } else {
    process.stderr.write(
      'Unable to understand command: ' + command + ', with data: ' + data
    )
  }
}

/**
 * Bot.setupSuperRegions
 * Initializes all super regions and assigns their bonuses
 *
 * @param Array data
 */
Bot.prototype.setupSuperRegions = function setupSuperRegions (data) {
  var i,
    continentId,
    continentBonus

  // loop through data in pairs of two
  for (i = 0; i + 1 < data.length; i += 2) {
    // get continent id
    continentId = parseInt(data[i], 10)

    // get continent bonus
    continentBonus = parseInt(data[i + 1], 10)

    // store content in continents object
    this.map.superRegions[continentId] = new SuperRegion(continentId, continentBonus)
  }
}

/**
 * Bot.setupRegions
 * Initializes all regions and sets their superRegions
 *
 * @param Array data
 */
Bot.prototype.setupRegions = function setupRegions (data) {
  var i,
    regionId,
    continent

  // loop through data in pairs of two
  for (i = 0; i + 1 < data.length; i += 2) {
    // get region id
    regionId = parseInt(data[i], 10)

    // get continent id
    continent = this.map.getSuperRegionById(parseInt(data[i + 1], 10))

    // store region in regions object
    this.map.regions[regionId] = new Region(regionId, continent)
  }
}

/**
 * Bot.setupNeighbors
 * Is used to update each regions neighbors according to data
 *
 * @param Array data
 */
Bot.prototype.setupNeighbors = function setupNeighbors (data) {
  var i,
    j,
    region,
    regionId,
    neighbor,
    neighborIds

  // loop through data in pairs of two
  for (i = 0; i + 1 < data.length; i += 2) {
    // get region by id
    regionId = parseInt(data[i], 10)
    region = this.map.getRegionById(regionId)

    // strip the string of brackets and convert to array
    neighborIds = data[i + 1].replace('[', '').replace(']', '').split(',')

    for (j = 0; j < neighborIds.length; j++) {
      // get the neighbor by Id
      var neigborId = parseInt(neighborIds[j], 10)
      neighbor = this.map.getRegionById(neigborId)

      // connect region with its neighbor
      neighbor.neighbors.push(region)
      region.neighbors.push(neighbor)
    }
  }
}

/**
 * Bot.setupWastelands
 * Is used to set the amount of armies on the wastelands
 *
 * @param Array data
 */
Bot.prototype.setupWastelands = function setupWastelands (data) {
  for (var i = 0; i < data.length; ++i) {
    var region = this.map.getRegionById(parseInt(data[i], 10))

    // this really shouldn't be hard coded
    region.troopCount = 6
    region.superRegion.wastelands++
  }
}

/**
 * Bot.updateMap
 * Is used to update our map every round
 *
 * @param Array data
 */
Bot.prototype.updateMap = function updateMap (data) {
  var botName = this.options.your_bot
  // loop through data in sets of three
  var handled = []
  for (var i = 0; i < data.length; i += 3) {
    // get region by id
    var regionId = parseInt(data[i], 10)
    handled.push(regionId)
    var region = this.map.getRegionById(regionId)

    // update region owner
    region.owner = data[i + 1]

    // update troopcount
    region.troopCount = parseInt(data[i + 2], 10)
  }

  var regions = this.map.getRegions()
  for (var j = 0; j < regions.length; ++j) {
    var mapRegion = regions[j]
    if (handled.indexOf(mapRegion.id) === -1 && mapRegion.owner === botName) {
      mapRegion.owner = this.options.opponent_bot
    }
  }
}

/**
 * Bot.pickStartingRegion
 * Is used to select initial starting regions.
 *
 * @param Array data
 * @return String
 */
Bot.prototype.pickStartingRegion = function pickStartingRegion (data) {
  // drop the time left
  data.shift()

  return this.rankRegions(data)[0]
}

Bot.prototype.rankRegions = function rankRegions (regionIds) {
  var bot = this

  var ranking = regionIds.map(function regionIdToRanking (regionId, index) {
    var region = bot.map.getRegionById(parseInt(regionId, 10))
    var value = 100
    value -= region.superRegion.wastelands * 10
    value -= Object.keys(region.superRegion.regions).length * 5
    value += region.superRegion.bonus * 3
    return {index: index, value: value, region: regionId}
  })

  ranking.sort(function sortByValue (a, b) {
    return b.value - a.value
  })

  var result = ranking.map(function buildResult (e) {
    return regionIds[e.index]
  })

  return result
}

/**
 * Bot.go
 * Calls placeArmies or attackTransfer depending on first item in data
 *
 * @param Array data
 * @return string
 */
Bot.prototype.go = function go (data) {
  var command = toCamelCase(data.shift())
  if (!(command in this)) {
    process.stderr.write(
      'Unable to understand command: ' + command + ', with data: ' + data
    )
  }

  return this[command](data)
}

/**
 * Bot.placeArmies
 * Is used to place troops. Currently places each army on a random region
 *
 * @param Array data
 * @return string
 */
Bot.prototype.placeArmies = function placeArmies () {
  var region
  var parsedPlacements = ''
  var placements = []
  var regionIndex = 0
  var troopsRemaining = parseInt(this.options.starting_armies, 10)
  var ownedRegions = this.map.getOwnedRegions(this.options.your_bot)
  var enemyRegions = this.map.getOwnedRegions(this.options.opponent_bot)
  var inNeed = []
  var enemy
  var neighboringEnemy
  var placing = 0

  ownedRegions.sort(function sortRegions (a, b) {
    var aValue = a.filterNeighbors(PossibleOwners.NEUTRAL).length
    var bValue = b.filterNeighbors(PossibleOwners.NEUTRAL).length
    return bValue - aValue
  })

  for (var i = 0; i < enemyRegions.length; ++i) {
    enemy = enemyRegions[i]
    neighboringEnemy = enemy.filterNeighbors(this.options.your_bot)
    for (var j = 0; j < neighboringEnemy.length; ++j) {
      var myRegion = neighboringEnemy[j]
      if (inNeed.indexOf(myRegion) === -1) {
        inNeed.push(neighboringEnemy[j])
      }
    }
  }

  inNeed.sort(function sortInNeed (a, b) {
    var aValue = a.filterNeighbors(PossibleOwners.NEUTRAL).length
    var bValue = b.filterNeighbors(PossibleOwners.NEUTRAL).length
    return bValue - aValue
  })

  while (troopsRemaining > 0) {
    if (inNeed.length >= 1) {
      region = inNeed[0]
      placing = Math.floor(troopsRemaining * 0.8)
      placements.push([region.id, placing])

      region.troopCount += placing
      troopsRemaining -= placing
      inNeed = []
      continue
    }

    if (troopsRemaining >= 2) {
      placing = 2
    } else {
      placing = 1
    }

    region = ownedRegions[regionIndex]

    // place a single army
    placements.push([region.id, placing])

    region.troopCount += placing
    troopsRemaining -= placing
    regionIndex = (regionIndex + 1) % ownedRegions.length
  }

  // parse the placements
  for (var k = 0; k < placements.length; k++) {
    parsedPlacements += (
      this.options.your_bot +
      ' place_armies ' +
      placements[k].join(' ')
    )

    if (k < placements.length - 1) {
      parsedPlacements += ', '
    }
  }

  return parsedPlacements
}

function sortByAttackOrder(name, a, b) {
  // default value for enemy
  var aValue = 2
  var bValue = 2
  if (a.owner === name) {
    // self worth no points
    aValue = 0
  } else if (a.owner === PossibleOwners.NEUTRAL) {
    // neutral worth less than enemy
    aValue = 1
  }
  if (b.owner === name) {
    // self worth no points
    bValue = 0
  } else if (b.owner === PossibleOwners.NEUTRAL) {
    // neutral worth less than enemy
    bValue = 1
  }
  // descending order
  return bValue - aValue
}

function sortByMoveOrder(name, a, b) {
  var aValue = 0
  aValue += a.filterNeighbors(name).length * 3
  aValue += a.filterNeighbors(PossibleOwners.NEUTRAL).length
  var bValue = 0
  bValue += b.filterNeighbors(name).length * 3
  bValue += b.filterNeighbors(PossibleOwners.NEUTRAL).length
  return bValue - aValue
}

Bot.prototype.attackTransfer = function attackTransfer () {
  var moves = []
  var ownedRegions = this.map.getOwnedRegions(this.options.your_bot)
  var n
  var targetRegion

  for (var i = 0; i < ownedRegions.length; i++) {
    var region = ownedRegions[i]
    var neighbors = region.neighbors.slice()
    neighbors.sort(sortByMoveOrder.bind(null, this.options.opponent_bot))
    // transfer troops to neighboring friendly region if troopCount > 1
    var anyNeutral = region.anyNeighbors(PossibleOwners.NEUTRAL)
    var anyEnemy = region.anyNeighbors(this.options.opponent_bot)
    if (region.troopCount > 1 && !anyNeutral && !anyEnemy) {
      for (n in neighbors) {
        // continue with the next iteration if n is a property of the neighbors array,
        // instead of an item in the array
        if (!region.neighbors.hasOwnProperty(n)) {
          continue
        }

        // set the target region
        targetRegion = region.neighbors[n]

        // transfer all available troops if target region is owned by bot
        if (this.options.your_bot === targetRegion.owner) {
          moves.push([region.id, targetRegion.id, region.troopCount - 1])
          region.troopCount = 1
          break
        }
      }
    }

    neighbors.sort(sortByAttackOrder.bind(null, this.options.your_name))
    // attack neighboring enemy / neutral region if troopCount > 6
    if (region.troopCount >= 4) {
      // shuffle the neighbours for some randomness
      for (var j = 0; j < neighbors.length; ++j) {
        // set the target region
        targetRegion = region.neighbors[j]

        // attack with all available troops if target region is not owned by bot
        if (this.options.your_bot !== targetRegion.owner) {
          if (region.troopCount > (targetRegion.troopCount * (10 / 7))) {
            moves.push([region.id, targetRegion.id, region.troopCount - 1])
            region.troopCount = 1
            break
          }
        }
      }
    }
  }

  // Return 'No moves' if no moves are made
  if (moves.length === 0) {
    return 'No moves'
  }
  var parsedMoves = ''
  // Else parse the moves
  for (i = 0; i < moves.length; i++) {
    parsedMoves += this.options.your_bot + ' attack/transfer ' + moves[i].join(' ')

    if (i < moves.length - 1) {
      parsedMoves += ','
    }
  }

  return parsedMoves
}

/**
 * Bot.opponentMoves
 * Can be used to parse the opponent_moves data, isn't used in the starter bot
 *
 * @param Array data
 */
Bot.prototype.opponentMoves = function opponentMoves (data) {
  process.stderr.write('opponentMoves:' + data + '\n')
}

Bot.prototype.setupOpponentStartingRegions = function setupOpponentStartingRegions(data) {
  process.stderr.write('setupOpponentStartingRegions:' + data + '\n')
}

function toCamelCase (input) {
  return input.replace('/', '_').replace(/_[a-z]/g, function replacer (match) {
    return match.toUpperCase().replace('_', '')
  })
}
<|endoftext|>


<commit_before>var HTTPS = require('https');
var path = require('path');
var config = require('./config');
var bot = {};

var groupIdToBotMap = {};
config.bots.forEach(function (bot) {
  groupIdToBotMap[bot.groupID] = bot;
});

var commands = [];
bot.registerCommand = function (command, description, func) {
  commands[command] = [description, func];
};

// http://stackoverflow.com/a/5365577 (node.js require all files in a folder?)
// And http://stackoverflow.com/questions/5364928/node-js-require-all-files-in-a-folder#comment25520686_5365577
var normalizedPath = path.join(__dirname, "commands");
require("fs").readdirSync(normalizedPath).forEach(function (file) {
  if (path.extname(file) === '.js') {
    require("./commands/" + file)(bot.registerCommand);
  }
});

bot.respond = function (request) {
  var botConfig, msg, botName;
  if (!request) {
    return;
  }
  botConfig = groupIdToBotMap[request.group_id];
  if (!botConfig) {
    console.log('New message received, but no bot configured for Group ID ' + request.group_id);
  } else {
    botName = botConfig.botName;
    msg = request.text;
    console.log('New message from %s in group \'%s\': %s', request.name, botConfig.groupLocalID, msg);
    if (typeof msg === 'string') {
      if (msg === botName) {
        msg = botName + ' help';
      }
      if (msg.substring(0, botName.length + 1) === botName + ' ') {
        msg = msg.substring(botName.length + 1);
        this.processCommand(botConfig.groupLocalID, request.name, msg, function (response) {
          if (response !== null) {
            this.postMessage(botConfig.botID, response);
          }
        }.bind(this));
      }
    }
  }
};

bot.processCommand = function (groupLocalID, userDisplayName, message, cb) {
  var tokens = message.split(' '),
      commandString = tokens.shift();

  if (groupLocalID === '3') {
    // do not send anything to the group I assigned local id 3
    cb(null);
    return;
  }

  if (!commandString) {
    cb(null);
    return;
  }

  if (commandString === 'help') {
    var helpText = 'Usage: bot <command> <arguments> [optional arguments]\n' +
      'Available commands:\nhelp: Display this text\n';
    for (var key in commands) {
      if (commands.hasOwnProperty(key)) {
        helpText += commands[key][0] + '\n';
      }
    }
    cb(helpText);
    return;
  }

  var command = commands[commandString];
  if (!command) {
    cb('Command \'' + commandString + '\' not supported. Type \'bot help\' for available commands.');
    return;
  }

  command[1](groupLocalID, userDisplayName, tokens, cb);
};

bot.postMessage = function (botID, text) {
  var options, body, botReq;

  options = {
    hostname: 'api.groupme.com',
    path: '/v3/bots/post',
    method: 'POST'
  };

  body = {
    "bot_id" : botID,
    "text" : text
  };

  console.log('sending ' + text + ' to ' + botID);

  botReq = HTTPS.request(options, function(res) {
      if(res.statusCode == 202) {
        //neat
      } else {
        console.log('rejecting bad status code ' + res.statusCode);
      }
  });

  botReq.on('error', function(err) {
    console.log('error posting message '  + JSON.stringify(err));
  });
  botReq.on('timeout', function(err) {
    console.log('timeout posting message '  + JSON.stringify(err));
  });
  botReq.end(JSON.stringify(body));
};

module.exports = bot;
<commit_msg>Remove condition to prevent messages being sent to group '3'<commit_after>var HTTPS = require('https');
var path = require('path');
var config = require('./config');
var bot = {};

var groupIdToBotMap = {};
config.bots.forEach(function (bot) {
  groupIdToBotMap[bot.groupID] = bot;
});

var commands = [];
bot.registerCommand = function (command, description, func) {
  commands[command] = [description, func];
};

// http://stackoverflow.com/a/5365577 (node.js require all files in a folder?)
// And http://stackoverflow.com/questions/5364928/node-js-require-all-files-in-a-folder#comment25520686_5365577
var normalizedPath = path.join(__dirname, "commands");
require("fs").readdirSync(normalizedPath).forEach(function (file) {
  if (path.extname(file) === '.js') {
    require("./commands/" + file)(bot.registerCommand);
  }
});

bot.respond = function (request) {
  var botConfig, msg, botName;
  if (!request) {
    return;
  }
  botConfig = groupIdToBotMap[request.group_id];
  if (!botConfig) {
    console.log('New message received, but no bot configured for Group ID ' + request.group_id);
  } else {
    botName = botConfig.botName;
    msg = request.text;
    console.log('New message from %s in group \'%s\': %s', request.name, botConfig.groupLocalID, msg);
    if (typeof msg === 'string') {
      if (msg === botName) {
        msg = botName + ' help';
      }
      if (msg.substring(0, botName.length + 1) === botName + ' ') {
        msg = msg.substring(botName.length + 1);
        this.processCommand(botConfig.groupLocalID, request.name, msg, function (response) {
          if (response !== null) {
            this.postMessage(botConfig.botID, response);
          }
        }.bind(this));
      }
    }
  }
};

bot.processCommand = function (groupLocalID, userDisplayName, message, cb) {
  var tokens = message.split(' '),
      commandString = tokens.shift();

  if (!commandString) {
    cb(null);
    return;
  }

  if (commandString === 'help') {
    var helpText = 'Usage: bot <command> <arguments> [optional arguments]\n' +
      'Available commands:\nhelp: Display this text\n';
    for (var key in commands) {
      if (commands.hasOwnProperty(key)) {
        helpText += commands[key][0] + '\n';
      }
    }
    cb(helpText);
    return;
  }

  var command = commands[commandString];
  if (!command) {
    cb('Command \'' + commandString + '\' not supported. Type \'bot help\' for available commands.');
    return;
  }

  command[1](groupLocalID, userDisplayName, tokens, cb);
};

bot.postMessage = function (botID, text) {
  var options, body, botReq;

  options = {
    hostname: 'api.groupme.com',
    path: '/v3/bots/post',
    method: 'POST'
  };

  body = {
    "bot_id" : botID,
    "text" : text
  };

  console.log('sending ' + text + ' to ' + botID);

  botReq = HTTPS.request(options, function(res) {
      if(res.statusCode == 202) {
        //neat
      } else {
        console.log('rejecting bad status code ' + res.statusCode);
      }
  });

  botReq.on('error', function(err) {
    console.log('error posting message '  + JSON.stringify(err));
  });
  botReq.on('timeout', function(err) {
    console.log('timeout posting message '  + JSON.stringify(err));
  });
  botReq.end(JSON.stringify(body));
};

module.exports = bot;
<|endoftext|>


<commit_before>const TelegramBot = require('node-telegram-bot-api');
const request = require('request');
const schedule = require('node-schedule');
const fs = require('fs');
var config = require('./config');

const token = config.bottoken;
const bot = new TelegramBot(token, {polling: true})
var dailyloc = config.dailyLocation;

bot.onText(/\/greet (.+)/, (msg, input) => {
	const chatId = msg.chat.id;
	var blub = input[1];
	var resp ='Hello, '+blub;

	bot.sendMessage(chatId, resp);
});

var loremSettings = {
	url: 'http://lorempixel.com/400/200',
	encoding: null
};

bot.onText(/\/lorem/||/\/lorem (.*)/, (msg) =>{
	const chatId = msg.chat.id;
	request(loremSettings, function (error, response, buffer) {
		if (!error && response.statusCode == 200){
			bot.sendPhoto(chatId, buffer);
		}
	})
});

var doit = [
	'http://i.imgur.com/RPbK0fZ.png',
	'http://i.imgur.com/TgUQfNI.jpg',
	'http://i.imgur.com/WSm116p.jpg',
]

bot.onText(/\/doit/,(msg) =>{
	const chatId = msg.chat.id;
	bot.sendPhoto(chatId, doit[Math.floor(Math.random()*doit.length)]);
});

var ship = [
	'http://i.imgur.com/b7bzy0C.png',
	'http://i.imgur.com/hse69ui.jpg',
	'http://i.imgur.com/pyjpvhM.gif',
	'http://i.imgur.com/66j50Xz.jpg',
	'http://i.imgur.com/tCiQSlg.jpg',
	'http://i.imgur.com/DDLLoL8.gif',
	'http://i.imgur.com/LDzcDY3.jpg',
	'http://i.imgur.com/nkeMpLe.jpg',
	'http://i.imgur.com/ACaARFw.jpg',
	'http://i.imgur.com/aJkhUrE.jpg',
	'http://i.imgur.com/YBdJsaS.jpg',
	'http://i.imgur.com/KmZrtgd.jpg',
	'http://i.imgur.com/rmgCY2Q.jpg',
	'http://i.imgur.com/g00lVs9.gif',
	'http://i.imgur.com/LIIXWmD.png',
	'http://i.imgur.com/c6K9rP3.jpg',
	'http://i.imgur.com/2M8iyPt.jpg',
	'http://i.imgur.com/7XxnrTu.jpg',
	'http://i.imgur.com/AJN04yl.jpg',
	'http://i.imgur.com/rcIMpM0.gif',
	'http://i.imgur.com/60u8kye.jpg',
	'http://i.imgur.com/yUypmaC.jpg',
	'http://i.imgur.com/IflZleY.jpg',
	'http://i.imgur.com/h3mlvCq.png',
	'http://i.imgur.com/dXzZETc.png',
	'https://media.giphy.com/media/143vPc6b08locw/giphy.gif',
	'https://media0.giphy.com/media/14tFXhhNurdGp2/giphy.gif',
	'https://media4.giphy.com/media/ta83CqOoRwfwQ/giphy.gif',
	'https://media2.giphy.com/media/tDafHUBVrRKtq/giphy.gif',
	'https://media2.giphy.com/media/tDafHUBVrRKtq/giphy.gif',
]

bot.onText(/\/ship/,(msg) =>{
	const chatId = msg.chat.id;
	bot.sendMessage(chatId, ship[Math.floor(Math.random()*ship.length)]);
});

var editions = [
	{short:'an', count:92},
	{short:'lg', count:310},
	{short:'dk', count:119},
	{short:'fe', count:187},
	{short:'hl', count:140},
	{short:'mr', count:350},
	{short:'vi', count:167},
	{short:'wl', count:167},
	{short:'tp', count:350},
	{short:'sh', count:167},
	{short:'ex', count:167},
	{short:'us', count:350},
	{short:'ul', count:143},
	{short:'ud', count:143},
	{short:'mm', count:350},
	{short:'ne', count:143},
	{short:'pr', count:143},
	{short:'in', count:355},
	{short:'ps', count:146},
	{short:'ap', count:148},
	{short:'od', count:350},
	{short:'tr', count:143},
	{short:'ju', count:143},
	{short:'on', count:350},
	{short:'le', count:145},
	{short:'sc', count:143},
	{short:'be', count:302},
	{short:'ug', count:88},
	{short:'po2', count:165},
	{short:'po', count:222},
	{short:'p3k', count:180},
	{short:'ced', count:302},
	{short:'cedi', count:302},
]

bot.onText(/\/draw/, (msg) =>{
	const chatId = msg.chat.id;
	let edition = editions[Math.floor(Math.random()*editions.length)];
	bot.sendMessage(chatId,`http://magiccards.info/scans/en/${edition.short}/${Math.floor(Math.random()*edition.count)}.jpg`);
});

var merge = [
	'https://i.imgur.com/X9zNSkM.gif',
	'https://cdn.meme.am/cache/instances/folder86/500x/64007086/disaster-girl-push-rejected-rebase-or-merge-git-push-force.jpg',
	'https://www.mememaker.net/static/images/memes/3629643.jpg',
	'http://s.quickmeme.com/img/58/58cdc50dcb04a16438e9759f2db7a0ac23442e718f69af7b2ac0a3761915e92a.jpg',
	'https://i.stack.imgur.com/nEfIm.jpg',
]

bot.onText(/\/💩/,(msg) => {
	const chatId = msg.chat.id;
	bot.sendMessage(chatId, 'Kothaufen');
});

bot.onText(/\/merge/,(msg) => {
	const chatId = msg.chat.id;
	bot.sendMessage(chatId, merge[Math.floor(Math.random()*merge.length)]);
});

var j = schedule.scheduleJob('30 5 * * *', function(){
	bot.sendMessage(config.dailyChatId, 'Todays weather forecast for '+dailyloc+':');
	bot.sendPhoto(config.dailyChatId, 'wttr.in/'+dailyloc+'.png');
});

var downloader = function(uri, filename, callback){
	request.head(uri, function(err, res, body){
		request(uri).pipe(fs.createWriteStream(filename)).on('close',callback);
		fs.close();
	});
};

bot.onText(/\/weather (.+)/, (msg, input) => {
	const chatId = msg.chat.id;
	var loc = input[1];
	downloader('http://wttr.in/'+loc+'.png?1', 'wetter.png',function(){
		console.log('done');
	});
	var photo = __dirname+'/wetter.png';
	bot.sendPhoto(chatId, photo, {caption: "Todays weather forecast for: "+loc});
});

bot.onText(/\/decide (.+)/, (msg, input) => {
	const chatID = msg.chat.id;
	var answer = Math.random() >= 0.5 ? "Yes" : "No";
	bot.sendMessage(chatID, input[1] + " " + answer);
});

bot.onText(/\/marius/, (msg) => {
	const chatID = msg.chat.id;
	bot.sendMessage(chatID, "https://i.giphy.com/media/l2YWsiql5xGPIbnzy/giphy.gif");
});
bot.onText(/\/slap (.+)/, (msg,input) => {
	const chatID = msg.chat.id;
	bot.sendMessage(chatID, "" + msg.from.first_name + " slaps " + input[1] + " around a bit with a large trout",{parse_mode : "HTML"});
});<commit_msg>Fix for weather<commit_after>const TelegramBot = require('node-telegram-bot-api');
const request = require('request');
const schedule = require('node-schedule');
const fs = require('fs');
var config = require('./config');

const token = config.bottoken;
const bot = new TelegramBot(token, {polling: true})
var dailyloc = config.dailyLocation;

bot.onText(/\/greet (.+)/, (msg, input) => {
	const chatId = msg.chat.id;
	var blub = input[1];
	var resp ='Hello, '+blub;

	bot.sendMessage(chatId, resp);
});

var loremSettings = {
	url: 'http://lorempixel.com/400/200',
	encoding: null
};

bot.onText(/\/lorem/||/\/lorem (.*)/, (msg) =>{
	const chatId = msg.chat.id;
	request(loremSettings, function (error, response, buffer) {
		if (!error && response.statusCode == 200){
			bot.sendPhoto(chatId, buffer);
		}
	})
});

var doit = [
	'http://i.imgur.com/RPbK0fZ.png',
	'http://i.imgur.com/TgUQfNI.jpg',
	'http://i.imgur.com/WSm116p.jpg',
]

bot.onText(/\/doit/,(msg) =>{
	const chatId = msg.chat.id;
	bot.sendPhoto(chatId, doit[Math.floor(Math.random()*doit.length)]);
});

var ship = [
	'http://i.imgur.com/b7bzy0C.png',
	'http://i.imgur.com/hse69ui.jpg',
	'http://i.imgur.com/pyjpvhM.gif',
	'http://i.imgur.com/66j50Xz.jpg',
	'http://i.imgur.com/tCiQSlg.jpg',
	'http://i.imgur.com/DDLLoL8.gif',
	'http://i.imgur.com/LDzcDY3.jpg',
	'http://i.imgur.com/nkeMpLe.jpg',
	'http://i.imgur.com/ACaARFw.jpg',
	'http://i.imgur.com/aJkhUrE.jpg',
	'http://i.imgur.com/YBdJsaS.jpg',
	'http://i.imgur.com/KmZrtgd.jpg',
	'http://i.imgur.com/rmgCY2Q.jpg',
	'http://i.imgur.com/g00lVs9.gif',
	'http://i.imgur.com/LIIXWmD.png',
	'http://i.imgur.com/c6K9rP3.jpg',
	'http://i.imgur.com/2M8iyPt.jpg',
	'http://i.imgur.com/7XxnrTu.jpg',
	'http://i.imgur.com/AJN04yl.jpg',
	'http://i.imgur.com/rcIMpM0.gif',
	'http://i.imgur.com/60u8kye.jpg',
	'http://i.imgur.com/yUypmaC.jpg',
	'http://i.imgur.com/IflZleY.jpg',
	'http://i.imgur.com/h3mlvCq.png',
	'http://i.imgur.com/dXzZETc.png',
	'https://media.giphy.com/media/143vPc6b08locw/giphy.gif',
	'https://media0.giphy.com/media/14tFXhhNurdGp2/giphy.gif',
	'https://media4.giphy.com/media/ta83CqOoRwfwQ/giphy.gif',
	'https://media2.giphy.com/media/tDafHUBVrRKtq/giphy.gif',
	'https://media2.giphy.com/media/tDafHUBVrRKtq/giphy.gif',
]

bot.onText(/\/ship/,(msg) =>{
	const chatId = msg.chat.id;
	bot.sendMessage(chatId, ship[Math.floor(Math.random()*ship.length)]);
});

var editions = [
	{short:'an', count:92},
	{short:'lg', count:310},
	{short:'dk', count:119},
	{short:'fe', count:187},
	{short:'hl', count:140},
	{short:'mr', count:350},
	{short:'vi', count:167},
	{short:'wl', count:167},
	{short:'tp', count:350},
	{short:'sh', count:167},
	{short:'ex', count:167},
	{short:'us', count:350},
	{short:'ul', count:143},
	{short:'ud', count:143},
	{short:'mm', count:350},
	{short:'ne', count:143},
	{short:'pr', count:143},
	{short:'in', count:355},
	{short:'ps', count:146},
	{short:'ap', count:148},
	{short:'od', count:350},
	{short:'tr', count:143},
	{short:'ju', count:143},
	{short:'on', count:350},
	{short:'le', count:145},
	{short:'sc', count:143},
	{short:'be', count:302},
	{short:'ug', count:88},
	{short:'po2', count:165},
	{short:'po', count:222},
	{short:'p3k', count:180},
	{short:'ced', count:302},
	{short:'cedi', count:302},
]

bot.onText(/\/draw/, (msg) =>{
	const chatId = msg.chat.id;
	let edition = editions[Math.floor(Math.random()*editions.length)];
	bot.sendMessage(chatId,`http://magiccards.info/scans/en/${edition.short}/${Math.floor(Math.random()*edition.count)}.jpg`);
});

var merge = [
	'https://i.imgur.com/X9zNSkM.gif',
	'https://cdn.meme.am/cache/instances/folder86/500x/64007086/disaster-girl-push-rejected-rebase-or-merge-git-push-force.jpg',
	'https://www.mememaker.net/static/images/memes/3629643.jpg',
	'http://s.quickmeme.com/img/58/58cdc50dcb04a16438e9759f2db7a0ac23442e718f69af7b2ac0a3761915e92a.jpg',
	'https://i.stack.imgur.com/nEfIm.jpg',
]

bot.onText(/\/💩/,(msg) => {
	const chatId = msg.chat.id;
	bot.sendMessage(chatId, 'Kothaufen');
});

bot.onText(/\/merge/,(msg) => {
	const chatId = msg.chat.id;
	bot.sendMessage(chatId, merge[Math.floor(Math.random()*merge.length)]);
});

var j = schedule.scheduleJob('30 5 * * *', function(){
	bot.sendMessage(config.dailyChatId, 'Todays weather forecast for '+dailyloc+':');
	bot.sendPhoto(config.dailyChatId, 'wttr.in/'+dailyloc+'.png');
});

var downloader = function(uri, filename, callback){
	request.head(uri, function(err, res, body){
		request(uri).pipe(fs.createWriteStream(filename)).on('finish',callback);
	});
};

bot.onText(/\/weather (.+)/, (msg, input) => {
	const chatId = msg.chat.id;
	var loc = input[1];
	downloader('http://wttr.in/'+loc+'.png?1', 'wetter.png',function(){
		console.log('done');
		sendingWeather(chatId,loc);
	});
});

bot.onText(/\/decide (.+)/, (msg, input) => {
	const chatID = msg.chat.id;
	var answer = Math.random() >= 0.5 ? "Yes" : "No";
	bot.sendMessage(chatID, input[1] + " " + answer);
});

bot.onText(/\/marius/, (msg) => {
	const chatID = msg.chat.id;
	bot.sendMessage(chatID, "https://i.giphy.com/media/l2YWsiql5xGPIbnzy/giphy.gif");
});
bot.onText(/\/slap (.+)/, (msg,input) => {
	const chatID = msg.chat.id;
	bot.sendMessage(chatID, "" + msg.from.first_name + " slaps " + input[1] + " around a bit with a large trout",{parse_mode : "HTML"});
});
function sendingWeather(chatId,loc){
	console.log("sending");
	var photo = __dirname+'/wetter.png';
	bot.sendPhoto(chatId, photo, {caption: "Todays weather forecast for: "+loc});
}<|endoftext|>


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

bot.on('ready', () =>  {
  console.log('Subiex is online')
  console.log('Subiex is ready')
  bot.user.setGame('┬─┬ ノ( ゜-゜ノ)-ing')
})

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

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

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

const emojis = [
		"( ͡° ͜ʖ ͡°)",
		"¯\\_(ツ)_/¯",
		"ʕ•ᴥ•ʔ",
		"(▀̿Ĺ̯▀̿ ̿)",
		"(ง ͠° ͟ل͜ ͡°)ง",
		"ಠ_ಠ",
		"̿'̿'\\̵͇̿̿\\з=( ͠° ͟ʖ ͡°)=ε/̵͇̿̿/'̿̿ ̿ ̿ ̿ ̿ ̿",
		"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
		"﴾͡๏̯͡๏﴿ O'RLY?",
		"[̲̅$̲̅(̲̅ ͡° ͜ʖ ͡°̲̅)̲̅$̲̅]",
		"(ᵔᴥᵔ)",
		"(¬‿¬)",
		"(☞ﾟヮﾟ)☞ ☜(ﾟヮﾟ☜)",
		"(づ￣ ³￣)づ",
		"ლ(ಠ益ಠლ)",
		"ಠ╭╮ಠ",
		"♪~ ᕕ(ᐛ)ᕗ",
		"ヾ(⌐■_■)ノ♪",
		"◉_◉",
		"\\ (•◡•) /",
		"༼ʘ̚ل͜ʘ̚༽",
		"┬┴┬┴┤(･_├┬┴┬┴",
		"ᕦ(ò_óˇ)ᕤ",
		"┻━┻ ︵ヽ(`Д´)ﾉ︵ ┻━┻",
		"（╯°□°）╯︵( .o.)"
	];

	const phrases = ["Take it easy pal","Whoa","Why always i have to unflip the damn table"
	,"Awesome, another table to unflip",
	"I will have my eyes on you ┬┴┬┴┤(･_├┬┴┬┴"]

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

function isMoji(moji) {
	for (var i = 0; i <= emojis.Length; i++) {
		if(emojis[i] == moji)
			return true;
		else
			return false;
	}
}

bot.on('message', (message) => {

	if(message.content.startsWith(config.prefix + 'dog'))
	{
		randomPuppy()
		.then(url => {
        	message.channel.send(url)
    	})
	}
	else if(message.content == "(╯°□°）╯︵ ┻━┻")
	{
		var index = getRandomInt(0,phrases.Length - 1);
		message.channel.send(phrases[index])
		message.channel.send("┬─┬ ノ( ゜-゜ノ)")
	}
	else if(message.content === "!moji")
	{
		var index = getRandomInt(0,24);
		message.channel.send(emojis[index]);
	}

})

bot.login(process.env.BOT_TOKEN)<commit_msg>:zap: Added Include<commit_after>const Discord = require('discord.js')
const bot = new Discord.Client()
const fs = require('fs')
const math = require('mathjs')
const config = require('./config')
const dotenv = require('dotenv')
const randomPuppy = require('random-puppy')
dotenv.load()

bot.on('ready', () =>  {
  console.log('Subiex is online')
  console.log('Subiex is ready')
  bot.user.setGame('┬─┬ ノ( ゜-゜ノ)-ing')
})

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

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

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

const emojis = [
		"( ͡° ͜ʖ ͡°)",
		"¯\\_(ツ)_/¯",
		"ʕ•ᴥ•ʔ",
		"(▀̿Ĺ̯▀̿ ̿)",
		"(ง ͠° ͟ل͜ ͡°)ง",
		"ಠ_ಠ",
		"̿'̿'\\̵͇̿̿\\з=( ͠° ͟ʖ ͡°)=ε/̵͇̿̿/'̿̿ ̿ ̿ ̿ ̿ ̿",
		"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
		"﴾͡๏̯͡๏﴿ O'RLY?",
		"[̲̅$̲̅(̲̅ ͡° ͜ʖ ͡°̲̅)̲̅$̲̅]",
		"(ᵔᴥᵔ)",
		"(¬‿¬)",
		"(☞ﾟヮﾟ)☞ ☜(ﾟヮﾟ☜)",
		"(づ￣ ³￣)づ",
		"ლ(ಠ益ಠლ)",
		"ಠ╭╮ಠ",
		"♪~ ᕕ(ᐛ)ᕗ",
		"ヾ(⌐■_■)ノ♪",
		"◉_◉",
		"\\ (•◡•) /",
		"༼ʘ̚ل͜ʘ̚༽",
		"┬┴┬┴┤(･_├┬┴┬┴",
		"ᕦ(ò_óˇ)ᕤ",
		"┻━┻ ︵ヽ(`Д´)ﾉ︵ ┻━┻",
		"（╯°□°）╯︵( .o.)"
	];

	const phrases =
	["Take it easy pal",
	"Whoa",
	"Why always me"
	,"Awesome, another table to unflip",
	"I will have my eyes on you ┬┴┬┴┤(･_├┬┴┬┴"];

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

function isMoji(moji) {
	for (var i = 0; i <= emojis.Length; i++) {
		if(emojis[i] == moji)
			return true;
		else
			return false;
	}
}

bot.on('message', (message) => {

	if(message.content.startsWith(config.prefix + 'dog'))
	{
		randomPuppy()
		.then(url => {
        	message.channel.send(url)
    	})
	}
	else if(message.content.includes("(╯°□°）╯︵ ┻━┻"))
	{
		var index = getRandomInt(0,phrases.Length - 1);
		message.channel.send(phrases[index])
		message.channel.send("┬─┬ ノ( ゜-゜ノ)")
	}
	else if(message.content === "!moji")
	{
		var index = getRandomInt(0,24);
		message.channel.send(emojis[index]);
	}

})

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


<commit_before>const { Client, Collection } = require('discord.js');
const client = new Client({ fetchAllMembers: true });
client.commands = new Collection();
client.aliases = new Collection();
client.conf = require('./conf');
const fs = require('fs');

/* Credits to https://github.com/eslachance for this easy but amazing command handler! */
fs.readdir('./commands/', (error, files) => {
  if(error) console.error(error);

  files.forEach(file => {
    if(file.endsWith('.json')) return;

    let command = require(`./commands/${file}`);
    client.commands.set(command.help.name, command);

    command.help.aliases.forEach(alias => {
      client.aliases.set(alias, command.help.name);
    });
  });
});
/* ---------- */

client.on('ready', () => {
  console.log('Selfbot ready...');
});

client.on('message', msg => {
  if(msg.author !== client.user) return;

  if(!msg.content.startsWith(client.conf.prefix)) return;

  let command = msg.content.replace(client.conf.prefix, '');
  let commandName = command.split(' ')[0];
  let params = command.split(' ').slice(1);

  if(client.commands.has(commandName)) {
    client.commands.get(commandName).exec(client, msg, params);
  } else if(client.aliases.has(commandName)) {
    client.commands.get(client.aliases.get(commandName)).exec(client, msg, params);
  }
});

client.login(client.conf.token).catch(console.error);<commit_msg>Disabled some events<commit_after>const { Client, Collection } = require('discord.js');
const client = new Client({
  fetchAllMembers: true,
  disabledEvents: [
    'channelCreate','channelDelete','channelPinsUpdate','channelUpdate','debug','error','guildBanAdd','guildBanRemove','guildEmojiCreate','guildEmojiDelete','guildEmojiUpdate','guildMemberAdd','guildMemberAvailable','guildMemberRemove','guildMembersChunk','guildMemberSpeaking','guildMemberUpdate','guildUnavailable','guildUpdate','messageDelete','messageDeleteBulk','messageUpdate','presenceUpdate','reconnecting','roleCreate','roleDelete','roleUpdate','typingStart','typingStop','userUpdate','voiceStateUpdate','warn'
  ]
});
client.commands = new Collection();
client.aliases = new Collection();
client.conf = require('./conf');
const fs = require('fs');

/* Credits to https://github.com/eslachance for this easy but amazing command handler! */
fs.readdir('./commands/', (error, files) => {
  if(error) console.error(error);

  files.forEach(file => {
    if(file.endsWith('.json')) return;

    let command = require(`./commands/${file}`);
    client.commands.set(command.help.name, command);

    command.help.aliases.forEach(alias => {
      client.aliases.set(alias, command.help.name);
    });
  });
});
/* ---------- */

client.on('ready', () => {
  console.log('Selfbot ready...');
});

client.on('message', msg => {
  if(msg.author !== client.user) return;

  if(!msg.content.startsWith(client.conf.prefix)) return;

  let command = msg.content.replace(client.conf.prefix, '');
  let commandName = command.split(' ')[0];
  let params = command.split(' ').slice(1);

  if(client.commands.has(commandName)) {
    client.commands.get(commandName).exec(client, msg, params);
  } else if(client.aliases.has(commandName)) {
    client.commands.get(client.aliases.get(commandName)).exec(client, msg, params);
  }
});

client.login(client.conf.token).catch(console.error);<|endoftext|>