bb/bot/handler/weather.go

78 lines
1.4 KiB
Go
Raw Normal View History

2022-08-24 14:06:00 +00:00
package handler
import (
"fmt"
"strings"
"git.kill0.net/chill9/beepboop/bot"
"git.kill0.net/chill9/beepboop/lib/weather"
2022-08-24 14:06:00 +00:00
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
2022-08-24 14:06:00 +00:00
)
type WeatherHandler struct {
Config bot.Config
Name string
2022-08-24 14:06:00 +00:00
}
2022-08-27 14:00:35 +00:00
func NewWeatherHandler(s string) *WeatherHandler {
2022-09-05 03:36:14 +00:00
return &WeatherHandler{Name: s}
2022-08-24 14:06:00 +00:00
}
func (h *WeatherHandler) SetConfig(config bot.Config) {
h.Config = config
}
func (h *WeatherHandler) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {
var (
err error
loc string
w weather.Weather
2022-08-24 14:06:00 +00:00
)
if m.Author.ID == s.State.User.ID {
return
}
if !strings.HasPrefix(m.Content, "!weather") {
return
}
x := strings.SplitN(m.Content, " ", 2)
if len(x) != 2 {
s.ChannelMessageSend(m.ChannelID, "help: `!weather <CITY>,<STATE>,<COUNTRY>`")
return
}
loc = x[1]
if h.Config.OpenWeatherMapToken == "" {
log.Error("OpenWeather token is not set")
return
}
wc := weather.NewClient(h.Config.OpenWeatherMapToken)
2022-08-24 14:06:00 +00:00
log.Debugf("weather requested for '%s'", loc)
2022-08-24 14:06:00 +00:00
w, err = wc.Get(loc)
2022-08-24 14:06:00 +00:00
if err != nil {
log.Errorf("weather client error: %v", err)
2022-08-24 14:06:00 +00:00
return
}
log.Debugf("weather returned for '%s': %+v", loc, w)
2022-08-24 14:06:00 +00:00
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf(
"%s (%.1f, %.1f) — C:%.1f F:%.1f K:%.1f",
loc,
w.Coord.Lat,
w.Coord.Lon,
w.Main.Temp.Celcius(),
w.Main.Temp.Fahrenheit(),
w.Main.Temp.Kelvin(),
))
}