無意間在找尋題材的時候看到這個 API 其實蠻有感的:居住在中部,這兩年明顯感受到空氣相當的混濁,除了出門常被叮嚀要戴口罩,家裡也買了空氣清淨機,雖然到最後吸入空氣的有沒有問題,其實我也搞不清楚,但多一分提醒、多一分防護總是好的,所以很臨時地把這篇加入系列文章。
Step 1. 前往政府資料開放平台 - 細懸浮微粒資料(PM2.5) - https://data.gov.tw/dataset/34827
Step 2. 不免俗的,複製資料來源網址進行測試
Step 3. 開啟 postman 來試試看 (似乎有點久):
Step 1. 將下方資料貼在 json2csharp (http://json2csharp.com/) 上進行類別轉換。
註:若您沒安裝 restsharp,請參考上一篇 應用: 自用氣象資訊機器人 - 程式章節
Step 2. 修改程式碼如下:
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using RestSharp;
using System.Collections.Generic;
namespace PMBotApplication.Dialogs
{
[Serializable]
public class RootDialog : IDialog<object>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
await context.PostAsync($"You sent {activity.Text} which was {length} characters");
context.Wait(MessageReceivedAsync);
}
public class RootObject
{
public string Site { get; set; }
public string county { get; set; }
public string PM25 { get; set; }
public string DataCreationDate { get; set; }
public string ItemUnit { get; set; }
}
}
}
Step 3. 將MessageReceivedAsync方法更改如下
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
if (activity.Text.IndexOf("空氣品質") >= 0 || activity.Text.IndexOf("PM2.5") >= 0)
{
var client = new RestClient("http://opendata.epa.gov.tw");
var request = new RestRequest("ws/Data/ATM00625/?$format=json", Method.GET);
var response = await client.ExecuteTaskAsync<List<RootObject>>(request);
Dictionary<string, RootObject> dictionary = response.Data.ToDictionary(x => x.Site);
await context.PostAsync($"{dictionary["西屯"].DataCreationDate} - 西屯 PM2.5 = {dictionary["西屯"].PM25} {dictionary["西屯"].ItemUnit}");
}
context.Wait(MessageReceivedAsync);
}
Step 4. 開啟機器人模擬進行測試。
其實程式部分還有很多地方可以強化,這邊就先提供可以運作的程式提供參考。
https://github.com/matsurigoto/BotFrameworkExample03