LoginSignup
4
2

More than 5 years have passed since last update.

OpenWeatherMap APIで天気情報を取得してMacの通知センターに表示する

Last updated at Posted at 2018-07-15

Cool.io::TimerWatcher、OpenWeatherMap API、terminal-notifierを使用して、指定した秒間隔で天気情報を取得し、Macの通知センターに表示するサンプルプログラムです。

weather_watcher_notification.png

準備

  • OpenWeatherMapのアカウント登録(Freeプランあり)とAPIキー取得
    • 下記サンプル内のYOUR_API_KEYに設定
  • gem install cool.io
  • gem install terminal-notifier

サンプル

weather_watcher.rb
require 'net/http'
require 'uri'
require 'json'
require 'cool.io'
require 'terminal-notifier'

class WeatherWatcher < Coolio::TimerWatcher
  API_KEY = 'YOUR_API_KEY'
  CITY_NAME = 'Tokyo'
  COUNTRY_CODE = 'JP'
  INTERVAL_SEC = 300

  def initialize
    super(INTERVAL_SEC, true)
  end

  def on_timer
    weather = get_weather
    icon_id = weather['weather'][0]['icon']
    temperature = weather['main']['temp']
    description = weather['weather'][0]['description']
    notify(icon_id, temperature, description)
  end

  def get_weather
    uri = URI('http://api.openweathermap.org')
    uri.path = '/data/2.5/weather'
    params = { q: "#{CITY_NAME},#{COUNTRY_CODE}", units: 'metric', appid: API_KEY }
    uri.query = URI.encode_www_form(params)
    response = Net::HTTP.get(uri)
    JSON.parse(response)
  end

  def notify(icon, temperature, description)
    TerminalNotifier.notify(
      "#{CITY_NAME}, #{COUNTRY_CODE}",
      title: "#{temperature}℃, #{description}",
      contentImage: "http://openweathermap.org/img/w/#{icon}.png"
    )
  end
end

def run
  loop = Coolio::Loop.new
  timer = WeatherWatcher.new
  loop.attach(timer)
  loop.run
ensure
  timer.detach
end

run

参考文献

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