route.js 10.9 KB
const MongoClient = require('mongodb').MongoClient;
const SlackBot = require('slackbots');
const dbname =  'jokeapi';
const collec = 'jokes';
const url = 'mongodb://localhost:27017/';

exports.startbot = ()=>{
    // Get authorization to use the slackbot
    const bot = new SlackBot({
        token : "xoxb-582582124755-587875604934-YBMZlb18wIdKQIEpyIV2dORa",
        name : "Joker"
    });
    
    // Start the slackbot
    bot.on('start', () =>{
        const face = {
            icon_emoji: ':bowtie:'
        };
        //Figure out user's all current channels and send the starting message
        channel = bot.getChannels();
        channel.then((data)=>{
        channel_length = data.channels.length; 
        for(i=0; i< channel_length; ++i){
            bot.postMessageToChannel(data.channels[i].name, 'Have some fun with @Joker!\nFor commands write @joker --help'
        , face);
        }
        return data;
    })
    .then((data)=>{
        console.log('Sucessfully started app to all channels');
    })  
    });
    // Error Handler
    bot.on('error', (err) => console.log(err));

    //Message Handler
bot.on('message', (data) => {
    if(data.type !== 'message'){
        return;
    }
    status = data;
    message_recieved = 0;
    //If it's first input from the user, go through this loop to store the data of channel names and ids
    if(message_recieved == 0){
        channel_length;
        channel_names = [];
        channel_ids = []; 

        channel = bot.getChannels();
        channel.then((data)=>{
            channel_length = data.channels.length;
            for(i=0; i< channel_length; ++i){
                channel_names.push(data.channels[i].name);
                channel_ids.push(data.channels[i].id);
            }
            return data;
        })
        .then((result)=>{
           ++message_recieved;
           console.log("User Channel list: " + channel_names)
           for(i=0; i< channel_length; ++i){
            if(channel_ids[i] == status.channel)
                handleMessage(status.text, channel_names[i]);
        }
        })
    }
    console.log(status);

    //If it's not the first user input, goes through simple loop to shorten response time
    if(message_recieved > 0){
        for(i=0; i< channel_length; ++i){
            if(channel_ids[i] == status.channel)
                handleMessage(status.text, channel_names[i]);
        }
    }
    //handleMessage(data.text);
});


// Responding to Data
function handleMessage(message, current_channel){
    console.log(message);

//Handles message response depending on the user message
    if(message.includes(' tell me')){
        if(message.includes(' knock')){
            knockknockJoke(current_channel);
        }
        else if(message.includes(' general')){
            generalJoke(current_channel);
        }

        else if(message.includes(' random')){
            randomJoke(current_channel);
        }
        else if(message.includes(' a joke')){
            randomJoke(current_channel);
        }
    
        else if(message.includes(' programming')){
            programmingJoke(current_channel);
        }
        else if(message.includes(' me   ')){
            const quiet = {
                icon_emoji: ':no_mouth:'
            }
            bot.postMessageToChannel(current_channel, "Tell you what??? :no_mouth:", quiet);
        }
        else{
            const embarrased = {
                icon_emoji: ':flushed:'
            };
            comment = "Sorry I dont' have that kind of joke.....:droplet::droplet::droplet:\nPlease use @joker --help to know what I can do!";
            bot.postMessageToChannel(current_channel, comment, embarrased);

        }
        
    }
    else if(message.includes(' help')){
        
    }
    else if(message.includes(' what jokes')){
        jokeTypes = ["general", 'programming', 'knock-knock'];
        const face = {
            icon_emoji: ':thumbsup:'
        };
        bot.postMessageToChannel(current_channel, `I have ${jokeTypes[0]}, ${jokeTypes[1]}, ${jokeTypes[2]} jokes!! :thumbsup: :thumbsup:`, face);
        return;
    }
    // else{
    //     const embarrased = {
    //         icon_emoji: ':flushed:'
    //     };
    //     const sweat = {
    //         icon_emoji: ':droplet:'
    //     };
    //     comment = "Sorry I'm not smart enough to understand this.....\nPlease use @joker help to know what I can do!";
    //     bot.postMessageToChannel('everyone', comment, embarrased);
        
    // }
}

//Gets a random integer
function getRandomInt(max_num) {
    min = Math.ceil(1);
    max = Math.floor(max_num);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

//Function for giving out random joke
randomJoke= (user_channel)=>{
    MongoClient.connect('mongodb://localhost:27017', function (err, client){
    if (err) throw err; 
    var db = client.db('jokeapi');

    json_max = 376;
    random = getRandomInt(json_max);
    result = db.collection('jokes').findOne({id: random});   
    
    user = result;
    user.then(function(total){
        question = total.setup;
        const face = {
            icon_emoji: ':laughing:'
        };
        
        function firstFunction(){
            bot.postMessageToChannel(user_channel, question, face);
        }
        firstFunction('everyone');
        console.log('질문 불려짐');
        return total;


    })
    .then((all)=>{
        joke = all.punchline;
        const face = {
            icon_emoji: ':laughing:'
        };
        setTimeout(function secondFunction(){
           bot.postMessageToChannel(user_channel, `${joke}:stuck_out_tongue_winking_eye::laughing:`, face, '/play secret')
            console.log( "허무개그 전송~~~~!")
        }, 3000);
        
    })
    client.close();
    })
}

//Function for giving out random joke after filtering only general type jokes
generalJoke= (user_channel)=>{
    MongoClient.connect(url, function (err, client){
        if (err) throw err; 
        var db = client.db('jokeapi');
    
        json_max = 376;
        random = getRandomInt(json_max);
        result = db.collection('jokes').findOne({id: random});   
        user = result;
        user.then(function(total){
                if(total.type === "general"){
                    question = total.setup;
                    joke = total.punchline;
                    channel = 'everyone';
                    const face = {
                        icon_emoji: ':laughing:'
                    };
                    ques_and_joke = [question, joke, face, channel];
                    return ques_and_joke;
                }
                else if(total.type != "general"){
                    client.close();
                    generalJoke(user_channel);
                }
            
        })
        .then((joke_info)=>{
            function askQuestion(){
                bot.postMessageToChannel(user_channel, joke_info[0], joke_info[2]);
                console.log("일반 질문 불려짐");
            }
            askQuestion();
            return joke_info;
        })
        .then((info)=>{
            setTimeout(function secondFunction(){
                bot.postMessageToChannel(user_channel, `${info[1]}:stuck_out_tongue_winking_eye::laughing:`, info[2])
                 console.log( "허무개그 전송~~~~!")
             }, 3000);
        })
        client.close();
        })
    };

//Function for giving out random joke after filtering only programming type jokes
programmingJoke= (user_channel)=>{
        MongoClient.connect(url, function (err, client){
        if (err) throw err; 
        var db = client.db('jokeapi');
    
        json_max = 376;
        random = getRandomInt(json_max);
        result = db.collection('jokes').findOne({id: random});   
        user = result;
        user.then(function(total){
                if(total.type === "programming"){
                    question = total.setup;
                    joke = total.punchline;
                    channel = 'everyone';
                    const face = {
                        icon_emoji: ':laughing:'
                    };
                    ques_and_joke = [question, joke, face, channel];
                    return ques_and_joke;
                }
                else if(total.type != "programming"){
                    client.close();
                    programmingJoke(user_channel);
                }
            
        })
        .then((joke_info)=>{
            function askQuestion(){
                bot.postMessageToChannel(user_channel, joke_info[0], joke_info[2]);
                console.log("프로그래밍 질문 불려짐");
            }
            askQuestion();
            return joke_info;
        })
        .then((info)=>{
            setTimeout(function secondFunction(){
                bot.postMessageToChannel(user_channel, `${info[1]}:stuck_out_tongue_winking_eye::laughing:`, info[2])
                 console.log( "허무개그 전송~~~~!")
             }, 3000);
        })
        client.close();
        })
    };

//Function for giving out random joke after filtering only knock-knock type jokes
knockknockJoke= (user_channel)=>{
    MongoClient.connect(url, function (err, client){
        if (err) throw err; 
        var db = client.db('jokeapi');
    
        json_max = 61;
        
        random = getRandomInt(json_max);
        result = db.collection('jokes').findOne({id: random});   
        user = result;
        user.then(function(total){
                if(total.type === "knock-knock"){
                    question = total.setup;
                    joke = total.punchline;
                    channel = 'everyone';
                    const face = {
                        icon_emoji: ':laughing:'
                    };
                    ques_and_joke = [question, joke, face, channel];
                    return ques_and_joke;
                }
                else if(total.type != "knock-knock"){
                    client.close();
                    knockknockJoke(user_channel);
                }
            
        })
        .then((joke_info)=>{
            function askQuestion(){
                bot.postMessageToChannel(user_channel, joke_info[0], joke_info[2]);
                console.log("똑똑 질문 불려짐");
            }
            askQuestion();
            return joke_info;
        })
        .then((info)=>{
            setTimeout(function secondFunction(){
                bot.postMessageToChannel(user_channel, `${info[1]}:stuck_out_tongue_winking_eye::laughing:`, info[2])
                 console.log( "허무개그 전송~~~~!")
             }, 3000);
        })
        client.close();
        })
    }

//Function for giving out information to user to control the bot
runHelp = () =>{
    
    const face = {
        icon_emoji: ':question:'
    };
    comment = "Thanks for using Joker bot!:ghost::ghost:laugh:\nBot info: type '@joker --help'\nBot functions: @joker tell me [something] "
    bot.postMessageToChannel('everyone', "Type @joker and write a joke that you would like\n ex- @joker random",face);
    
    }
}