all repos — paprika @ 83a983af647189c6127ba3437e8604fc5e4575d9

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/weather"
 8	"github.com/dgraph-io/badger/v3"
 9	"gopkg.in/irc.v3"
10)
11
12func init() {
13	Register(Weather{})
14}
15
16type Weather struct{}
17
18func (Weather) Triggers() []string {
19	return []string{
20		".w",
21		".weather",
22	}
23}
24
25func (Weather) Execute(m *irc.Message) (string, error) {
26	parsed := strings.SplitN(m.Trailing(), " ", 2)
27	var loc string
28	if len(parsed) != 2 {
29		var err error
30		// Check if they've already set their location
31		loc, err = location.GetLocation(m.Prefix.Name)
32		if err == badger.ErrKeyNotFound {
33			return "Location not set. Use '.loc <location>' to set it.", nil
34		} else if err != nil {
35			return "Error getting location", err
36		}
37	}
38
39	// They're either querying for a location or @nick.
40	if len(loc) == 0 {
41		if strings.HasPrefix(parsed[1], "@") {
42			// Strip '@'
43			var err error
44			loc, err = location.GetLocation(parsed[1][1:])
45			if err == badger.ErrKeyNotFound {
46				return "Location not set. Use '.loc <location>' to set it.", nil
47			} else if err != nil {
48				return "Error getting location. Try again.", err
49			}
50		} else {
51			loc = parsed[1]
52		}
53	}
54
55	li, err := location.GetLocationInfo(loc)
56	if err != nil {
57		return "Error getting location info. Try again.", err
58	}
59
60	if len(li.Features) == 0 {
61		return "Error getting location info. Try again.", nil
62	}
63	coordinates := li.Features[0].Geometry.Coordinates
64	label := li.Features[0].Properties.Geocoding.Label
65	info, err := weather.GetWeather(coordinates, label)
66	if err != nil {
67		return "Error getting weather data", err
68	}
69	return info, nil
70}