天気予報をLINEbotに通知するGASスクリプト!

天気予報をLINEbotに通知するGASスクリプトを書きました。

// LINE Message API チャネルアクセストークン
const LINE_ACCESS_TOKEN = "【Channel access token (long-lived)を記載】";
//ユーザーIDを指定
const LINE_USER_ID = "【Your user IDを記載】";
// 通知用のLINE API
const PUSH_API = "https://api.line.me/v2/bot/message/push";

const WEATHER_APP_ID = "【openweatherIDを記載】";
const LAT = 34.672314;
const LON = 135.484802;
// 天気予報情報取得API;
const WEWATHER_API = `https://api.openweathermap.org/data/2.5/onecall?lat=${LAT}&lon=${LON}&units=metric&lang=ja&appid=${WEATHER_APP_ID}`
Logger.log(WEWATHER_API);



/** 
 * push
 * botからメッセージを送る
 */
function doPost() {

  const date = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy/MM/dd HH:mm');
  Logger.log(date);

  // リクエストヘッダ
  const headers = {
    "Content-Type" : "application/json; charset=UTF-8",
    "Authorization" : "Bearer " + LINE_ACCESS_TOKEN
  };
  // メッセージ
  let weatherInfo = getWeather();
  const postData = {
    "to" : LINE_USER_ID, 
    "messages" : [
      {
        "type" : "text",
        "text" : `現在の大阪の日時とお天気をお伝えします🐻時刻: ${ weatherInfo.datetime }, 天気: ${ weatherInfo.weather }, 気温: ${ weatherInfo.temp }, 湿度: ${ weatherInfo.humidity }☀君の心はいつも晴れ☀いってらっしゃーい🐻`
      }
    ]
  };
Logger.log(postData);

  // POSTオプション作成
  const options = {
    "method" : "POST",
    "headers" : headers,
    "payload" : JSON.stringify(postData)
  };
  return UrlFetchApp.fetch(PUSH_API, options);
}


function unixtimeToDatetime(unixtime) {
  const date = new Date(unixtime * 1000);
  return Utilities.formatDate(date, 'Asia/Tokyo', 'YY/MM/dd HH:mm');
}

function getWeather() {
  // @ts-ignore
  let res = JSON.parse(UrlFetchApp.fetch(WEWATHER_API));
  let current = res.current;

  let unixtime = unixtimeToDatetime(Number(current.dt));

  weatherInfo = {
    "datetime": unixtime,
    "weather": current.weather[0].description,
    "icon": current.weather[0].icon,
    "temp": Math.round(current.temp),
    "humidity": current.humidity
  };
  return weatherInfo;
}

コメント