all repos — paprika @ f6eedab26bfdb778c676fd60259b531d25f66ad6

go rewrite of taigabot

plugins/weather.go (view raw)

  1package plugins
  2
  3import (
  4	"strings"
  5
  6	"git.icyphox.sh/paprika/plugins/location"
  7	"git.icyphox.sh/paprika/plugins/time"
  8	"git.icyphox.sh/paprika/plugins/weather"
  9	"github.com/dgraph-io/badger/v3"
 10	"gopkg.in/irc.v3"
 11)
 12
 13func init() {
 14	Register(Weather{})
 15}
 16
 17type Weather struct{}
 18
 19func (Weather) Triggers() []string {
 20	return []string{
 21		".w",
 22		".weather",
 23		".t",
 24		".time",
 25	}
 26}
 27
 28func (Weather) Execute(m *irc.Message) (string, error) {
 29	parsed := strings.SplitN(m.Trailing(), " ", 2)
 30
 31	// TODO: AAAAAAAAAAAAAAAAAAAAAAAAAAA
 32	found := false
 33	trigger := parsed[0]
 34	for _, v := range (Weather{}).Triggers() {
 35		if trigger == v {
 36			found = true
 37			break
 38		}
 39	}
 40	if !found {
 41		return "", NoReply
 42	}
 43
 44
 45	var loc string
 46	if len(parsed) != 2 {
 47		var err error
 48		// Check if they've already set their location
 49		loc, err = location.GetLocation(m.Prefix.Name)
 50		if err == badger.ErrKeyNotFound {
 51			return "Location not set. Use '.loc <location>' to set it.", nil
 52		} else if err != nil {
 53			return "Error getting location", err
 54		}
 55	}
 56
 57	// They're either querying for a location or @nick.
 58	if len(loc) == 0 {
 59		if strings.HasPrefix(parsed[1], "@") {
 60			// Strip '@'
 61			var err error
 62			loc, err = location.GetLocation(parsed[1][1:])
 63			if err == badger.ErrKeyNotFound {
 64				return "Location not set. Use '.loc <location>' to set it.", nil
 65			} else if err != nil {
 66				return "Error getting location. Try again.", err
 67			}
 68		} else {
 69			loc = parsed[1]
 70		}
 71	}
 72
 73	li, err := location.GetLocationInfo(loc)
 74	if err != nil {
 75		return "Error getting location info. Try again.", err
 76	}
 77
 78	if len(li.Features) == 0 {
 79		return "Error getting location info. Try again.", nil
 80	}
 81	coordinates := li.Features[0].Geometry.Coordinates
 82	label := li.Features[0].Properties.Geocoding.Label
 83
 84	switch trigger {
 85	case ".t", ".time":
 86		time, err := time.GetTime(coordinates, label)
 87		if err != nil {
 88			return "Error getting time data", err
 89		}
 90		return time, nil
 91	case ".w", ".weather":
 92
 93		info, err := weather.GetWeather(coordinates, label)
 94		if err != nil {
 95			return "Error getting weather data", err
 96		}
 97		return info, nil
 98	}
 99	return "", nil
100}