Build your own WeatherBot with Botframework + Openweathermap + Adaptive cards UI
Today world is now full swing in the evolution of artificial intelligence and chatbots are playing a vital roles in this areas. Due to rapidly increases the number of users of messaging app like FB messenger, WhatsApp, Skype, Telegram, Slack etc. Alone FB messenger has more than 1.2 billion monthly users.
Now time has come to develop a chatbot application to solve the social and business requirement. As per gartner forecasts that by 2020, over 85% of customer interactions will be handled without a human. However, the opportunities provided by chatbot systems go far beyond giving responses to customers’ inquiries. There is no wonder that size of the chatbot market is growing exponentially.
In this post, i’m going to build an interactive UI based weatherbot by using Microsoft Bot framework, Openweathermap API and adaptive cards.
The first interaction of chatbot is shows as below image with minimal content.
In this bot, user can type the city name to get the current weather status. The bot has to call Openweathermap API to get the current weather reports. then will update reports in Json template for showing the next interaction of it.
Before going to start build, we need some pre-setup for the project build.
Prerequisites
- .NET Core SDK version 2.1
- Visual Studio 2017/ visual studio code
- Bot Framework V4
- OpenWeathermap API
- Bot framework Emulator (testing)
- Adaptive cards for UI
Step 1:- Download the .NET Core SDK and install in your system.
after installed check the version of dotnet
# determine dotnet version
dotnet --version
Step 2:- OpenWeatherMap Account setup
if you want to play with APIs, OpenWeatherMap is a good place to start. They actually provide 11 different APIs all related to weather that you can access.
For this project, we are using the Free ‘Current Weather’ API. go to this link and sign up for an account.
Once signed in, select the API keys tab. Here you can Create a Key on the right-hand side of the page. Enter a name anything works and select Generate. Your API Key will appear on the left. Copy this key for later.
Now go to the API tab to know the details knowledge of API, and select API doc of the current weather data. and come to “By geographic coordinates” section, see once how API will show the data.
Step 3:- Create a project
Full code of this project is available in GitHub Repo
To try this sample
- Clone the repository
git clone https://github.com/zayedrais/WeatherBot.git
- In a terminal, navigate to
WeatherBot/Bots/WeatherBot.cs
- The bot first welcome interaction will be initiated on added new member of user method called OnMembersAddedAsync.
- Here using a Hero card for the welcome contents, the below highlighted code is for Hero card.
protected override async Task OnMembersAddedAsync
(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity>
turnContext, CancellationToken cancellationToken)
{
IConversationUpdateActivity iConversationUpdated = turnContext.Activity as IConversationUpdateActivity;foreach (var member in membersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
var card = new HeroCard
{
Title = "Welcome to WeatherBot",
Text = @"Type the city name for get the weather report",
Images = new List<CardImage>() { new CardImage(ImageToBase64(_images[0])) },
};
await turnContext.SendActivityAsync(MessageFactory.Attachment
(card.ToAttachment()), cancellationToken);
}
}
}
-After Welcome message, user can type the name of city for get the current weather reports.
-Then invoke the method as OnMessageActivityAsync. this method contents the current city name, which is type of user for weather.
- Just replaced the API key into OpenwetherMapAPI place.
- The following things are doing inside this method:-
- calling the weathermap API
- Select and update the image for template.
- Select and update the current data of Json template for UI.
- Send the updated Json template for showing the weather reports.
protected override async Task OnMessageActivityAsync(ITurnContext
<IMessageActivity> turnContext, CancellationToken
cancellationToken){
var client = new OpenWeatherMapClient("OpenwetherMapAPI");
var CloudImage = "http://messagecardplayground.azurewebsites.net/assets/Mostly%20Cloudy-Square.png";var DizzleImage = "http://messagecardplayground.azurewebsites.net/assets/Drizzle-Square.png";var rainImage = "https://raw.githubusercontent.com/zayedrais/WeatherBot/master/Resources/rain.png";var stormImage = "https://raw.githubusercontent.com/zayedrais/WeatherBot/master/Resources/storm.png";var sunImage = "https://raw.githubusercontent.com/zayedrais/WeatherBot/master/Resources/sun.png";var currentWeather = await client.CurrentWeather.GetByName(turnContext.Activity.Text);var search =await client.Search.GetByName("Chennai");var forcast = await client.Forecast.GetByName("Chennai");var curtTemp = currentWeather.Temperature.Value - 273.15;var MaxTemp = currentWeather.Temperature.Max -273.15;var MinTemp = currentWeather.Temperature.Min -273.15;var updateCard = readFileforUpdate_jobj(_cards[0]);JToken cityName = updateCard.SelectToken("body[0].text");JToken tdyDate = updateCard.SelectToken("body[1].text");JToken curTemp = updateCard.SelectToken("body[2].columns[1].items[0].text");JToken maxTem = updateCard.SelectToken("body[2].columns[3].items[0].text");JToken minTem = updateCard.SelectToken("body[2].columns[3].items[1].text");JToken weatherImageUrl = updateCard.SelectToken("body[2].columns[0].items[0].url");cityName.Replace(currentWeather.City.Name);curTemp.Replace(curtTemp.ToString("N0"));tdyDate.Replace(DateTime.Now.ToString("dddd, dd MMMM yyyy"));maxTem.Replace("Max" +" "+MaxTemp.ToString("N0"));minTem.Replace("Min" + " "+MinTemp.ToString("N0"));var n = currentWeather.Clouds.Name;if(n=="overcast clouds")
{
weatherImageUrl.Replace(rainImage);
}
else if (n.Contains("clouds"))
{
weatherImageUrl.Replace(CloudImage);
}
else if (n.Contains("sky"))
{
weatherImageUrl.Replace(sunImage);
}
else if (n.Contains("rain"))
{
weatherImageUrl.Replace(rainImage);
}
else if(n.Contains("storm") || n.Contains("thunder"))
{
weatherImageUrl.Replace(stormImage);
}
var updateWeatherTem = UpdateAdaptivecardAttachment(updateCard);await turnContext.SendActivityAsync(MessageFactory.Attachment
(updateWeatherTem), cancellationToken):
}
Run the project:-
- Run the bot from a terminal or from Visual Studio, choose option A or B.
- A) From a terminal
# run the bot
dotnet run
- B) Or from Visual Studio
- Launch Visual Studio
- File -> Open -> Project/Solution
- Navigate to
WeatherBot/Bots
folder - Select
WeatherBot.csproj
file - Press
F5
to run the project
Step 4:-Testing the bot using Bot Framework Emulator
Bot Framework Emulator is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
- Install the Bot Framework Emulator version 4.3.0 or greater from here
Connect to the bot using Bot Framework Emulator
- Launch Bot Framework Emulator
- File -> Open Bot
- Enter a Bot URL of
http://localhost:3978/api/messages
The final look like as below image:-
Full code of this project is available in GitHub Repo