Search code examples
javascriptrestbotkit

Connect botkit to my service restful api


I installed botkit locally and is working perfect with slack. Now, i want to connect the bot with an external restful api to ask for example:

HUMAN: How many clients do you have connected? Bot: The bot execute internally a query over the rest api of my service and then, answer Bot: There are 21 clients connected.

Any suggestion?


Solution

  • We do a similar operation and it's pretty simle. Use some sort or HTTP client to make a GET to your endpoint. We use the request npm. Then you just have to call the bot.reply in the callback. To kick off the interaction I'm using ambient to listen to any channel the bot is invited to, but you could set that to direct_message if that's how you roll.

    var request = require('request');
    
    module.exports = function(controller) {
        controller.hears(['How many clients'], 'ambient', function(bot, message) {
    
            request('http://api.com/totalUsers', function (err, response, body) {
    
                console.log('error: ', err); // Handle the error if one occurred
                console.log('statusCode: ', response && response.statusCode); // Check 200 or such
                console.log('This is the count of users: ', body.usersCount);
    
                bot.reply(message, 'There are ' + body.usersCount + ' clients connected');
    
            });
        });
    };