rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

google apps scriptで「天気予報」「この日の過去の出来事」付き見守りメール定期発信

2021 Jan. 23.

googleドライブのスプレッドシート -> ツール -> スクリプト・エディタ に下記のスクリプトを記述し、トリガーにセットする。

(メール送信スクリプト

function sendMimamori(){
  // 2017 Jan. 04.
  // 2016 Dec. 25.
  // Ryuichi Hashimoto.

  // 現在時刻を取得
  var now = Utilities.formatDate(new Date(), "JST", "yyyy-MM-dd hh:mm");
  
  // 電子メール送信する
  var toAddress = "TO@ADDRESS,TO2@ADDRESS2";
  var ccAddress = "CC@ADDRESS,CC2@ADDRESS2";
  var cityID = "330010";  // 地域ID
  // cityID List: https://weather.tsukumijima.net/primary_area.xml

  var mailTitle = 'お元気ですか?';
  var mailText = "元気ですか?\n何も書かなくてよいので[すべてへ返信]をして下さい。\n";
  mailText = mailText + now + "\n\n" + weatherForecast(cityID) + "\n" + wikipediaWhatIsToday(5);
  MailApp.sendEmail(toAddress,mailTitle,mailText, {cc:ccAddress});
}


(天気予報取得スクリプト

function weatherForecast(cityID) {  // cityID: 地域ID
  // 2021 Jan. 23.
  // 2016 Dec. 29.
  // Ryuichi Hashimoto.

  // cityID List: https://weather.tsukumijima.net/primary_area.xml
  // api url: https://weather.tsukumijima.net/api/forecast

  var response = UrlFetchApp.fetch("http://weather.tsukumijima.net/api/forecast/city/"+cityID); //ApiUrl+/city/+cityID
  var json=JSON.parse(response.getContentText());

  var forecastText = "";
  if (json["publicTime"]) {
    if (json["title"]) {
      forecastText = "(ご参考)\n"+json["title"]+"の天気 "+json["publicTime"].substring(0,16).replace("T"," ")+"発表\n"
      if (json["forecasts"][0]) {
        if (json["forecasts"][0]["telop"]) forecastText=forecastText+"今日の天気は "+json["forecasts"][0]["telop"]+"\n";
        if (json["forecasts"][0]["temperature"]["max"] ) forecastText=forecastText+"最高気温:"+json["forecasts"][0]["temperature"]["max"]["celsius"]+"度\n";
        if (json["forecasts"][0]["temperature"]["min"] ) forecastText=forecastText+"最低気温:"+json["forecasts"][0]["temperature"]["min"]["celsius"]+"度\n";
        forecastText=forecastText+"\n";
      }
      if (json["forecasts"][1]) {
        if (json["forecasts"][1]["telop"]) forecastText=forecastText+"明日の天気は "+json["forecasts"][1]["telop"]+"\n";
        if (json["forecasts"][1]["temperature"]["max"] ) forecastText=forecastText+"最高気温:"+json["forecasts"][1]["temperature"]["max"]["celsius"]+"度\n";
        if (json["forecasts"][1]["temperature"]["min"] ) forecastText=forecastText+"最低気温:"+json["forecasts"][1]["temperature"]["min"]["celsius"]+"度\n\n";
      }
      if (json["description"]["text"]) forecastText=forecastText+json["description"]["text"]+"\n";
    }
  }
  return forecastText;
}


wikipediaから今日の月日の過去の出来事を取得するスクリプト

function wikipediaWhatIsToday(countArticle) {  // countArticle: 取得する記事数
  // 2016 Jan. 04.
  // Ryuichi Hashimoto.


  var now = new Date();
  var month = now.getMonth()+1;
  var day = now.getDate();
  var monthDay = month+"月"+day+"日 ";
  
  var url = 'https://ja.wikipedia.org/w/api.php?format=json&utf8&action=query&prop=revisions&rvprop=content&titles=';
  url = url + monthDay;
  var response = UrlFetchApp.fetch(url);
  var json = response.getContentText();
  var data = JSON.parse(json);

  // get the page IDs
  var pageid = [];
  for( var id in data.query.pages ) {
    pageid.push( id );
  }

  // 記事本文を取得  
  var content = data.query.pages[ pageid[0] ].revisions[0]["*"];
    // 次の区切り・順番で記事が並んでいる
    //   == できごと ==
    //   == 誕生日 ==
    //   == 忌日 ==
    //   == 記念日・年中行事 ==
    //   == フィクションのできごと ==
    //   == 誕生日(フィクション) ===
    //   == 出典 ==
    //   == 関連項目 ==
  
  // 「できごと」を取り出す
  var dekigoto = content.match(/== できごと ==[\s\S]*== 誕生日 ==/);
  
  // アスタリスクで始まり改行文字で終わる文字列を取り出す
  article = dekigoto[0].match(/\*.+\n/g);
  
  // countArticleの個数の記事を取り出す
  var numberArticle = [];
  while (true) {
    var rand = Math.floor( Math.random() * article.length) ;
    numberArticle.push(rand);
    numberArticle = numberArticle.filter(function (x, i, self) {
            return self.indexOf(x) === i;
        })
    if (numberArticle.length == countArticle ) {
      break; 
    }
  }

  var outputText = monthDay + "のできごと\n";
  numberArticle.forEach(function(numLine) {
    outputText = outputText + article[numLine] + "\n";
  });
  return outputText;
}