// vi:ts=4:sts=4:sw=4:noet:tw=72 // // flokatirc weather module // // Copyright (c) 2016 Daniel Aberger package weather import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strconv" "strings" "github.com/sorcix/irc" ) var ( sayCh chan string owmQueryAPIKey = "" owmQueryURLPrefix = "http://api.openweathermap.org/data/2.5/weather?q=" owmQueryURLSuffix = "&appid=" weatherPrefix = "[WTHR] " ) type WeatherObject struct { Base string `json:"base"` Clouds struct { All int `json:"all"` } `json:"clouds"` Cod int `json:"cod"` Coord struct { Lat float64 `json:"lat"` Lon float64 `json:"lon"` } `json:"coord"` Dt int `json:"dt"` ID int `json:"id"` Main struct { GrndLevel float64 `json:"grnd_level"` Humidity int `json:"humidity"` Pressure float64 `json:"pressure"` SeaLevel float64 `json:"sea_level"` Temp float64 `json:"temp"` TempMax float64 `json:"temp_max"` TempMin float64 `json:"temp_min"` } `json:"main"` Name string `json:"name"` Rain struct { ThreeH float64 `json:"3h"` } `json:"rain"` Sys struct { Country string `json:"country"` Message float64 `json:"message"` Sunrise int `json:"sunrise"` Sunset int `json:"sunset"` } `json:"sys"` Weather []struct { Description string `json:"description"` Icon string `json:"icon"` ID int `json:"id"` Main string `json:"main"` } `json:"weather"` Wind struct { Deg float64 `json:"deg"` Speed float64 `json:"speed"` } `json:"wind"` } func Init(ch chan string) { log.Println("Initializing weather module") sayCh = ch } func HandleMessage(m *irc.Message) { tok := strings.Split(m.Trailing, " ") if len(tok) < 1 { return } switch tok[0] { case "!w": switch len(tok) { case 1: sayCh <- fmt.Sprintf("*\n%s", weatherPrefix+"Usage: !w ") default: if strings.Compare(owmQueryAPIKey, "") == 0 { sayCh <- fmt.Sprintf("*\n%s", weatherPrefix+"No API Key set.") } else { go getWeather(strings.Join(tok[1:], " ")) } } default: } } func getWeather(query string) { q := owmQueryURLPrefix + query + owmQueryURLSuffix + owmQueryAPIKey r, err := http.Get(q) if err != nil { log.Println(err) sayCh <- fmt.Sprintf("*\n%s", weatherPrefix+err.Error()) } else { re, err := ioutil.ReadAll(r.Body) if err != nil { log.Println(err) sayCh <- fmt.Sprintf("*\n%s", weatherPrefix+err.Error()) } else { defer r.Body.Close() var wo WeatherObject err := json.Unmarshal(re, &wo) if err != nil { log.Println(err) sayCh <- fmt.Sprintf("*\n%s", weatherPrefix+err.Error()) } else { var description string if len(wo.Weather) < 1 { description = "" } else { description = ", " + wo.Weather[0].Description } sayCh <- fmt.Sprintf("*\n%s", weatherPrefix+wo.Name+", "+wo.Sys.Country+ " - Temp: "+strconv.Itoa(int(wo.Main.Temp-273.15))+ "°C"+description+ ", Humidity: "+strconv.Itoa(int(wo.Main.Humidity))+ "%, Wind: "+strconv.Itoa(int(wo.Wind.Speed*3.6))+ " km/h") } } } }