3

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?

chan go
  • 137
  • 11

1 Answers1

7

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');

        });
    });
};
GitTristan
  • 96
  • 5
  • Awesome, Do you a repo or something like that to do so? – chan go Jun 16 '17 at 14:20
  • 1
    If you have a botkit running locally all you should have to do it create a new file in the `skills` directory. Name it anything, for example `clientCount.js`. The code above should just work after you `npm install --save request` – GitTristan Jun 17 '17 at 15:34
  • Has this answer answered your original question on how to call an external REST API and have botkit respond dynamically? – GitTristan Jun 19 '17 at 19:39
  • I have studio.botkit running. After creating my clientCoud.js my bot doesn't answer with the skill, the studio answer with default response. Any idea? – chan go Jun 26 '17 at 00:59
  • If you are using studio then I would look at `controller.studio.before()` in the [Howdy Docs](https://botkit.groovehq.com/knowledge_base/topics/botkit-studio-function-index). They enable you to run javascript functions before the studio script is run. This allows you to `convo.setVar('count', body.usersCount);` and pass them into your studio script. – GitTristan Jun 27 '17 at 02:58
  • Think the quickest way to get there is to have the [Slack Starter Kit](https://github.com/howdyai/botkit-starter-slack) running locally with ngrok. Adapt some code from the docs to set that before hook. Then look how to handle the vars you passed into the studio. Good luck. Botkit has an active [Slack Community](https://community.botkit.ai/) that can help with these types of things. If you ask good questions the community is very helpful. – GitTristan Jun 27 '17 at 02:59