Skip to content

Instantly share code, notes, and snippets.

@yogthos
Last active March 24, 2024 10:35
Show Gist options
  • Save yogthos/f86e63b856e1413180b2262024ece977 to your computer and use it in GitHub Desktop.
Save yogthos/f86e63b856e1413180b2262024ece977 to your computer and use it in GitHub Desktop.
command line util for grabbing current weather for a city using OpenWeather API

usage

Create an account at https://openweathermap.org and get an API key. Note that it can take up to a couple of hours for the key to become active. Add an environment variable OPEN_WEATHER_API_KEY with the value of the key.

run the script:

./weather.clj Toronto,CA

🌆 City:	Old Toronto
📍 State:	Ontario
🌍 Country:	CA

🌡 Temperature:	5 °C
💁‍♀️ Feel like:	0 °C
🧊 Minimum:	4 °C
🔥 Maximum:	5 °C
🌊 Pressure:	1015 hPa
😰 Humitdity:	61 %

☁️ Cloudiness:		0 %
🌬 Wind Speed:		8.75 m/s
🧭 Wind Direction:	210 °
🌁 Visibility:		10000
#!/usr/bin/env bb
(ns weather
(:require
[cheshire.core :as cheshire]
[clojure.string :as string]
[org.httpkit.client :as http]))
(def app-id (System/getenv "OPEN_WEATHER_API_KEY"))
(def base-url "https://api.openweathermap.org")
(defn fetch-data
[path params]
(-> @(http/get (str base-url path)
{:query-params (assoc params :appid app-id)})
:body
(cheshire/decode true)))
(defn fetch-city
[city]
(first (fetch-data "/geo/1.0/direct" {:q city :limit 1})))
(defn fetch-weather
[city-info]
(fetch-data "/data/2.5/weather" (select-keys city-info [:lat :lon])))
(defn kelvin->celsius
[temp]
(int (- temp 273.15)))
(defn format-temp
[{:keys [temp feels_like temp_min temp_max pressure humidity]}]
(str
"\n🌡 Temperature:\t" (kelvin->celsius temp) " °C"
"\n💁‍♀️ Feel like:\t" (kelvin->celsius feels_like) " °C"
"\n🧊 Minimum:\t" (kelvin->celsius temp_min) " °C"
"\n🔥 Maximum:\t" (kelvin->celsius temp_max) " °C"
"\n🌊 Pressure:\t" pressure " hPa"
"\n😰 Humitdity:\t" humidity " %"))
(defn format-city
[{:keys [name country state]}]
(str
"\n🌆 City:\t" name
"\n📍 State:\t" state
"\n🌍 Country:\t" country))
(defn format-weather
[{:keys [wind clouds visibility]}]
(str
"\n☁️ Cloudiness:\t\t" (:all clouds) " %"
"\n🌬 Wind Speed:\t\t" (:speed wind) " m/s"
"\n🧭 Wind Direction:\t" (:deg wind) " °"
"\n🌁 Visibility:\t\t" visibility))
(defn print-weather
[city]
(let [city-info (fetch-city city)
{:keys [main] :as weather}
(fetch-weather city-info)]
(->> [(format-city city-info)
(format-temp main)
(format-weather weather)]
(string/join "\n")
(println))))
(when-not app-id
(println "missing OPEN_WEATHER_API_KEY environment variable")
(System/exit 1))
(print-weather (first *command-line-args*))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment