slack_bot_weatherIn this tutorial, we will build a slack bot which will tell you weather of any given city. For this, we need to setup a chatbot similar to the hello world bot that we built in our previous article and add weather capability via some open APIi for weather.

How to build a weather bot in Slack?

Step 1: Get weather API

  1. Get weather API key from https://openweathermap.org/api.  We can make 60 calls in a minute with free account which is enough for us.
  2. We will be using current weather data by city api shown here https://openweathermap.org/current.
end point: https://api.openweathermap.org/data/2.5/weather?q=<your_city>&appid=<your_api_key> 

method: GET
Response:

{
coord: {
lon: 77.22,
lat: 28.67
},
weather: [
{
id: 721,
main: "Haze",
description: "haze",
icon: "50d"
}
],
base: "cmc stations",
main: {
temp: 297.15,
pressure: 1007,
humidity: 44,
temp_min: 297.15,
temp_max: 297.15
},
wind: {
speed: 0.32,
deg: 81.5026
},
clouds: {
all: 20
},
dt: 1461717000,
sys: {
type: 1,
id: 7809,
message: 0.0029,
country: "IN",
sunrise: 1461716017,
sunset: 1461763453
},
id: 1273294,
name: "Delhi",
cod: 200
}

Step 2: Add weather feature to your chatbot

  1. Open hello world slack bot code and add a new hears()  function to listen the weather message from user.
    controller.hears(['weather in (.*)', '(.*) weather'], 'direct_message,direct_mention,mention', function(bot,message) {
        var city = message.match[1];
    }

    Here, we are using regex match in received message to get the city name. As you can see, we have two alternative message formats. weather in (.*) will look for e.g. “weather in Bangalore” and (.*) weather will look for “Bangalore weather”.

  2. Call weather API, get weather info and reply back to user. Don’t forget to enter your API key.
    controller.hears(['weather in (.*)', '(.*) weather'], 'direct_message,direct_mention,mention', function(bot,message) {
        var city = message.match[1];
        console.log("city: "+city);
        if(undefined === city || '' === city || null === city)
        {
            bot.reply(message,"Are't you forgot the city name? I am really sorry, currently I can't guess your city.");
        }
        else{
            var options = {
                protocol : 'http:',
                host : 'api.openweathermap.org',
                path : '/data/2.5/weather?q='+city+'&appid=<your_api_key>',
                port : 80,
                method : 'GET'
              }
    
            var request = http.request(options, function(response){
                var body = "";
                response.on('data', function(data) {
                    body += data;
                    weather = JSON.parse(body);
                    console.log("weather :" + weather.weather[0].main);
                    bot.reply(message, "Its " + weather.weather[0].main + " in " + city);
                    var reaction = "";
                    switch(weather.weather[0].main)
                    {
                            case "Clear":
                                    reaction = "mostly_sunny";
                                    bot.reply(message,":"+reaction+":");
                                    bot.reply(message,"Its good idea to wear sunglasses before going out");
                                    break;
                            case "Clouds":
                            case "Cloud":
                                    reaction = "cloud";
                                    bot.reply(message,":"+reaction+":");
                                    break;
                            case "Smoke":
                                    reaction = "smoking";
                                    bot.reply(message,":"+reaction+":");
                                    break;
                            case "Rain":
                                    reaction = "rain_cloud";
                                    bot.reply(message,":"+reaction+":");
                                    bot.reply(message,"Please carry umbrella if you are in " + city);
                                    break;
                            case "Thunderstorm":
                                    reaction = "thunder_cloud_and_rain";
                                    bot.reply(message,":"+reaction+":");
                                    bot.reply(message,"Please don't go out if you are in " + city);
                                    break;
                    }
                    bot.api.reactions.add({
                        timestamp: message.ts,
                        channel: message.channel,
                        name: reaction,
                    }, function(err, res) {
                        if (err) {
                            bot.botkit.log('Failed to add emoji reaction :(', err);
                        }
                    });
                });
                response.on('end', function() {
                  /*res.send(JSON.parse(body));*/
                });
              });
              request.on('error', function(e) {
                console.log('Problem with request: ' + e.message);
                bot.reply(message, "sorry, couldn't find weather info for city " + city);
              });
              request.end();
      }
    })

    Your slack weather bot is ready. Let’s see it working. Run node weather_salck_bot.js

weather bot

So, you can make a weather bot for Slack very easily. If you wish to explore latest bots for different platforms, or submit your own bot, don’t forget to check out BotArena — the world’s most informative bot store.

Recommended: How To Build A Slack Chatbot In Node.js Using Botkit