Skip to content
This repository has been archived by the owner on Sep 20, 2024. It is now read-only.

Conversation not waiting for the response #556

Closed
pkvenu opened this issue Dec 15, 2016 · 1 comment
Closed

Conversation not waiting for the response #556

pkvenu opened this issue Dec 15, 2016 · 1 comment

Comments

@pkvenu
Copy link

pkvenu commented Dec 15, 2016

Hi All,

Botkit Version : 0.4.1
I am having some issues with conversations. I am trying to run the "pizzatime" example. When I run them, the bot does not wait for my input and display all the next step one after the other

Output:
pizzatime
What flavor of pizza do you want?
Awesome.
What size do you want?
Ok.
So where do you want it delivered?
Ok! Goodbye.

glip_bot.js:
`

"use strict";

var Botkit = require('./lib/Botkit.js');
var os = require('os');
var http = require('http');
var request = require('request');

var controller = Botkit.glipbot({
    debug: false,
});

var bot = controller.spawn({
    server: process.env.HOST,
    appKey: process.env.APP_KEY,
    appSecret: process.env.APP_SECRET,
    appName: 'GlipDemo',
    appVersion: '0.1',
    username: process.env.USERNAME,
    password: process.env.PASSWORD,
    extension: process.env.EXTENSION
}).startRTM();

controller.setupWebserver(process.env.port || 3000, function(err, webserver){
    webserver.get('/', function (req ,res) {
        res.send(':)');
    });

    controller.createWebhookEndpoints(webserver, bot);

});


// Usage: uptime
controller.hears(['uptime'],'message_received',function(bot, message) {
    console.log('uptime in glipbot.js file: ' + JSON.stringify(message));
    var hostname = os.hostname();
    var uptime = formatUptime(process.uptime());
    bot.reply(message,'I am a bot! I have been running for ' + uptime + ' on ' + hostname + '.');
});

// Usage: question me
controller.hears(['question me'], 'message_received', function(bot,message) {

    // start a conversation to handle this response.
    bot.startConversation(message,function(err,convo) {

        convo.ask('Shall we proceed Say YES, NO or DONE to quit.',[
            {
                pattern: 'done',
                callback: function(response,convo) {
                    convo.say('OK you are done!');
                    convo.next();
                }
            },
            {
                pattern: bot.utterances.yes,
                callback: function(response,convo) {
                    convo.say('Great! I will continue...');
                    // do something else...
                    convo.next();

                }
            },
            {
                pattern: bot.utterances.no,
                callback: function(response,convo) {
                    convo.say('Perhaps later.');
                    // do something else...
                    convo.next();
                }
            },
            {
                default: true,
                callback: function(response,convo) {
                    // just repeat the question
                    convo.repeat();
                    convo.next();
                }
            }
        ]);

    })

});

//usage: pizzatime
controller.hears(['pizzatime'],'message_received',function(bot,message) {
    bot.startConversation(message, askFlavor);
});

var askFlavor = function(response, convo) {
    convo.ask("What flavor of pizza do you want?", function(response, convo) {
        convo.say("Awesome.");
        askSize(response, convo);
        convo.next();
    });
}
var askSize = function(response, convo) {
    convo.ask("What size do you want?", function(response, convo) {
        convo.say("Ok.")
        askWhereDeliver(response, convo);
        convo.next();
    });
}
var askWhereDeliver = function(response, convo) {
    convo.ask("So where do you want it delivered?", function(response, convo) {
        convo.say("Ok! Goodbye.");
        convo.next();
    });
}




function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}

Glipbot.js - custom bot similar to slack

/**
 * Created by pawan.venugopal on 10/17/16.
 */

"use strict";

var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var GlipClient = require('glip-client');
var async = require('async');



function Glipbot(configuration) {

    //Create a core botkit bot
    var glip_botkit = Botkit(configuration || {});

    glip_botkit.defineBot(function (botkit, config) {
        var bot = {
            type: 'glip',
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances
        };

      

        bot.startConversation = function (message, cb) {
            botkit.startConversation(this, message, cb);
        };




        bot.send = function (message, cb) {
            console.log("Send Method : " + JSON.stringify(message));
            bot.api.post(message.channel, message.text);
        };

        bot.reply = function(src, resp, cb) {
            console.log("Reply Method : " + JSON.stringify(src));
            var msg ={};
            if(typeof(resp) == 'string'){
                msg.text = resp;
            }else {
                msg =resp;
            }
            //msg.user = src.user;
            msg.channel = src.channel;

            bot.say(msg, cb);
        };




        /**
         * This handles the particulars of finding an existing conversation or
         * topic to fit the message into...
         */
        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            console.log('Find Conversation', JSON.stringify(message));
            //if(message.type == 'message' || message.type == 'slash_command' || message.type == 'direct_mention') {
            //if(message.messageType == 'PostAdded' || message.messageType == 'PostChanged') {
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                        botkit.tasks[t].convos[c].isActive() &&
                        botkit.tasks[t].convos[c].source_message.user == message.user &&
                        botkit.tasks[t].convos[c].source_message.channel == message.channel
                    ) {
                        console.log('FOUND EXISTING CONVO!');
                        if(message.text){
                            message.text = message.text.trim();
                        }
                        cb(botkit.tasks[t].convos[c]);
                        return ;
                    }
                }
            }
            //}

            cb();
        };



        var glipClient = new GlipClient({
            server: config.server,
            appKey: config.appKey,
            appSecret: config.appSecret,
            appName: config.appName,
            appVersion: config.appVersion
        });

        bot.client = glipClient;

        bot.api = bot.client;

        bot.startRTM = function(cb) {
            var message = null;
            bot.api.login({
                username: config.username,
                password: config.password,
                extension: config.extension
            }).then(function(response){
                console.log('logged in' + JSON.stringify(response));
                bot.api.listen(function(data){
                    console.log("RTM: " + JSON.stringify(data));

                    try{
                        message = {
                            channel: data.groupId,
                            text: data.text,
                            user: data.creatorId,
                            type: 'message'
                        }
                    } catch (err){
                        console.log('** Received Bad JSON **');
                    }

                    if(message != null){
                        botkit.receiveMessage(bot, message)
                    }
                });
            });

        };

        return bot;

    });

    glip_botkit.setupWebserver = function(port, cb){
        if(!port) {
            throw new Error('Cannot start webserver without a port');
        }

        if (isNaN(port)) {
            throw new Error('Specified port is not a valid number');
        }

        glip_botkit.config.port = port;
        glip_botkit.webserver = express();
        glip_botkit.webserver.use(bodyParser.json());
        glip_botkit.webserver.use(bodyParser.urlencoded({ extended: true }));
        glip_botkit.webserver.use(express.static(__dirname + '/public'));


        var server = glip_botkit.webserver.listen(
            glip_botkit.config.port,
            function() {
                glip_botkit.log('** Starting webserver on port ' +
                    glip_botkit.config.port);
                if (cb) { cb(null, glip_botkit.webserver); }
            });


        return glip_botkit;
    };


    glip_botkit.createWebhookEndpoints = function(webserver, bot){

        glip_botkit.log('** Serving Webhooks endpoint for receiving messages ** ' +
            'webhooks at: http://localhost:' + glip_botkit.config.port + '/glip/receive');


        webserver.post('/glip/receive', function(req,res){

            console.log('In webhook endpoints');
            console.log(JSON.stringify(req.body));

            if(req.body.command){
                var message = {};

                for (var key in req.body){
                    message[key] = req.body[key];
                }

                console.log(message);
            }
        });


        glip_botkit.startTicking();

        return glip_botkit;
    };

    glip_botkit.handelGlipEvents = function(){

        glip_botkit.log('** Setting up custom handlers for processing Glip messages');

        console.log("In Message received");
        glip_botkit.on('message_received', function(bot, message) {

            if('message' == message.type){
                if(message.text){
                    message.text = message.text.trim();
                }
            } else if('direct_mention' == message.type) {
                message.text = message.text.split('</a>')[1].trim();
            }

            // glip_botkit.trigger(message.type, [bot, message]);

            return ;

        });

    }

    glip_botkit.handelGlipEvents();

    return glip_botkit;

}




module.exports = Glipbot;

`

Please let me know what I am missing here. I have tried with the latest botkit version and when i say "pizzatime" I don't get any response back. I also tried the console logger in the latest version and the bot did not respond the the pizzatime command.

@benbrown
Copy link
Contributor

@pkvenu did we sort this out earlier for you?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants