LoginSignup
4
3

More than 3 years have passed since last update.

LINE BOTで位置情報を使って天気予報を取得する

Last updated at Posted at 2020-04-13

railsで位置情報で天気予報を取得できるBOTを作成したので、APIの搭載の仕方をご紹介します。今回はXML形式で取得した場合です。

LINEBOTの作り方はこちらを参照いたしました。
https://qiita.com/takashico/items/edb6050a8e54dd137148

apiはこちらから取得いたしました。
https://openweathermap.org/

apiの搭載はこちらの記事を参考にいたしました。
https://yoheikoga.github.io/2016/08/14/weather-in-the-area-now-on-by-gps-module/
http://tokin-kame.hatenablog.com/entry/2015/05/31/105245

ライブラリーを記載

controller.rb


  require 'line/bot'
  require 'open-uri'
  require 'kconv'
  require 'rexml/document'

XMLファイルから必要なものを取得

URLからXMLを取得しパースしていきます。
OpenWeatherMapは属性の中に必要な情報が記載されていたため、情報の取得に苦労しました。
API KEYは環境変数にセットしましょう。

controller.rb


# 省略
      when Line::Bot::Event::Message
        case event.type
        when Line::Bot::Event::MessageType::Location
      # LINEの位置情報から緯度経度を取得
          latitude = event.message['latitude']
          longitude = event.message['longitude']
          appId = "取得したAPI KEY"
          url= "http://api.openweathermap.org/data/2.5/forecast?lon=#{longitude}&lat=#{latitude}&APPID=#{appId}&units=metric&mode=xml"
         # XMLをパースしていく
          xml  = open( url ).read.toutf8
          doc = REXML::Document.new(xml)
          xpath = 'weatherdata/forecast/time[1]/'
          nowWearther = doc.elements[xpath + 'symbol'].attributes['name']
          nowTemp = doc.elements[xpath + 'temperature'].attributes['value']
          case nowWearther
     # 条件が一致した場合、メッセージを返す処理。絵文字も入れています。
          when /.*(clear sky|few clouds).*/
            push = "現在地の天気は晴れです\u{2600}\n\n現在の気温は#{nowTemp}℃です\u{1F321}"
          when /.*(scattered clouds|broken clouds|overcast clouds).*/
            push = "現在地の天気は曇りです\u{2601}\n\n現在の気温は#{nowTemp}℃です\u{1F321}"
          when /.*(rain|thunderstorm|drizzle).*/
            push = "現在地の天気は雨です\u{2614}\n\n現在の気温は#{nowTemp}℃です\u{1F321}"
          when /.*(snow).*/
            push = "現在地の天気は雪です\u{2744}\n\n現在の気温は#{nowTemp}℃です\u{1F321}"
          when /.*(fog|mist|Haze).*/
            push = "現在地では霧が発生しています\u{1F32B}\n\n現在の気温は#{nowTemp}℃です\u{1F321}"
          else
            push = "現在地では何かが発生していますが、\nご自身でお確かめください。\u{1F605}\n\n現在の気温は#{nowTemp}℃です\u{1F321}"
          end
      }
# 省略

最後に

OpenWeahterMapは降水確率がないので、簡易的な天気予報しか作れませんでした。もう少し精度の高い天気予報APIが欲しいですが、おそらく有料になってくると思います。
LINE BOTは一度形ができてしまえば、意外と簡単に作ることができました。
ぜひ、皆さんもオリジナルボット作り試してみてください。

4
3
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
4
3