all repos — paprika @ time

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	trigger := parsed[0]
31	var loc string
32	if len(parsed) != 2 {
33		var err error
34		// Check if they've already set their location
35		loc, err = location.GetLocation(m.Prefix.Name)
36		if err == badger.ErrKeyNotFound {
37			return "Location not set. Use '.loc <location>' to set it.", nil
38		} else if err != nil {
39			return "Error getting location", err
40		}
41	}
42
43	// They're either querying for a location or @nick.
44	if len(loc) == 0 {
45		if strings.HasPrefix(parsed[1], "@") {
46			// Strip '@'
47			var err error
48			loc, err = location.GetLocation(parsed[1][1:])
49			if err == badger.ErrKeyNotFound {
50				return "Location not set. Use '.loc <location>' to set it.", nil
51			} else if err != nil {
52				return "Error getting location. Try again.", err
53			}
54		} else {
55			loc = parsed[1]
56		}
57	}
58
59	li, err := location.GetLocationInfo(loc)
60	if err != nil {
61		return "Error getting location info. Try again.", err
62	}
63
64	if len(li.Features) == 0 {
65		return "Error getting location info. Try again.", nil
66	}
67	coordinates := li.Features[0].Geometry.Coordinates
68	label := li.Features[0].Properties.Geocoding.Label
69
70	switch trigger {
71	case ".t", ".time":
72		time, err := time.GetTime(coordinates, label)
73		if err != nil {
74			return "Error getting time data", err
75		}
76		return time, nil
77	case ".w", ".weather":
78
79		info, err := weather.GetWeather(coordinates, label)
80		if err != nil {
81			return "Error getting weather data", err
82		}
83		return info, nil
84	}
85	return "", nil
86}