LoginSignup
1
1

More than 1 year has passed since last update.

Twilio Functionsを使って、現在の天気を取得する

Last updated at Posted at 2018-05-20

2023年5月1日を持ちまして、株式会社KDDIウェブコミュニケーションズのTwilioリセール事業が終了したため、本記事に記載されている内容は正確ではないことを予めご了承ください。

はじめに

ハッカソンイベントなどでは、ときどき天気を取得したいときがあります。
天気を取得するためのAPIはいくつかありますが、今回はOpenWeatherMapというサービスを利用して、Twilio Functionsから天気を取得するコードを紹介します。

準備

OpenWeatherMapに移動し、サインアップページからアカウントを作成します。サインアップは無料です。

サインアップが完了したら、API keysタブに移動し、Keyの値をメモ帳に記録します。
OpenWeatherMap.png

Functionsの作成

  • Twilioの管理コンソールにログインします。
  • RuntimeメニューのFunctionsを選択し、さらにManageを選びます。
  • 新しくFunctionを作成します。テンプレートはBlankで構いません。
  • FUNCTION NAMEPATH欄は適当に入力します。
  • ACCESS CONTROLのチェックボックスは外しておきます。
  • CODE欄に以下のコードを貼り付けます。
Function
const https = require('https');

exports.handler = function(context, event, callback) {
    const HOST = 'api.openweathermap.org/data/2.5/weather';
    const CITY = 'Tokyo';
    const APPID = 'ここにOpenWeatherMapのAPP Keyを貼り付けます';

    let result = {};
    const req = https.request(`https://${HOST}?q=${CITY}&APPID=${APPID}`, (res) => {
        res.on('data', (chunk) => {
            result = JSON.parse(chunk);
        });
        res.on('end', () => {
            console.log(`${CITY} is a ${result.weather[0].description}.`);
            callback(null, result);
        });
    });

    req.on('error', (e) => {
      console.error(`problem with request: ${e.message}`);
      callback(e.message);
    });

    req.end();

};
  • 6行目に先程控えておいたKeyを書き込みます。
  • SAVEボタンを押して、Functionを保存します。
  • デプロイが完了した旨のメッセージが表示されたら、PATH欄のURLをコピーして、ブラウザで実行してみます。
  • Functionの画面には、以下のようなメッセージが表示されれば成功です。
スクリーンショット 2018-05-20 21.37.49.png

ちなみに、天気データの詳細はこちらのページを参照してください。

このFunction自体は、以下のような天気データをJSON形式で返しますので、たとえばTwilio StudioなどでこのFunctionを呼び出し、必要なデータだけを取得することもできます。

JSON
{"coord":{"lon":139.76,"lat":35.68},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":288.45,"pressure":1020,"humidity":51,"temp_min":286.15,"temp_max":290.15},"visibility":10000,"wind":{"speed":4.1,"deg":160},"clouds":{"all":75},"dt":1526817600,"sys":{"type":1,"id":7619,"message":0.0045,"country":"JP","sunrise":1526758342,"sunset":1526809383},"id":1850147,"name":"Tokyo","cod":200}

Happy Hacking!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1