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

/******************************************************************
 *
 *  bot online CONSOLE
 *
 * ***************************************************************/
bot.on('ready', () =>
{
    console.log('A sua Escrava esta pronta!');
});

/******************************************************************
 *
 *  novo usuario - bem vindo CANAL
 *
 * ***************************************************************/
bot.on("guildMemberAdd", member =>
{
    let guild = member.guild;
    guild.defaultChannel.sendMessage('Ola!, ${member.user}. Eu serei a sua escrava! Seja bem vindo(a)! :heartpulse:');
});

/******************************************************************
 *
 *  novo usuario - CONSOLE
 *
 * ***************************************************************/
bot.on("guildCreate", guild =>
{
    console.log('Nova usuario : ${guild.name}, Adicionado por ${guild.owner.user.username}');
});

/******************************************************************
 *
 *  enviar msg - commando " ! "
 *
 * ***************************************************************/
//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
     *
     * ***************************************************************/
    //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);  }*/

    /******************************************************************
     *
     *  fazer o bot falar - !falar
     *
     * ***************************************************************/
    //Faz o bot dizer alguma coisa
    if(command === "falar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            message.channel.sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :heartpulse:");
        }
    }

    /******************************************************************
     *
     *  ping
     *
     * ***************************************************************/
    //ping
    if(command === "ping")
    {
        message.channel.sendMessage(`**Pong!** \`${Date.now() - message.createdTimestamp } ms\``);
    }

    /******************************************************************
     *
     *  roll
     *
     * ***************************************************************/
    //roll
    if(command === "roll")
    {
        var roll = Math.floor(Math.random() * 1000) + 1;
        message.reply("Você tirou " + roll);
    }

    /******************************************************************
     *
     *  purge - limpar tela
     *
     * ***************************************************************/
    //purge - deleta msg do servidor - escolhe quantas msg
    if(command === "limpar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            let messagecount = parseInt(args.join(' '));
            message.channel.fetchMessages({limit: messagecount}).then(messages => message.channel.bulkDelete(messages));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :heartpulse:");
        }
    }

    /******************************************************************
     *
     *  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 === "sfalar")
    {
        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 :heartpulse:");
        }
    }

    //msg sala #eventos id - 269005594462126080 -------------------------------
    if(command === "efalar")
    {
        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 :heartpulse:");
        }
    }

    //msg sala #restrito id 269010915456843777 -------------------------------
    if(command === "rfalar")
    {
        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 :heartpulse:");
        }
    }

    //msg sala #admin id 269009554308726784 -------------------------------
    if(command === "afalar")
    {
        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 :heartpulse:");
        }
    }

    /******************************************************************
     *
     *  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 :heartpulse:");
        }
    }

    /******************************************************************
     *
     *  help
     *
     * ***************************************************************/
    //help
    if(command === "ajuda")
    {
        message.channel.sendMessage("Comandos para mandar em mim: :heartpulse:\n"+
                                    "**!ajuda** - Todos os comandos\n"+
                                    "**!ping** - O seu ping\n"+
                                    "**!roll** - Um valor random entre 1 a 1000\n"+
                                    "**!salvar texto** - Salvar coisas importantes no canal **#salvos**\n"+
                                    "O canal **#salvos** está configurado para não deletar mensagens\n"+
                                    "Use ele para salvar links ou avisos importantes\n"+

                                    "__**Comandos restritos**__\n"+
                                    "**!limpar** - Deleta as msg do servidor no canal onde foi usado\n"+
                                    "**!limpar numero** - Escolhe quantas mensagens deseja apagar\n"+
                                    "**!falar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!sfalar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!efalar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!rfalar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!afalar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!kick @nome** - Kickar usuário do servidor **Apenas: Mestre**\n"+
                                    "**!ban @nome** - Banir usuário do servidor **Apenas: Mestre**\n"+

                                    "**Sistema de webhook** - Gerenciado pelo **Mestre**\n");
    }

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

/******************************************************************
 *
 *  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 :heartpulse:").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 :heartpulse:').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 online CONSOLE
 *
 * ***************************************************************/
bot.on('ready', () =>
{
    console.log('A sua Escrava esta pronta!');
});

/******************************************************************
 *
 *  novo usuario - bem vindo CANAL
 *
 * ***************************************************************/
bot.on("guildMemberAdd", member =>
{
    let guild = member.guild;
    guild.defaultChannel.sendMessage('Ola!, ${member.user}. Eu serei a sua escrava! Seja bem vindo(a)! :heartpulse:');
});

/******************************************************************
 *
 *  novo usuario - CONSOLE
 *
 * ***************************************************************/
bot.on("guildCreate", guild =>
{
    console.log('Nova usuario : ${guild.name}, Adicionado por ${guild.owner.user.username}');
});

/******************************************************************
 *
 *  enviar msg - commando " ! "
 *
 * ***************************************************************/
//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
     *
     * ***************************************************************/
    //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);  }*/

    /******************************************************************
     *
     *  fazer o bot falar - !falar
     *
     * ***************************************************************/
    //Faz o bot dizer alguma coisa
    if(command === "falar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            message.channel.sendMessage(args.join(" "));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :heartpulse:");
        }
    }

    /******************************************************************
     *
     *  ping
     *
     * ***************************************************************/
    //ping
    if(command === "ping")
    {
        message.channel.sendMessage(`**Pong!** \`${Date.now() - message.createdTimestamp } ms\``);
    }

    /******************************************************************
     *
     *  roll
     *
     * ***************************************************************/
    //roll
    if(command === "roll")
    {
        var roll = Math.floor(Math.random() * 1000) + 1;
        message.reply("Você tirou " + roll);
    }

    /******************************************************************
     *
     *  purge - limpar tela
     *
     * ***************************************************************/
    //purge - deleta msg do servidor - escolhe quantas msg
    if(command === "limpar")
    {
        let modRole = message.guild.roles.find("name", "Mestre");
        if(message.member.roles.has(modRole.id))
        {
            let messagecount = parseInt(args.join(' '));
            message.channel.fetchMessages({limit: messagecount}).then(messages => message.channel.bulkDelete(messages));
        }
        else
        {
            message.reply("Você não tem poder para usar este comando! Morra :heartpulse:");
        }
    }

    /******************************************************************
     *
     *  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 === "sfalar")
    {
        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 :heartpulse:");
        }
    }

    //msg sala #eventos id - 269005594462126080 -------------------------------
    if(command === "efalar")
    {
        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 :heartpulse:");
        }
    }

    //msg sala #restrito id 269010915456843777 -------------------------------
    if(command === "rfalar")
    {
        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 :heartpulse:");
        }
    }

    //msg sala #admin id 269009554308726784 -------------------------------
    if(command === "afalar")
    {
        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 :heartpulse:");
        }
    }

    /******************************************************************
     *
     *  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 :heartpulse:");
        }
    }

    /******************************************************************
     *
     *  help
     *
     * ***************************************************************/
    //help
    if(command === "ajuda")
    {
        message.channel.sendMessage("Comandos para mandar em mim: :heartpulse:\n"+
                                    "**!ajuda** - Todos os comandos\n"+
                                    "**!ping** - O seu ping\n"+
                                    "**!roll** - Um valor random entre 1 a 1000\n"+
                                    "**!salvar texto** - Salvar coisas importantes no canal **#salvos**\n"+
                                    "O canal **#salvos** está configurado para não deletar mensagens\n"+
                                    "Use ele para salvar links ou avisos importantes\n"+

                                    "__**Comandos restritos**__\n"+
                                    "**!limpar** - Deleta as msg do servidor no canal onde foi usado\n"+
                                    "**!limpar numero** - Escolhe quantas mensagens deseja apagar\n"+
                                    "**!falar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!sfalar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!efalar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!rfalar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!afalar texto** - Cria comandos de fala para mim **Apenas: Mestre**\n"+
                                    "**!kick @nome** - Kickar usuário do servidor **Apenas: Mestre**\n"+
                                    "**!ban @nome** - Banir usuário do servidor **Apenas: Mestre**\n"+

                                    "**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!");
    }

/******************************************************************
 *
 *  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 :heartpulse:").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 :heartpulse:').catch(console.error);
        }).catch(console.error)
    }

}); //fim para prefixo commando

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


<commit_before>/**
 * DEPENDENCIES
 */
var twit = require('twit');
var config = require('./config');
var sentiment = require('./sentiment');

var Twitter = new twit(config);

var queryString = '#100DaysOfCode, #100daysofcode';

// Console Welcome Msg
console.log('Welcome to #100DaysOfCode');

// RETWEET
// find latest tweets according to #100daysofcode
var retweet = function () {
  var params = {
    q: queryString,
    result_type: 'recent',
    lang: 'en'
  };
  // for more parameters options, see: https://dev.twitter.com/rest/reference/get/search/tweets
  Twitter.get('search/tweets', params, function (err, data) {
    // if no errors
    if (!err) {
      // grab ID of tweet to retweet
      var retweetId = data.statuses[0].id_str;
      // Tell Twitter to retweet
      Twitter.post('statuses/retweet/:id', {
        id: retweetId
      }, function (err, response) {
        // if error while retweet
        if (err) {
          console.log('While Retweet. ERROR!...Maybe Duplicate Tweet');
        } else {
          console.log('Retweet. SUCCESS!');
        }

      });
    }
    // if unable to search a tweet
    else {
      console.log('Cannot Search Tweet. ERROR!');
    }
  });
};

retweet();
// retweet every 6 minutes
setInterval(retweet, 360000);

// FAVORITE ==============================
// find a random tweet using querySring and 'favorite' it
var favoriteTweet = function () {
  var params = {
    q: queryString,
    result_type: 'recent',
    lang: 'en'
  };
  // for more parameters, see: https://dev.twitter.com/rest/reference

  // find a tweet
  Twitter.get('search/tweets', params, function (err, data) {
    // find tweets randomly
    var tweet = data.statuses;
    var randomTweet = ranDom(tweet);    //pick a random tweet

    //if random tweet is found
    if (typeof randomTweet != 'undefined') {
      // Tell Twitter to 'favorite' it
      Twitter.post('favorites/create', { id: randomTweet.id_str }, function (err, response) {
        // if error while 'favorite'
        if (err) {
          console.log('Cannot Favorite. ERROR!');
        }
        else {
          console.log('Favorite Done. SUCCESS!');
        }
      });
    }
  });
};
// grab & 'favorite' a tweet ASAP program is running
favoriteTweet();
// 'favorite' a tweet every 12 minutes
setInterval(favoriteTweet, 720000);

// STREAM API for interacting with a USER =======
// set up a user stream
var userStream = Twitter.stream('user');

// REPLY-FOLLOW BOT ============================
// what to do when someone follows you?
userStream.on('follow', followed);

// ...trigger the callback
function followed(event) {
  console.log('Follow Event now RUNNING');
  // get USER's twitter handler (screen name)
  var name = event.source.name,
    screenName = event.source.screen_name;
  // function that replies back to every USER who followed for the first time
  tweetNow('@' + screenName + ' Thank you. What are you working on today?');
}

// function definition to tweet back to USER who followed
function tweetNow(tweetTxt) {
  var tweet = {
    status: tweetTxt
  };
  Twitter.post('statuses/update', tweet, function (err, data, response) {
    if (err) {
      console.log("Cannot Reply to Follower. ERROR!");
    }
    else {
      console.log('Reply to follower. SUCCESS!');
    }
  });
}

// Congratulation Messages for Day 1 & Day 100 ========
const hashtagStream = Twitter.stream('statuses/filter', {
  track: ['#100DaysOfCode']
});

// Function that checks if day 1 or day 100
hashtagStream.on('tweet', (tweet) => {
  if (checkIfLastDay(tweet)) {
    console.log(`Sending a congrats to @${tweet.user.screen_name}`)
    tweetNow(`WOOT! You did it @${tweet.user.screen_name}! Party Time!`)
  } else if (checkIfFirstDay(tweet)) {
    console.log(`Sending a congrats to @${tweet.user.screen_name}`)
    tweetNow(`Congrats on your first day @${tweet.user.screen_name}! Keep it up!`)
  };
})

// NOTE: String elements in firstDay & lastDay are case insensitive

function checkIfFirstDay(tweet) {
  const firstDay = ['first day', 'day one', '1/100'];
  const firstdayRegex = /\bday\s?0?1\b/i;
  console.log(`Checking if first day`)
  for (let i = 0; i < firstDay.length; i++) {
    if (checkTweetForText(tweet.text, firstDay[i]) || tweet.text.match(firstdayRegex) != null) {
      return true;
    }
  }
}

function checkIfLastDay(tweet) {
  const lastDay = ['#day100', 'final day', 'day 100', 'one hundred', '100/100'];
  const lastdayRegex = /\bday\s?100\b/i;
  console.log(`Checking if Last day`)
  for (let i = 0; i < lastDay.length; i++) {
    if (checkTweetForText(tweet.text, lastDay[i]) || tweet.text.match(lastdayRegex) != null) {
      return true;
    }
  }
}

function checkTweetForText(tweetText, value){
  return tweetText.toLowerCase().indexOf(value) > -1 && tweetText.toLowerCase().indexOf('100daysofcode') > -1
}

function ranDom(arr) {
  var index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

// SENTIMENT DETECTION =================
const hashtagStream = Twitter.stream('statuses/filter', {
   track: '#100DaysOfCode'
});

hashtagStream.on('tweet', (tweet) => {

  //  Setup the http call
  var httpCall = sentiment.init()

  // Don't do anything if it's the bot tweet
  if (tweet.user.screen_name == '_100DaysOfCode') return;

  httpCall.send("txt=" + tweet.text).end(function (result) {

    var sentim = result.body.result.sentiment;
    var confidence = parseFloat(result.body.result.confidence);

    // if sentiment is Negative and the confidence is above 75%
    if (sentim == 'Negative' && confidence >= 75) {

      // get a random quote
      var phrase = sentiment.randomQuote()
      var screen_name = tweet.user.screen_name

      // tweet a random encouragement phrase
      tweetNow('@' + screen_name + ' ' + phrase)

    }

  });
 })
<commit_msg>update, change hashtagStream name in Sentiment Detection<commit_after>/**
 * DEPENDENCIES
 */
var twit = require('twit');
var config = require('./config');
var sentiment = require('./sentiment');

var Twitter = new twit(config);

var queryString = '#100DaysOfCode, #100daysofcode';

// Console Welcome Msg
console.log('Welcome to #100DaysOfCode');

// RETWEET
// find latest tweets according to #100daysofcode
var retweet = function () {
  var params = {
    q: queryString,
    result_type: 'recent',
    lang: 'en'
  };
  // for more parameters options, see: https://dev.twitter.com/rest/reference/get/search/tweets
  Twitter.get('search/tweets', params, function (err, data) {
    // if no errors
    if (!err) {
      // grab ID of tweet to retweet
      var retweetId = data.statuses[0].id_str;
      // Tell Twitter to retweet
      Twitter.post('statuses/retweet/:id', {
        id: retweetId
      }, function (err, response) {
        // if error while retweet
        if (err) {
          console.log('While Retweet. ERROR!...Maybe Duplicate Tweet');
        } else {
          console.log('Retweet. SUCCESS!');
        }

      });
    }
    // if unable to search a tweet
    else {
      console.log('Cannot Search Tweet. ERROR!');
    }
  });
};

retweet();
// retweet every 6 minutes
setInterval(retweet, 360000);

// FAVORITE ==============================
// find a random tweet using querySring and 'favorite' it
var favoriteTweet = function () {
  var params = {
    q: queryString,
    result_type: 'recent',
    lang: 'en'
  };
  // for more parameters, see: https://dev.twitter.com/rest/reference

  // find a tweet
  Twitter.get('search/tweets', params, function (err, data) {
    // find tweets randomly
    var tweet = data.statuses;
    var randomTweet = ranDom(tweet);    //pick a random tweet

    //if random tweet is found
    if (typeof randomTweet != 'undefined') {
      // Tell Twitter to 'favorite' it
      Twitter.post('favorites/create', { id: randomTweet.id_str }, function (err, response) {
        // if error while 'favorite'
        if (err) {
          console.log('Cannot Favorite. ERROR!');
        }
        else {
          console.log('Favorite Done. SUCCESS!');
        }
      });
    }
  });
};
// grab & 'favorite' a tweet ASAP program is running
favoriteTweet();
// 'favorite' a tweet every 12 minutes
setInterval(favoriteTweet, 720000);

// STREAM API for interacting with a USER =======
// set up a user stream
var userStream = Twitter.stream('user');

// REPLY-FOLLOW BOT ============================
// what to do when someone follows you?
userStream.on('follow', followed);

// ...trigger the callback
function followed(event) {
  console.log('Follow Event now RUNNING');
  // get USER's twitter handler (screen name)
  var name = event.source.name,
    screenName = event.source.screen_name;
  // function that replies back to every USER who followed for the first time
  tweetNow('@' + screenName + ' Thank you. What are you working on today?');
}

// function definition to tweet back to USER who followed
function tweetNow(tweetTxt) {
  var tweet = {
    status: tweetTxt
  };
  Twitter.post('statuses/update', tweet, function (err, data, response) {
    if (err) {
      console.log("Cannot Reply to Follower. ERROR!");
    }
    else {
      console.log('Reply to follower. SUCCESS!');
    }
  });
}

// Congratulation Messages for Day 1 & Day 100 ========
const hashtagStream = Twitter.stream('statuses/filter', {
  track: ['#100DaysOfCode']
});

// Function that checks if day 1 or day 100
hashtagStream.on('tweet', (tweet) => {
  if (checkIfLastDay(tweet)) {
    console.log(`Sending a congrats to @${tweet.user.screen_name}`)
    tweetNow(`WOOT! You did it @${tweet.user.screen_name}! Party Time!`)
  } else if (checkIfFirstDay(tweet)) {
    console.log(`Sending a congrats to @${tweet.user.screen_name}`)
    tweetNow(`Congrats on your first day @${tweet.user.screen_name}! Keep it up!`)
  };
})

// NOTE: String elements in firstDay & lastDay are case insensitive

function checkIfFirstDay(tweet) {
  const firstDay = ['first day', 'day one', '1/100'];
  const firstdayRegex = /\bday\s?0?1\b/i;
  console.log(`Checking if first day`)
  for (let i = 0; i < firstDay.length; i++) {
    if (checkTweetForText(tweet.text, firstDay[i]) || tweet.text.match(firstdayRegex) != null) {
      return true;
    }
  }
}

function checkIfLastDay(tweet) {
  const lastDay = ['#day100', 'final day', 'day 100', 'one hundred', '100/100'];
  const lastdayRegex = /\bday\s?100\b/i;
  console.log(`Checking if Last day`)
  for (let i = 0; i < lastDay.length; i++) {
    if (checkTweetForText(tweet.text, lastDay[i]) || tweet.text.match(lastdayRegex) != null) {
      return true;
    }
  }
}

function checkTweetForText(tweetText, value){
  return tweetText.toLowerCase().indexOf(value) > -1 && tweetText.toLowerCase().indexOf('100daysofcode') > -1
}

function ranDom(arr) {
  var index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

// SENTIMENT DETECTION =================
const hashtagStream2 = Twitter.stream('statuses/filter', {
   track: '#100DaysOfCode'
});

hashtagStream2.on('tweet', (tweet) => {

  //  Setup the http call
  var httpCall = sentiment.init()

  // Don't do anything if it's the bot tweet
  if (tweet.user.screen_name == '_100DaysOfCode') return;

  httpCall.send("txt=" + tweet.text).end(function (result) {

    var sentim = result.body.result.sentiment;
    var confidence = parseFloat(result.body.result.confidence);

    // if sentiment is Negative and the confidence is above 75%
    if (sentim == 'Negative' && confidence >= 75) {

      // get a random quote
      var phrase = sentiment.randomQuote()
      var screen_name = tweet.user.screen_name

      // tweet a random encouragement phrase
      tweetNow('@' + screen_name + ' ' + phrase)

    }

  });
 })
<|endoftext|>


<commit_before>//BaconHawkJS Bot Frame Work by Bacon_Space & NiteHawk Please refer to https://github.com/BaconHawk/BaconHawkJS for help!

const chalk = require('chalk');
const logError = chalk.red('ERR!') + chalk.white
const bhlog = console.log //DONT REMOVE NITEHAWK
const Package = require('./package.json');
const Discord = require('discord.js');
let AuthData; //will be removed in coming versions
let Config;

bhlog(`Starting BaconHawkJS\nBaconHawkJS version: ${Package.version}\nDiscordJS version: v${Discord.version}`);

//Get Auth Data from Auth.json
try{
	AuthData = require('./auth.json');
} catch(e) {
	bhlog(logError('Please create an auth.json file in the main directory based off of the auth.json.example file!\n' + e.stack));
	process.exit();
}

//Get Config Data from config.json
try{
	Config = require('./config.json');
} catch(e) {
	bhlog(logError('Please create an config.json file in the main directory based off of the config.json.example file!\n' + e.stack));
	process.exit();
}

let commands = {
	"ping": {
		run: function(bot,suffix,msg) {
			msg.reply('Pong!');
		}
	},

	"about": {
		run: function(bot,suffix,msg) {
			msg.reply('Feel Free To Check Out My New Framework Right Here https://github.com/BaconHawk/BaconHawkJS/');
		}
	}
}

const bot = new Discord.Client();

function checkForCommand(msg) {
	if(msg.author.id != bot.user.id && msg.content.startsWith(Config.prefix)){

		let cmdTxt = msg.content.split(' ')[0].substring(Config.prefix.length);
		let suffix = msg.content.substring(cmdTxt.length+Config.prefix.length+1);

		bhlog(`Running ${cmdTxt}, from ${msg.author.id}, as a command!`);

		let cmd = commands[cmdTxt];

		if(cmd){
			try{
				cmd.run(bot,suffix,msg);
			} catch(e) {
				var msgTxt = `Command ${cmdTxt} was unable to run!`;
				msg.channel.sendMessage(msgTxt);
			}
		}
	}
}

bot.on('message', msg => checkForCommand(msg));
bot.on('ready', () => {log('Your bot is ready and running on ' + chalk.blue(`${bot.guilds.size}`) + ' servers with ' + chalk.blue(`${bot.channels.size}`) + ' channels for ' + chalk.blue(`${bot.users.filter(user => !user.bot).size}`) + ' users!')});

if(AuthData.bot_token){
	bot.login(AuthData.bot_token);
} else{
	bhlog(logError('Please Provide a bot token in auth.json'));
}
<commit_msg>Updated for modules<commit_after>//BaconHawkJS Bot Frame Work by Bacon_Space & NiteHawk Please refer to https://github.com/BaconHawk/BaconHawkJS for help!

const chalk = require('chalk');
const logError = chalk.red('ERR!') + chalk.white
const bhlog = console.log
const Package = require('./package.json');
const Discord = require('discord.js');
let AuthData; //will be removed in coming versions
let Config;

bhlog(`Starting BaconHawkJS\nBaconHawkJS version: ${Package.version}\nDiscordJS version: v${Discord.version}`);

//Get Auth Data from Auth.json
try{
	AuthData = require('./auth.json');
} catch(e) {
	bhlog(logError('Please create an auth.json file in the main directory based off of the auth.json.example file!\n' + e.stack));
	process.exit();
}

//Get Config Data from config.json
try{
	Config = require('./config.json');
} catch(e) {
	bhlog(logError('Please create an config.json file in the main directory based off of the config.json.example file!\n' + e.stack));
	process.exit();
}

let commands = {};

const bot = new Discord.Client();

function checkForCommand(msg) {
	if(msg.author.id != bot.user.id && msg.content.startsWith(Config.prefix)){

		let cmdTxt = msg.content.split(' ')[0].substring(Config.prefix.length);
		let suffix = msg.content.substring(cmdTxt.length+Config.prefix.length+1);

		log(`Running ${cmdTxt}, from ${msg.author.id}, as a command!`);

		let cmd = commands[cmdTxt];

		if(cmd){
			try{
				cmd.run(bot,suffix,msg);
			} catch(e) {
				var msgTxt = `Command ${cmdTxt} was unable to run!`;
				msg.channel.sendMessage(msgTxt);
			}
		}
	}
}

bot.on('message', msg => checkForCommand(msg));
bot.on('ready', () => {
	bhlog('Your bot is ready and running on ' + chalk.blue(`${bot.guilds.size}`) + ' servers with ' + chalk.blue(`${bot.channels.size}`) + ' channels for ' + chalk.blue(`${bot.users.filter(user => !user.bot).size}`) + ' users!')
	require("./modules.js").init();
});

exports.addCommand = function(commandName, commandObject){
    try {
        commands[commandName] = commandObject;
    } catch(e){
        bhlog(e);
    }
}

if(AuthData.bot_token){
	bot.login(AuthData.bot_token);
} else{
	bhlog(logError('Please Provide a bot token in auth.json'));
}
<|endoftext|>


<commit_before>// Dependencies
const Discordie = require('discordie');
const readline = require('readline');

// Plugins
const consoleHandler = require('./plugins/consoleHandler');
const messageHandler = require('./plugins/messageHandler');
const logger = require('./plugins/logger');
const osu = require('./plugins/osu');
const cleverbot = require('./plugins/cleverbot');
const music = require('./plugins/music');
const drawing = require('./plugins/drawing');

// External JSON files
const auth = require('./auth');
const config = require('./config');

const Events = Discordie.Events;
const client = new Discordie({
	autoReconnect: true
});
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

rl.on('line', c => {
	consoleHandler.respond(c, client);
});

client.connect({ token: auth.loginToken });

client.Dispatcher.on(Events.GATEWAY_READY, e => { // eslint-disable-line no-unused-vars
	client.User.setGame('with new discoveries');
	client.User.setStatus(config.idleMode ? 'idle' : 'online');
	console.log('[System] Connected.');
});

client.Dispatcher.on(Events.DISCONNECTED, e => console.log(`[System] Connection interrupted. (${e.error})`));
client.Dispatcher.on(Events.GATEWAY_RESUMED, () => console.log('[System] Connection resumed.'));

client.Dispatcher.on(Events.GUILD_MEMBER_ADD, e => {
	e.guild.generalChannel.sendMessage(`Welcome, **${e.member.name}** to **${e.guild.name}**.`);
});

client.Dispatcher.on(Events.GUILD_MEMBER_REMOVE, e => {
	e.guild.generalChannel.sendMessage(`**${e.member.name}** has left **${e.guild.name}**.`);
});

/**
 * Fired every time a message is received by the bot.
 * @param {Object} e Event object
 */
function onMessageCreate (e) {
	if (!e) return;
	const msg = e.message;
	logger.init(msg);
	messageHandler.respond(msg, client);
	if (!msg || !msg.content) return;
	osu.respond(msg);
	cleverbot.init(msg, client);
	music.respond(msg, client);
	drawing.respond(msg, client);
}

client.Dispatcher.on(Events.MESSAGE_CREATE, onMessageCreate);
<commit_msg>Fix guild leave msg<commit_after>// Dependencies
const Discordie = require('discordie');
const readline = require('readline');

// Plugins
const consoleHandler = require('./plugins/consoleHandler');
const messageHandler = require('./plugins/messageHandler');
const logger = require('./plugins/logger');
const osu = require('./plugins/osu');
const cleverbot = require('./plugins/cleverbot');
const music = require('./plugins/music');
const drawing = require('./plugins/drawing');

// External JSON files
const auth = require('./auth');
const config = require('./config');

const Events = Discordie.Events;
const client = new Discordie({
	autoReconnect: true
});
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

rl.on('line', c => {
	consoleHandler.respond(c, client);
});

client.connect({ token: auth.loginToken });

client.Dispatcher.on(Events.GATEWAY_READY, e => { // eslint-disable-line no-unused-vars
	client.User.setGame('with new discoveries');
	client.User.setStatus(config.idleMode ? 'idle' : 'online');
	console.log('[System] Connected.');
});

client.Dispatcher.on(Events.DISCONNECTED, e => console.log(`[System] Connection interrupted. (${e.error})`));
client.Dispatcher.on(Events.GATEWAY_RESUMED, () => console.log('[System] Connection resumed.'));

client.Dispatcher.on(Events.GUILD_MEMBER_ADD, e => {
	e.guild.generalChannel.sendMessage(`Welcome, **${e.member.name}** to **${e.guild.name}**.`);
});

client.Dispatcher.on(Events.GUILD_MEMBER_REMOVE, e => {
	e.guild.generalChannel.sendMessage(`**${e.user.username}** has left **${e.guild.name}**.`);
});

/**
 * Fired every time a message is received by the bot.
 * @param {Object} e Event object
 */
function onMessageCreate (e) {
	if (!e) return;
	const msg = e.message;
	// TODO: Add idle mode, top priority listen
	logger.init(msg);
	messageHandler.respond(msg, client);
	if (!msg || !msg.content) return;
	osu.respond(msg);
	cleverbot.init(msg, client);
	music.respond(msg, client);
	drawing.respond(msg, client);
}

client.Dispatcher.on(Events.MESSAGE_CREATE, onMessageCreate);
<|endoftext|>


<commit_before>'use strict';

const Twit = require('twit');
const config = require('./config');
const chalk = require('chalk');

const connectColor = chalk.cyan.bold;
const eventColor = chalk.magenta.bold;
const successColor = chalk.green.bold;
const errorColor = chalk.red.bold;

const Twitter = new Twit({
  consumer_key: config.twitter.CONSUMER_KEY,
  consumer_secret: config.twitter.CONSUMER_SECRET,
  access_token: config.twitter.ACCESS_TOKEN,
  access_token_secret: config.twitter.ACCESS_TOKEN_SECRET
});

const stream = Twitter.stream('user');

stream.on('connect', (req) => {
  console.log(connectColor('Stream connected'));
});
stream.on('disconnect', (disconnectMsg) => {
  console.log('Stream disconnected')
});

stream.on('follow', followed);

function followed(event) {
  console.log(eventColor('Follow event is running'));
  let screenName = event.source.screen_name;
  tweet(screenName);
}

function tweet(name) {
  let content = {
    status: `@${name} Thanks for following! #yeswecode #flyeaglesfly`
  }
  Twitter.post('statuses/update', content, (err, data, response) => {
    if(err) {
      console.log(errorColor('Error:'), err.message);
    } else {
      console.log(successColor('Success'));
    }
  });
}<commit_msg>changed es6 to es5<commit_after>var Twit = require('twit');
var config = require('./config');
var chalk = require('chalk');

var connectColor = chalk.cyan.bold;
var eventColor = chalk.magenta.bold;
var successColor = chalk.green.bold;
var errorColor = chalk.red.bold;

var Twitter = new Twit({
  consumer_key: config.twitter.CONSUMER_KEY,
  consumer_secret: config.twitter.CONSUMER_SECRET,
  access_token: config.twitter.ACCESS_TOKEN,
  access_token_secret: config.twitter.ACCESS_TOKEN_SECRET
});

var stream = Twitter.stream('user');

stream.on('connect', function(req) {
  console.log(connectColor('Stream connected'));
});

stream.on('follow', followed);

stream.on('disconnect', function(disconnectMsg) {
  console.log('Stream disconnected')
});

function followed(event) {
  console.log(eventColor('Follow event is running'));
  var screenName = event.source.screen_name;
  tweet(screenName);
}

function tweet(name) {
  var content = {
    status: '@' + name + ' Thanks for following! #yeswecode #flyeaglesfly'
  }
  Twitter.post('statuses/update', content, function(err, data, response) {
    if(err) {
      console.log(errorColor('Error:'), err.message);
    } else {
      console.log(successColor('Success'));
    }
  });
}<|endoftext|>


<commit_before>var builder = require('botbuilder');
var api = require('./api');
var ui = require('./ui');

var CSAS_API_KEY = process.env.CSAS_API_KEY;
var PORT = process.env.port || process.env.PORT || 3978;
var HOSTNAME = process.env.WEBSITE_HOSTNAME ? ("https://" + process.env.WEBSITE_HOSTNAME) : ("http://localhost" + ":" + PORT);

// use demo user : 7777777777 / any password
var authCallbackUrlCode = 'https://api.csas.cz/sandbox/widp/oauth2/auth?redirect_uri='+HOSTNAME+'/authCallbackServer&client_id=WebExpoClient&response_type=code';
var authCodeUrl = 'https://api.csas.cz/sandbox/widp/oauth2/auth';

var telemetryModule = require('./telemetry-module.js');

var appInsights = require('applicationinsights');
appInsights.setup(process.env.APPINSIGHTS_INSTRUMENTATIONKEY).start();
var appInsightsClient = appInsights.getClient();

function create(connector) {

    //=========================================================
    // Bot Setup
    //=========================================================

    var bot = new builder.UniversalBot(connector);

    bot.on('contactRelationUpdate', function (message) {
        // for webchat
        // if (message.action === 'add') {
        //     sendGreetings(message, bot);
        // } else {
        //     // delete their data
        // }
    });
    bot.on('conversationUpdate', function (message) {
        // for skype and emulator
        if (message.membersAdded) {
            sendGreetings(message, bot);
        }
    });

    bot.dialog('rootMenu', [
        function (session) {

            builder.Prompts.choice(session, "Select", "Accounts|Cards");
        },
        function (session, results) {
            switch (results.response.index) {
                case 0:
                    session.replaceDialog('selectAccountMenu');
                    break;
                case 1:
                    session.replaceDialog('selectCardMenu');
                    break;

                default:
                    break;
            }

        },
        function (session) {
            // Reload menu
            session.replaceDialog('rootMenu');
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i })
    .triggerAction({ matches: /^(home)/i });;

    bot.dialog('authorizeDialog', [
        function (session, nextDialog) { //, next)
            session.dialogData.nextDialog = nextDialog;
            session.userData.accountsPrompt = [];
            session.userData.access_token = "";
            session.userData.accounts = {};
            session.userData.nextDialog = nextDialog;
            sendSignInCard(session);
            var telemetry = telemetryModule.createTelemetry(session);
            appInsightsClient.trackEvent('authorizeDialog', telemetry);

        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i });

    bot.dialog('selectAccountMenu', [
        function (session) {
            var telemetry = telemetryModule.createTelemetry(session);
            appInsightsClient.trackEvent('accounts selected', telemetry);

            api.refreshAccounts(session)
                .then(function(result){
                        builder.Prompts.choice(session, "Select your account", getAccountsPromt(session));
                    }
                )
                .catch(function(e){
                    console.log("Catch handler " + e);
                    var exceptionTelemetry = telemetryModule.createTelemetry(session);
                    exceptionTelemetry.exception = e.toString();
                    appInsightsClient.trackException(exceptionTelemetry);
                    authorize(session, 'selectAccountMenu');
                });

        },
        function (session, results) {
            session.userData.acountIndex = results.response.index;
            session.replaceDialog('accountDialog');
        },
        function (session) {
            // Reload menu
            session.replaceDialog('selectAccountMenu');
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i })
    .triggerAction({ matches: /^(accounts|\?)/i });;

    bot.dialog('accountDialog', [
        function (session) {
            var telemetry = telemetryModule.createTelemetry(session);
            appInsightsClient.trackEvent('account selected', telemetry);
            builder.Prompts.choice(session, "What do you want to do? Type 'accounts' to return to account selection or 'home'", "Show balance|Show history");
        },
        function (session, results) {
            switch (results.response.index) {
                case 0:
                    session.send(ui.accountBalance(session.userData.accounts.accounts[session.userData.acountIndex]));
                    session.replaceDialog('accountDialog');
                    break;
                case 1:
                    api.accountHistory(session)
                        .then(function(result){
                                var history = '';
                                session.userData.accountHistory.transactions.forEach(function(transaction) {
                                        history += ui.transactionDetail(transaction);
                                }, this);
                                session.send(history);
                                session.replaceDialog('accountDialog');
                            }
                        )
                        .catch(function(e){
                            console.log("Catch handler " + e);
                            var exceptionTelemetry = telemetryModule.createTelemetry(session);
                            exceptionTelemetry.exception = e.toString();
                            appInsightsClient.trackException(exceptionTelemetry);
                            authorize(session, 'accountDialog');
                        });

                    break;
                default:
                    break;
            }

        },
        function (session) {
            // Reload menu
            session.replaceDialog('accountDialog');
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i });

    bot.dialog('selectCardMenu', [
        function (session) {
            var telemetry = telemetryModule.createTelemetry(session);
            appInsightsClient.trackEvent('cards selected', telemetry);
            api.refreshCards(session)
            .then(function(result){
                    builder.Prompts.choice(session, "Select your card to show more info", getCardsPromt(session));
                }
            )
            .catch(function(e){
                console.log("Catch handler " + e);
                var exceptionTelemetry = telemetryModule.createTelemetry(session);
                exceptionTelemetry.exception = e.toString();
                appInsightsClient.trackException(exceptionTelemetry);
                authorize(session, 'selectCardMenu');
            });
        },
        function (session, results) {
            session.userData.cardIndex = results.response.index;
            var cardBalance = ui.cardBalance(session.userData.cards.cards[session.userData.cardIndex]);
            session.send(cardBalance);
            session.replaceDialog('selectCardMenu');
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i })
    .triggerAction({ matches: /^(cards|\?)/i });;

    return bot;
};

module.exports = { create };

// private functions

function getAccountsPromt(session)
{
    var accountsPrompt = [];
    session.userData.accounts.accounts.forEach(function(account) {
        accountsPrompt.push(ui.accountNumber(account));
    }, this);
    return accountsPrompt;
}
function getCardsPromt(session)
{
    var cardsPrompt = [];
    session.userData.cards.cards.forEach(function(card) {
        cardsPrompt.push(ui.shortCardInfo(card));
    }, this);
    return cardsPrompt;
}
 function authorize(session, nextDialog)
{
    session.replaceDialog('authorizeDialog', nextDialog);
}

function sendGreetings(message, bot)
{
    var name = message.user ? message.user.name : null;
    message.membersAdded.forEach(function (identity) {
        if (identity.id === message.address.bot.id) {
            var session = bot.loadSession(message.address, function(error, session){
                var telemetry = telemetryModule.createTelemetry(session, { where: 'conversationUpdate' });
                appInsightsClient.trackTrace('start', telemetry);
                session.send("Hello %s...  I'm a CSAS bank bot ...", name || 'there');
                session.userData.nextDialog = "rootMenu";
                session.replaceDialog('authorizeDialog', 'rootMenu')
            });

        }
    });
}
function sendSignInCard(session){
    var b = new Buffer(JSON.stringify(session.message.address));
    var card = createSigninCard(session, authCallbackUrlCode + "&state=" + b.toString('base64'));
    // attach the card to the reply message
    var msg = new builder.Message(session).addAttachment(card);
    session.send(msg);
}

function createSigninCard(session, url) {
    return new builder.SigninCard(session)
        .text('CSAS Sandbox, please sign-in first')
        .button('Sign-in', url);
}<commit_msg>refactoring<commit_after>var builder = require('botbuilder');
var api = require('./api');
var ui = require('./ui');

var CSAS_API_KEY = process.env.CSAS_API_KEY;
var PORT = process.env.port || process.env.PORT || 3978;
var HOSTNAME = process.env.WEBSITE_HOSTNAME ? ("https://" + process.env.WEBSITE_HOSTNAME) : ("http://localhost" + ":" + PORT);

// use demo user : 7777777777 / any password
var authCallbackUrlCode = 'https://api.csas.cz/sandbox/widp/oauth2/auth?redirect_uri='+HOSTNAME+'/authCallbackServer&client_id=WebExpoClient&response_type=code';
var authCodeUrl = 'https://api.csas.cz/sandbox/widp/oauth2/auth';

var telemetryModule = require('./telemetry-module.js');

var appInsights = require('applicationinsights');
appInsights.setup(process.env.APPINSIGHTS_INSTRUMENTATIONKEY).start();
var appInsightsClient = appInsights.getClient();

function create(connector) {

    //=========================================================
    // Bot Setup
    //=========================================================

    var bot = new builder.UniversalBot(connector);

    bot.on('contactRelationUpdate', function (message) {
        // for webchat
        // if (message.action === 'add') {
        //     sendGreetings(message, bot);
        // } else {
        //     // delete their data
        // }
    });
    bot.on('conversationUpdate', function (message) {
        // for skype and emulator
        if (message.membersAdded) {
            sendGreetings(message, bot);
        }
    });

    bot.dialog('rootMenu', [
        function (session) {

            builder.Prompts.choice(session, "Select", "Accounts|Cards");
        },
        function (session, results) {
            switch (results.response.index) {
                case 0:
                    session.replaceDialog('selectAccountMenu');
                    break;
                case 1:
                    session.replaceDialog('selectCardMenu');
                    break;

                default:
                    break;
            }

        },
        function (session) {
            // Reload menu
            session.replaceDialog('rootMenu');
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i })
    .triggerAction({ matches: /^(home)/i });;

    bot.dialog('authorizeDialog', [
        function (session, nextDialog) { //, next)
            session.userData.accountsPrompt = [];
            session.userData.access_token = "";
            session.userData.accounts = {};

            session.userData.nextDialog = nextDialog;

            var telemetry = telemetryModule.createTelemetry(session);
            appInsightsClient.trackEvent('authorizeDialog', telemetry);

            sendSignInCard(session);
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i });

    bot.dialog('selectAccountMenu', [
        function (session) {
            var telemetry = telemetryModule.createTelemetry(session);
            appInsightsClient.trackEvent('accounts selected', telemetry);

            api.refreshAccounts(session)
                .then(function(result){
                        builder.Prompts.choice(session, "Select your account", getAccountsPromt(session));
                    }
                )
                .catch(function(e){
                    console.log("Catch handler " + e);
                    var exceptionTelemetry = telemetryModule.createTelemetry(session);
                    exceptionTelemetry.exception = e.toString();
                    appInsightsClient.trackException(exceptionTelemetry);
                    authorize(session, 'selectAccountMenu');
                });

        },
        function (session, results) {
            session.userData.acountIndex = results.response.index;
            session.replaceDialog('accountDialog');
        },
        function (session) {
            // Reload menu
            session.replaceDialog('selectAccountMenu');
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i })
    .triggerAction({ matches: /^(accounts|\?)/i });;

    bot.dialog('accountDialog', [
        function (session) {
            var telemetry = telemetryModule.createTelemetry(session);
            appInsightsClient.trackEvent('account selected', telemetry);
            builder.Prompts.choice(session, "What do you want to do? Type 'accounts' to return to account selection or 'home'", "Show balance|Show history");
        },
        function (session, results) {
            switch (results.response.index) {
                case 0:
                    session.send(ui.accountBalance(session.userData.accounts.accounts[session.userData.acountIndex]));
                    session.replaceDialog('accountDialog');
                    break;
                case 1:
                    api.accountHistory(session)
                        .then(function(result){
                                var history = '';
                                session.userData.accountHistory.transactions.forEach(function(transaction) {
                                        history += ui.transactionDetail(transaction);
                                }, this);
                                session.send(history);
                                session.replaceDialog('accountDialog');
                            }
                        )
                        .catch(function(e){
                            console.log("Catch handler " + e);
                            var exceptionTelemetry = telemetryModule.createTelemetry(session);
                            exceptionTelemetry.exception = e.toString();
                            appInsightsClient.trackException(exceptionTelemetry);
                            authorize(session, 'accountDialog');
                        });

                    break;
                default:
                    break;
            }

        },
        function (session) {
            // Reload menu
            session.replaceDialog('accountDialog');
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i });

    bot.dialog('selectCardMenu', [
        function (session) {
            var telemetry = telemetryModule.createTelemetry(session);
            appInsightsClient.trackEvent('cards selected', telemetry);
            api.refreshCards(session)
            .then(function(result){
                    builder.Prompts.choice(session, "Select your card to show more info", getCardsPromt(session));
                }
            )
            .catch(function(e){
                console.log("Catch handler " + e);
                var exceptionTelemetry = telemetryModule.createTelemetry(session);
                exceptionTelemetry.exception = e.toString();
                appInsightsClient.trackException(exceptionTelemetry);
                authorize(session, 'selectCardMenu');
            });
        },
        function (session, results) {
            session.userData.cardIndex = results.response.index;
            var cardBalance = ui.cardBalance(session.userData.cards.cards[session.userData.cardIndex]);
            session.send(cardBalance);
            session.replaceDialog('selectCardMenu');
        }
    ])
    .reloadAction('showMenu', null, { matches: /^(menu|help|\?)/i })
    .triggerAction({ matches: /^(cards|\?)/i });;

    return bot;
};

module.exports = { create };

// private functions

function getAccountsPromt(session)
{
    var accountsPrompt = [];
    session.userData.accounts.accounts.forEach(function(account) {
        accountsPrompt.push(ui.accountNumber(account));
    }, this);
    return accountsPrompt;
}
function getCardsPromt(session)
{
    var cardsPrompt = [];
    session.userData.cards.cards.forEach(function(card) {
        cardsPrompt.push(ui.shortCardInfo(card));
    }, this);
    return cardsPrompt;
}
 function authorize(session, nextDialog)
{
    session.replaceDialog('authorizeDialog', nextDialog);
}

function sendGreetings(message, bot)
{
    var name = message.user ? message.user.name : null;
    message.membersAdded.forEach(function (identity) {
        if (identity.id === message.address.bot.id) {
            var session = bot.loadSession(message.address, function(error, session){
                var telemetry = telemetryModule.createTelemetry(session, { where: 'conversationUpdate' });
                appInsightsClient.trackTrace('start', telemetry);
                session.send("Hello %s...  I'm a CSAS bank bot ...", name || 'there');
                session.userData.nextDialog = "rootMenu";
                session.replaceDialog('authorizeDialog', 'rootMenu')
            });

        }
    });
}
function sendSignInCard(session){
    var b = new Buffer(JSON.stringify(session.message.address));
    var card = createSigninCard(session, authCallbackUrlCode + "&state=" + b.toString('base64'));
    // attach the card to the reply message
    var msg = new builder.Message(session).addAttachment(card);
    session.send(msg);
}

function createSigninCard(session, url) {
    return new builder.SigninCard(session)
        .text('CSAS Sandbox, please sign-in first')
        .button('Sign-in', url);
}<|endoftext|>


<commit_before>// This code is awful, and I know it.

var config = Config.ircconfig;

exports.report = function report(message) {
	if (!config) {
		return;
	}
	var room = config.reportroom;
	if (room) {
		say(room, message);
	}
};

if (!config) {
	return;
}

var irc = require('irc');
var Pool = require('generic-pool').Pool;
var Client = require('pg-native');

var pool = Pool({
	create: function (callback) {
		var client = new Client();
		client.connect(function (err) {
			if (err) {
				callback(err, null);
			} else {
				callback(null, client);
			}
		});
	},
	destroy: function (client) {
		client.end();
	},
	max: 5,
	idleTimeoutMillis: 30000
});

var connection = exports.connection = new irc.Client(config.server, config.nickname, config);

function say(room, message) {
	connection.say(room, message);
	if (!config.loggerid) return;
	var messages = message.split("\n");
	for (var i = 0; i < messages.length; i++) {
		log(config.loggerid, 1, config.nickname, messages[i]);
	}
}

function log(bufferid, type, user, message) {
	pool.acquire(function (err, client) {
		if (err) throw err;
		client.query('SELECT insert_row($1, $2, $3, $4)', [bufferid, type, user, message], function (err, result) {
			pool.release(client);
			if (err) throw err;
		});
	});
}

function listenForLogs(socket, channel, bufferid) {
	socket.on('join' + channel, function join(nick, message) {
		log(bufferid, 32, message.prefix, channel);
	});

	socket.on('part' + channel, function part(nick, reason, message) {
		log(bufferid, 64, message.prefix, reason);
	});

	socket.on('quit', function quit(nick, reason, channels, message) {
		if (channels.indexOf(channel) !== -1) return;

		log(bufferid, 128, message.prefix, reason);
	});

	socket.on('kick' + channel, function kick(nick, by, reason, message) {
		log(bufferid, 256, message.prefix, nick + ' ' + reason);
	});

	socket.on('action', function action(nick, to, actionMessage, message) {
		log(bufferid, 4, message.prefix, actionMessage);
	});

	socket.on('notice', function notice(nick, to, text, message) {
		if (to !== channel) return;
		log(bufferid, 2, message.prefix, text);
	});

	socket.on('nick', function nick(oldnick, newnick, channels, message) {
		log(bufferid, 8, message.prefix, newnick);
	});

	socket.on('topic', function topic(to, newTopic, nick, message) {
		if (to !== channel) return;
		// Initial message
		if (/!/.test(nick)) {
			log(bufferid, 16384, "", 'Topic for ' + to + ' is "' + newTopic + '"');
		} else {
			log(bufferid, 16384, "", nick + ' has changed topic for ' + to + ' to: "' + newTopic + '"');
		}
	});

	// Mode messages in IRC framework are way too clever.
	socket.on('raw', function (message) {
		if (message.command !== 'MODE' || message.args[0] !== channel) return;
		log(bufferid, 16, message.prefix, message.args.join(' '));
	});
}

function identity(value) {
	return function identityFunction() {
		return value;
	};
}

function parseRaw(message) {
	return message
		.replace(/Super Effective<\/font><\/b>/g, "\x033Super Effective\x0F")
		.replace(/]*room=[^>]*>(.*?)<\/a>/g, "$1")
		.replace(/(.*?)<\/a>/g, "[$2]($1)")
		.replace(/
/g, "\n  • ")
		.replace(/<\/?(?:ul|font size|div)[^>]*?>/g, "")
		.replace(/.*?<\/small>/g, "")
		.replace(/<\/?(?:b|strong)(?: class="username")?>/g, "\x02")
		.replace(/<\/?em>/g, "\x1D")
		.replace(/<(?:\/span|\/font|font color=black)>/g, "\x0F")
		.replace(//g, "\x02\x034")
		.replace(//g, "\x02\x0312")
		.replace(//g, "\x02\x0314")
		.replace(//g, "\x02\x1F\x033")
		.replace(//g, "\x02\x1F\x034")
		.replace(//g, "\x0314")
		.replace(//g, "\x0314")
		.replace(/ |  | +/g, " ")
		.replace(/✓/g, "✓")
		.replace(/</g, "<")
		.replace(/>/g, ">")
		.replace(/"/g, '"')
		.replace(/'/g, "'")
		.replace(///g, "/")
		.replace(/é/g, "é")
		.replace(/&/g, "&")
		.split(/
/);
}

function verifyParts(parts) {
	if (parts.length > 6) {
		return false;
	}
	for (var i = 0; i < parts.length; i++) {
		var part = parts[i];
		if (part.length > 440) {
			return false;
		}
	}
	return true;
}

var dataParsers = {
	pokemon: function (specie) {
		var specieData = Tools.getTemplate(specie);
		var result = [];
		var tier = specieData.tier;
		if (!require('./data/tpp').BattleTPP[specieData.id] && !specieData.isNonstandard && !specieData.isUnreleased) {
			tier = 'T-Rule ' + tier;
		}
		result.push(tier);
		result.push(specieData.species);
		result.push(specieData.types.join("/") + '-type');

		var baseStats = [];
		var bst = 0;
		var stats = ['HP', 'Atk', 'Def', 'SpA', 'SpD', 'Spe'];
		var statsLength = stats.length;
		var i;
		for (i = 0; i < statsLength; i++) {
			var stat = stats[i];
			var statValue = specieData.baseStats[toId(stat)];
			bst += statValue;
			baseStats.push('\x0314' + stat + ':\x0F ' + statValue);
		}
		baseStats.push('\x0314BST:\x0F ' + bst);
		result.push(baseStats.join(', '));

		var abilityData = specieData.abilities;
		var abilityOrder = [0, 1, 'H'];
		var abilityOrderLength = abilityOrder.length;
		var abilities = [];

		for (i = 0; i < abilityOrderLength; i++) {
			var abilityPosition = abilityOrder[i];
			var ability = abilityData[abilityPosition];
			if (ability) {
				if (abilityPosition === 'H') {
					ability = '\x1D' + ability + '\x1D';
				}
				abilities.push(ability);
			}
		}
		result.push('\x0314Abilities:\x0F ' + abilities.join(', '));

		return result.join(' | ');
	},
	item: function (item) {
		var itemData = Tools.getItem(item);
		return [itemData.name, itemData.desc].join(' | ');
	},
	ability: function (ability) {
		var abilityData = Tools.getAbility(ability);
		return [abilityData.name, abilityData.shortDesc].join(' | ');
	},
	move: function (move) {
		var moveData = Tools.getMove(move);

		var result = [];
		result.push(moveData.name);
		result.push(moveData.category);
		result.push(moveData.type + '-type');

		if (moveData.category !== 'Status') {
			if (moveData.basePower) {
				result.push('\x0314Power:\x0F ' + moveData.basePower + ' BP');
			} else {
				result.push('\x0314Power:\x0F —');
			}
		}

		if (moveData.accuracy === true) {
			result.push('\x0314Accuracy:\x0F —');
		} else {
			result.push('\x0314Accuracy:\x0F ' + moveData.accuracy + '%');
		}

		result.push('\x0314PP:\x0F ' + moveData.pp * 8 / 5);
		result.push(moveData.shortDesc);

		return result.join(' | ');
	}
};

function filter(rawMessage) {
	var parts = rawMessage.split(/\n/);
	var rawSignal = '|raw|';
	var dataSignal = '|c|~|/data-';
	var errorSignal = '|html|
';
	var finalParts = [];
	for (var i = 0; i < parts.length; i++) {
		var part = parts[i];
		var message;
		if (part.slice(0, rawSignal.length) === rawSignal) {
			message = part.slice(rawSignal.length);
			Array.prototype.push.apply(finalParts, parseRaw(message));
		} else if (part.slice(0, dataSignal.length) === dataSignal) {
			message = part.slice(dataSignal.length);
			var splitter = message.indexOf(' ');
			var type = message.slice(0, splitter);
			var what = message.slice(splitter + 1);
			finalParts.push(dataParsers[type](what));
		} else if (part.slice(0, errorSignal.length) !== errorSignal) {
			finalParts.push(part);
		}
	}
	if (!verifyParts(finalParts)) return "Response too long.";
	return finalParts.join("\n");
}

function FakeRoom(id) {
	this.id = id;
}
FakeRoom.prototype.isMuted = identity(false);
FakeRoom.prototype.users = {};

var ircUser = {
	named: false,
	can: identity(false),
	resetName: identity(),
	tryJoinRoom: identity(null),
	leaveRoom: identity(),
	group: ' '
};

var ircConnection = {
	sendTo: function (room, message) {
		say(room.id, filter(message));
	},
	popup: identity()
};

connection.on('message', function parseMessage(from, to, text, message) {
	if (config.loggerid && to === (config.reportroom || config.channels[0])) {
		log(config.loggerid, 1, message.prefix, text);
	}
	if (to.charAt(0) !== '#') {
		to = from;
	}
	if (/\byay\b/i.test(text)) {
		connection.say(to, 'Y+A+Y');
	}
	// DootBot conflict
	if (text.slice(0, 2) === '!?') return;
	if (text.charAt(0) !== '!' && text.charAt(0) !== '/') return;
	CommandParser.parse('/' + text.slice(1), new FakeRoom(to), ircUser, ircConnection);
});

if (config.loggerid) {
	listenForLogs(connection, config.reportroom || config.channels[0], config.loggerid);
}

if (!Config.irclog) {
	Config.irclog = [];
}

for (var i = 0; i < Config.irclog.length; i++) {
	var server = Config.irclog[i];
	var channels = server.channels;
	server.channels = server.channels.map(function (channel) {
		return channel.name;
	});
	var logConnection = new irc.Client(server.server, server.nickname, server);
	for (var j = 0; j < channels.length; j++) {
		var channel = channels[j];
		listenForLogs(logConnection, channel.name, channel.loggerid);
		logConnection.on('message' + channel.name, function (nick, text, message) {
			log(channel.loggerid, 1, message.prefix, text);
		});
	}
}
<commit_msg>Fix channel list check in YayBot.<commit_after>// This code is awful, and I know it.

var config = Config.ircconfig;

exports.report = function report(message) {
	if (!config) {
		return;
	}
	var room = config.reportroom;
	if (room) {
		say(room, message);
	}
};

if (!config) {
	return;
}

var irc = require('irc');
var Pool = require('generic-pool').Pool;
var Client = require('pg-native');

var pool = Pool({
	create: function (callback) {
		var client = new Client();
		client.connect(function (err) {
			if (err) {
				callback(err, null);
			} else {
				callback(null, client);
			}
		});
	},
	destroy: function (client) {
		client.end();
	},
	max: 5,
	idleTimeoutMillis: 30000
});

var connection = exports.connection = new irc.Client(config.server, config.nickname, config);

function say(room, message) {
	connection.say(room, message);
	if (!config.loggerid) return;
	var messages = message.split("\n");
	for (var i = 0; i < messages.length; i++) {
		log(config.loggerid, 1, config.nickname, messages[i]);
	}
}

function log(bufferid, type, user, message) {
	pool.acquire(function (err, client) {
		if (err) throw err;
		client.query('SELECT insert_row($1, $2, $3, $4)', [bufferid, type, user, message], function (err, result) {
			pool.release(client);
			if (err) throw err;
		});
	});
}

function listenForLogs(socket, channel, bufferid) {
	socket.on('join' + channel, function join(nick, message) {
		log(bufferid, 32, message.prefix, channel);
	});

	socket.on('part' + channel, function part(nick, reason, message) {
		log(bufferid, 64, message.prefix, reason);
	});

	socket.on('quit', function quit(nick, reason, channels, message) {
		if (channels.indexOf(channel) === -1) return;

		log(bufferid, 128, message.prefix, reason);
	});

	socket.on('kick' + channel, function kick(nick, by, reason, message) {
		log(bufferid, 256, message.prefix, nick + ' ' + reason);
	});

	socket.on('action', function action(nick, to, actionMessage, message) {
		log(bufferid, 4, message.prefix, actionMessage);
	});

	socket.on('notice', function notice(nick, to, text, message) {
		if (to !== channel) return;
		log(bufferid, 2, message.prefix, text);
	});

	socket.on('nick', function nick(oldnick, newnick, channels, message) {
		if (channels.indexOf(channel) === -1) return;

		log(bufferid, 8, message.prefix, newnick);
	});

	socket.on('topic', function topic(to, newTopic, nick, message) {
		if (to !== channel) return;
		// Initial message
		if (/!/.test(nick)) {
			log(bufferid, 16384, "", 'Topic for ' + to + ' is "' + newTopic + '"');
		} else {
			log(bufferid, 16384, "", nick + ' has changed topic for ' + to + ' to: "' + newTopic + '"');
		}
	});

	// Mode messages in IRC framework are way too clever.
	socket.on('raw', function (message) {
		if (message.command !== 'MODE' || message.args[0] !== channel) return;
		log(bufferid, 16, message.prefix, message.args.join(' '));
	});
}

function identity(value) {
	return function identityFunction() {
		return value;
	};
}

function parseRaw(message) {
	return message
		.replace(/Super Effective<\/font><\/b>/g, "\x033Super Effective\x0F")
		.replace(/]*room=[^>]*>(.*?)<\/a>/g, "$1")
		.replace(/(.*?)<\/a>/g, "[$2]($1)")
		.replace(/
/g, "\n  • ")
		.replace(/<\/?(?:ul|font size|div)[^>]*?>/g, "")
		.replace(/.*?<\/small>/g, "")
		.replace(/<\/?(?:b|strong)(?: class="username")?>/g, "\x02")
		.replace(/<\/?em>/g, "\x1D")
		.replace(/<(?:\/span|\/font|font color=black)>/g, "\x0F")
		.replace(//g, "\x02\x034")
		.replace(//g, "\x02\x0312")
		.replace(//g, "\x02\x0314")
		.replace(//g, "\x02\x1F\x033")
		.replace(//g, "\x02\x1F\x034")
		.replace(//g, "\x0314")
		.replace(//g, "\x0314")
		.replace(/ |  | +/g, " ")
		.replace(/✓/g, "✓")
		.replace(/</g, "<")
		.replace(/>/g, ">")
		.replace(/"/g, '"')
		.replace(/'/g, "'")
		.replace(///g, "/")
		.replace(/é/g, "é")
		.replace(/&/g, "&")
		.split(/
/);
}

function verifyParts(parts) {
	if (parts.length > 6) {
		return false;
	}
	for (var i = 0; i < parts.length; i++) {
		var part = parts[i];
		if (part.length > 440) {
			return false;
		}
	}
	return true;
}

var dataParsers = {
	pokemon: function (specie) {
		var specieData = Tools.getTemplate(specie);
		var result = [];
		var tier = specieData.tier;
		if (!require('./data/tpp').BattleTPP[specieData.id] && !specieData.isNonstandard && !specieData.isUnreleased) {
			tier = 'T-Rule ' + tier;
		}
		result.push(tier);
		result.push(specieData.species);
		result.push(specieData.types.join("/") + '-type');

		var baseStats = [];
		var bst = 0;
		var stats = ['HP', 'Atk', 'Def', 'SpA', 'SpD', 'Spe'];
		var statsLength = stats.length;
		var i;
		for (i = 0; i < statsLength; i++) {
			var stat = stats[i];
			var statValue = specieData.baseStats[toId(stat)];
			bst += statValue;
			baseStats.push('\x0314' + stat + ':\x0F ' + statValue);
		}
		baseStats.push('\x0314BST:\x0F ' + bst);
		result.push(baseStats.join(', '));

		var abilityData = specieData.abilities;
		var abilityOrder = [0, 1, 'H'];
		var abilityOrderLength = abilityOrder.length;
		var abilities = [];

		for (i = 0; i < abilityOrderLength; i++) {
			var abilityPosition = abilityOrder[i];
			var ability = abilityData[abilityPosition];
			if (ability) {
				if (abilityPosition === 'H') {
					ability = '\x1D' + ability + '\x1D';
				}
				abilities.push(ability);
			}
		}
		result.push('\x0314Abilities:\x0F ' + abilities.join(', '));

		return result.join(' | ');
	},
	item: function (item) {
		var itemData = Tools.getItem(item);
		return [itemData.name, itemData.desc].join(' | ');
	},
	ability: function (ability) {
		var abilityData = Tools.getAbility(ability);
		return [abilityData.name, abilityData.shortDesc].join(' | ');
	},
	move: function (move) {
		var moveData = Tools.getMove(move);

		var result = [];
		result.push(moveData.name);
		result.push(moveData.category);
		result.push(moveData.type + '-type');

		if (moveData.category !== 'Status') {
			if (moveData.basePower) {
				result.push('\x0314Power:\x0F ' + moveData.basePower + ' BP');
			} else {
				result.push('\x0314Power:\x0F —');
			}
		}

		if (moveData.accuracy === true) {
			result.push('\x0314Accuracy:\x0F —');
		} else {
			result.push('\x0314Accuracy:\x0F ' + moveData.accuracy + '%');
		}

		result.push('\x0314PP:\x0F ' + moveData.pp * 8 / 5);
		result.push(moveData.shortDesc);

		return result.join(' | ');
	}
};

function filter(rawMessage) {
	var parts = rawMessage.split(/\n/);
	var rawSignal = '|raw|';
	var dataSignal = '|c|~|/data-';
	var errorSignal = '|html|
';
	var finalParts = [];
	for (var i = 0; i < parts.length; i++) {
		var part = parts[i];
		var message;
		if (part.slice(0, rawSignal.length) === rawSignal) {
			message = part.slice(rawSignal.length);
			Array.prototype.push.apply(finalParts, parseRaw(message));
		} else if (part.slice(0, dataSignal.length) === dataSignal) {
			message = part.slice(dataSignal.length);
			var splitter = message.indexOf(' ');
			var type = message.slice(0, splitter);
			var what = message.slice(splitter + 1);
			finalParts.push(dataParsers[type](what));
		} else if (part.slice(0, errorSignal.length) !== errorSignal) {
			finalParts.push(part);
		}
	}
	if (!verifyParts(finalParts)) return "Response too long.";
	return finalParts.join("\n");
}

function FakeRoom(id) {
	this.id = id;
}
FakeRoom.prototype.isMuted = identity(false);
FakeRoom.prototype.users = {};

var ircUser = {
	named: false,
	can: identity(false),
	resetName: identity(),
	tryJoinRoom: identity(null),
	leaveRoom: identity(),
	group: ' '
};

var ircConnection = {
	sendTo: function (room, message) {
		say(room.id, filter(message));
	},
	popup: identity()
};

connection.on('message', function parseMessage(from, to, text, message) {
	if (config.loggerid && to === (config.reportroom || config.channels[0])) {
		log(config.loggerid, 1, message.prefix, text);
	}
	if (to.charAt(0) !== '#') {
		to = from;
	}
	if (/\byay\b/i.test(text)) {
		connection.say(to, 'Y+A+Y');
	}
	// DootBot conflict
	if (text.slice(0, 2) === '!?') return;
	if (text.charAt(0) !== '!' && text.charAt(0) !== '/') return;
	CommandParser.parse('/' + text.slice(1), new FakeRoom(to), ircUser, ircConnection);
});

if (config.loggerid) {
	listenForLogs(connection, config.reportroom || config.channels[0], config.loggerid);
}

if (!Config.irclog) {
	Config.irclog = [];
}

for (var i = 0; i < Config.irclog.length; i++) {
	var server = Config.irclog[i];
	var channels = server.channels;
	server.channels = server.channels.map(function (channel) {
		return channel.name;
	});
	var logConnection = new irc.Client(server.server, server.nickname, server);
	for (var j = 0; j < channels.length; j++) {
		var channel = channels[j];
		listenForLogs(logConnection, channel.name, channel.loggerid);
		logConnection.on('message' + channel.name, function (nick, text, message) {
			log(channel.loggerid, 1, message.prefix, text);
		});
	}
}
<|endoftext|>


<commit_before>// bot.js
'use strict';

// Loading env configuration
require('dotenv').config({path: `${__dirname}/.env`});

// BASE SETUP
// =============================================================================

// needed packages

// express, used for the api
const express					= require('express');
const app							= express();

// bodyparser, used for parsing json body
const bodyParser			= require('body-parser');

// setting port
const port						= process.env.PORT || 8080;

// filesystem module
const fs							= require('fs');

// Discord Bot
const bot = new (require('discord.js')).Client();

global.hello = {};

try {
	global.hello = JSON.parse(fs.readFileSync(`${__dirname}/.config/hello.json`).toString());
} catch(e) {
	console.log(e);
	global.hello = {};
}

global.answers = {};

try {
	global.answers = JSON.parse(fs.readFileSync(`${__dirname}/.config/answers.json`).toString());
} catch(e) {
	global.answers = {};
}

global.mentions = [];

try {
	global.mentions = JSON.parse(fs.readFileSync(`${__dirname}/.config/mentions.json`).toString());
} catch(e) {
	global.mentions = [];
}

// Basic express settings
app.set('json spaces', 2);
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

app.get('/', (req, res) => {
	res.json({msg: 'Qu\'est que tu veux encore ?'});
});

// requiring routers
app.use('/hello', require('./controllers/hello'));
app.use('/answers', require('./controllers/answers'));
app.use('/mentions', require('./controllers/mentions'));

app.listen(process.env.PORT, function () {
	console.log("Magic happens on port", process.env.PORT);
});

bot.on('ready', () => {
	bot.channels
		.filter(channel => channel.type === 'text')
		.forEach(channel => channel.sendMessage("Salut bande de batards !"));
});

bot.on('message', (message) => {
	if(message.author.bot){
		return;
	}

	let match;
	const content = message.cleanContent.toLowerCase();
	const sContent = content.split(' ');

	const helloMatch = global.hello.triggers.indexOf(sContent) > -1;

	const answersMatch = helloMatch || Object.keys(global.answers).indexOf(sContent) > -1;

	const mentionsMatch = answersMatch || content.indexOf('@slackbot') > -1;

	if(helloMatch){
		const a = global.hello.answers;
		message.reply(a[Math.floor(Math.random() * a.length)]);
		console.log(`Replied to hello ${content}`);
	} else if (answersMatch){
		message.reply(global.answers[answersMatch]);
		console.log(`Replied to answers ${content}`);
	} else if(mentionsMatch) {
		const m = global.mentions;
		message.reply(m[Math.floor(Math.random() * m.length)]);
		console.log(`Replied to mention ${content}`);
	} else {
		console.log(`Nothing matches "${content}"`);
	}

});

bot.login(process.env.TOKEN);
<commit_msg>Fix message recognition<commit_after>// bot.js
'use strict';

// Loading env configuration
require('dotenv').config({path: `${__dirname}/.env`});

// BASE SETUP
// =============================================================================

// needed packages

// express, used for the api
const express					= require('express');
const app							= express();

// bodyparser, used for parsing json body
const bodyParser			= require('body-parser');

// setting port
const port						= process.env.PORT || 8080;

// filesystem module
const fs							= require('fs');

// Discord Bot
const bot = new (require('discord.js')).Client();

global.hello = {};

try {
	global.hello = JSON.parse(fs.readFileSync(`${__dirname}/.config/hello.json`).toString());
} catch(e) {
	console.log(e);
	global.hello = {};
}

global.answers = {};

try {
	global.answers = JSON.parse(fs.readFileSync(`${__dirname}/.config/answers.json`).toString());
} catch(e) {
	global.answers = {};
}

global.mentions = [];

try {
	global.mentions = JSON.parse(fs.readFileSync(`${__dirname}/.config/mentions.json`).toString());
} catch(e) {
	global.mentions = [];
}

// Basic express settings
app.set('json spaces', 2);
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

app.get('/', (req, res) => {
	res.json({msg: 'Qu\'est que tu veux encore ?'});
});

// requiring routers
app.use('/hello', require('./controllers/hello'));
app.use('/answers', require('./controllers/answers'));
app.use('/mentions', require('./controllers/mentions'));

app.listen(process.env.PORT, function () {
	console.log("Magic happens on port", process.env.PORT);
});

bot.on('ready', () => {
	bot.channels
		.filter(channel => channel.type === 'text')
		.forEach(channel => channel.sendMessage("Salut bande de batards !"));
});

bot.on('message', (message) => {
	if(message.author.bot){
		return;
	}

	let match;
	const content = message.cleanContent.toLowerCase();
	const sContent = content.split(' ');

	const helloMatch = global.hello.triggers.find(t => t.toLowerCase() === content);

	const answersMatch = helloMatch || Object.keys(global.answers).find(t => t.toLowerCase() === content);

	const mentionsMatch = answersMatch || content.indexOf('@slackbot') > -1;

	if(helloMatch){
		const a = global.hello.answers;
		message.reply(a[Math.floor(Math.random() * a.length)]);
		console.log(`Replied to hello ${content}`);
	} else if (answersMatch){
		message.reply(global.answers[answersMatch]);
		console.log(`Replied to answers ${content}`);
	} else if(mentionsMatch) {
		const m = global.mentions;
		message.reply(m[Math.floor(Math.random() * m.length)]);
		console.log(`Replied to mention ${content}`);
	} else {
		console.log(`Nothing matches "${content}"`);
	}

});

bot.login(process.env.TOKEN);
<|endoftext|>