昨天我們做了自動化寫入 Google Sheet,今天要來完成一個更實用的案例:
👉 每天自動抓取台灣氣象局的天氣資訊,並推送到 Discord。
台灣氣象局提供免費的開放資料 API,你需要先申請一個授權碼:
Authorization
金鑰例如要查詢 台中市 36 小時天氣預報:
https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=你的API_KEY&locationName=臺中市
07:30
GET
https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=你的API_KEY&locationName=臺中市
因為氣象局 API 資料層級比較深,我們先解析:
const location = $json["records"]["location"][0];
const city = location["locationName"];
const weather = location["weatherElement"].find(e => e.elementName === "Wx").time[0].parameter.parameterName;
const minT = location["weatherElement"].find(e => e.elementName === "MinT").time[0].parameter.parameterName;
const maxT = location["weatherElement"].find(e => e.elementName === "MaxT").time[0].parameter.parameterName;
return [
{
json: {
embeds: [
{
title: `🌤️ 今日天氣 - ${city}`,
description: weather,
color: 16776960, // 黃色
fields: [
{ name: "🌡️ 最低溫", value: `${minT} °C`, inline: true },
{ name: "🔥 最高溫", value: `${maxT} °C`, inline: true }
],
footer: { text: "資料來源:中央氣象局 CWA" },
timestamp: new Date().toISOString()
}
]
}
}
];
POST
JSON
每天早上,你的 Discord 頻道就會收到這樣的卡片通知:
今天我們完成了 每日天氣自動通知 Discord:
這樣,你的 Discord 就多了一個定時發送天氣通知的機器人 !