Open Weather Map API를 통해 날씨 정보를 얻고 Mac의 알림 센터에 표시
7469 단어 OpenWeatherMapRuby
차리다
YOUR_API_KEY
gem install cool.io
gem install terminal-notifier
견본
weather_watcher.rbrequire '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
참고 문헌
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
Reference
이 문제에 관하여(Open Weather Map API를 통해 날씨 정보를 얻고 Mac의 알림 센터에 표시), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/kenrota/items/8d24469cc359fe71131b텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)