We write our own bot in .NET Core. Part II: we create a sunny weather

In the previous part of the guide, we managed to create a bot from the command line that could easily answer Slack. However, these were only simple answers to our taunts.

In this part, we will try something more useful. We will teach our bot to find weather forecasts for us.

We create a new responder

To preserve the modular architecture of our solution, let's create a new responder to look for the weather. In this way, we will be able to decide whether to load it in a given instance of our bot or not.

We create a new responder just like SimpleResponder in the previous part: create a new class file. We can do it in any way. The easiest way to do this is in the Visual Studio Code:

  • Selecting the New File -> option and calling the new WeatherResponder.cs file
  • If we installed the Visual Studio Code plug-in called C # Extensions, we can immediately create a predefined class:

The result of the activity should be such a class:

Let's add two lines at the beginning of the file:

using System ;

using MargieBot ;

Next, NotImplementedException implement the interface, so far throwing only the NotImplementedException exception. Visual Studio Code will do it for us when we click the "bulb" icon and choose the option Implement Interface .

We gain access to weather data

It's time to take care of the weather data source. For this purpose, we will go to the OpenWeatherMap API website, where we can get access to the API that provides weather data for free.

To this end, we register as a free user. Select the "Current weather data" option and click "Subscribe". Then click "Get API key and Start" in the "Free" column. After completing the account creation in the "API Keys" section, we will have access to our key. Let's copy it to use later when creating our WeatherResponder object.

First, however, we will test the operation of the key. Enter the following address in your browser:

http://api.openweathermap.org/data/2.5/weather?q=Szczecin&mode=json&units=metric&APPID=<TUTAJ PODAJEMY SWOJ KLUCZ API>

We should see JSON (a typical format of data transmission in the network) containing information about the current weather in Szczecin.

Let's take a look at the address we have entered and let's break it down into the first few factors:

  • After q = we give the name of the city you want to search
  • After mode = we give the mode of data returned - we will use the json value here
  • After units = we give the type of data returned. Metric means that we are interested in metric units, i.e. expressed in degrees Celsius (many countries use Fahrenheit degrees).
  • In the APPID = section, we provide our application key, so you do not have to log in to the service in any other way.

The received JSON will look something like this:

Unformatted JSON looks quite illegible. However, Visual Studio Code is a great tool to look at it in a nicer form. Let's copy the whole to the new Visual Studio Code window and press Shift-Alt-F (or Shift-Option-F on the Mac).

Immediately, better, let us take a moment to look at what weather data (and not only), we are asked by OpenWeatherMap.

The format of this data will always be the same: only the values ​​will change. We call this type of contract a contract - there is a contract that the endpoint API will return the values ​​in a specific form.

It's time to call OpenWeatherMap from our bot

We must now modify our responder so that:

  • found in our message the name of the city in which we want to know the weather,
  • called OpenWeatherMap with the appropriate URL and read the returned JSON,
  • decoded the text returned in JSON to learn about specific weather data,
  • He formulated the answer and sent it to Slack.

Get to work. We must do the same work as the browser did by opening the given URL and downloading the data.

At the beginning, let's plan the constructor of our class so that we have to give him the API key. Why? Thanks to this, we will be able to use this class in different environments without revealing our key.

Then we will implement the CanRespond method. We will check in it if the word "weather" appeared in it. Then we'll assume that the rest is the name of the city. So the exemplary calls of our bot are: "weather Szczecin", "weather Warsaw" etc. This is a big simplification, but we want a quick effect here.

 public bool CanRespond(ResponseContext context) { return context.Message.Text.ToLower().Contains("pogoda"); } 

Now we must formulate the answer. This will be done in the GetResponse method, in the same way as in SimpleResponder.

 BotMessage response = new BotMessage(); string city = context.Message.Text.Replace("pogoda ", ""); string url = $"http://api.openweathermap.org/data/2.5/weather?q={city}&mode=json&units=metric&APPID={ApiKey}"; response.Text = "Szukales pogody w miescie: " + city; string pogoda = String.Empty; using (HttpClient client = new HttpClient()) { string json = RetrieveJsonAsync(url, client).Result; dynamic jsonData = JObject.Parse(json); pogoda = $"Temperatura w tym mieście to {jsonData.main.temp} stopni Celsjusza"; } response.Text = response.Text + Environment.NewLine + pogoda; return response; 

The compilation attempt will indicate errors. We do not have any packages with:

  • HttpClient - an object for downloading data from the network,
  • RetrieveJsonAsync methods, which will help us "wait" for asynchronous downloads,
  • Object JObject, used to load and analyze JSON data, located in the well-known open source package Newtonsoft.

We will fix the first problem by adding in using using System.Net.Http ;

The second problem - by defining the method needed:

 private async Task<string> RetrieveJsonAsync(string url, HttpClient client) { string result = await client.GetStringAsync(url); return result; } 

We add using System.Threading.Tasks ; in the using section.

The third problem will allow us to fix the Visual Studio Code. Next to the error in the line with JObject is the light bulb icon - we choose to add using Newtonsoft.Json.Linq; to the using section.

Now we have to add our responder when starting the bot, giving him the application key from OpenWeatherMap. For this purpose, we add a line by Console.Read() :

myBot.Responders.Add(new WeatherResponder("<tutaj klucz API OpenWeather>")) ;

We run our bot and test it.

It works ... but soon we will notice that the bot is causing problems - when we enter the name of the city that it could not find, it throws out an error - which prevents further conversation. Improving it (eg using the try…catch…finally clause) I leave readers! We can also be tempted to inform the user that an error has occurred.

In the next part, we will try to use our chatbot for the function with which we associate artificial intelligence. We will connect to available AI services and use them in bot functionality.



We write our own bot in .NET Core. Part II: we create a sunny weather

Comments

Popular posts from this blog

What is VoLTE and how can you activate it on your Xiaomi

So you can check the battery status of your Xiaomi smartphone and how many cycles you have performed

How to exit the FASTBOOT mode of your Xiaomi if you have entered accidentally

Does your Xiaomi charge slowly or intermittently? So you can fix it

Problems with Android Auto and your Xiaomi? So you can fix it

If your Xiaomi disconnects only from the WiFi it may be because of that MIUI setting

How to change the font in MIUI and thus further customize your Xiaomi: so you can change the type, color and size of the letters of MIUI

What is the Safe Mode of your Xiaomi, what is it for and how can you activate it

Improve and amplify the volume of your Xiaomi and / or headphones with these simple adjustments

How to activate the second space if your Xiaomi does not have this option