/
weather.go
211 lines (190 loc) · 6.85 KB
/
weather.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
Package worldweather is an reference implementation that provides relatively practical sarah.CommandProps.
This illustrates the use of user's conversational context, sarah.UserContext.
When weather API returns response that indicates input error, this command returns text message along with a sarah.UserContext
so the user's next input will be directly fed to the designated function, which actually is equivalent to second command call in this time.
To see detailed implementation, read corresponding code where this command is calling slack.NewStringResponseWithNext.
When this sarah.CommandProps is passed to sarah.Runner, sarah.Runner tries to read configuration file and map content to weather.CommandConfig.
Setup should be somewhat like below:
options := sarah.NewRunnerOptions
options.Append(sarah.WithCommandProps(hello.SlackProps))
options.Append(sarah.WithCommandProps(echo.SlackProps))
options.Append(sarah.WithCommandProps(worldweather.SlackProps))
// Config.PluginConfigRoot must be set to read configuration file for this command.
// Runner searches for configuration file located at config.PluginConfigRoot + "/slack/weather.(yaml|yml|json)".
config := sarah.NewConfig()
config.PluginConfigRoot = "/path/to/config/" // Or do yaml.Unmarshal(fileBuf, config), json.Unmarshal(fileBuf, config)
runner, err := sarah.NewRunner(config, options.Arg())
*/
package worldweather
import (
"fmt"
"github.com/oklahomer/go-sarah"
"github.com/oklahomer/go-sarah/log"
"github.com/oklahomer/go-sarah/slack"
"github.com/oklahomer/golack/webapi"
"golang.org/x/net/context"
"regexp"
"time"
)
// MatchPattern defines regular expression pattern that is checked against user input
var MatchPattern = regexp.MustCompile(`^\.weather`)
// SlackProps provide a set of command configuration variables for weather command.
// Since this sets *CommandConfig in ConfigurableFunc, configuration file is observed by Runner and CommandConfig is updated on file change.
// Weather command is re-built on configuration update.
var SlackProps = sarah.NewCommandPropsBuilder().
BotType(slack.SLACK).
Identifier("weather").
ConfigurableFunc(NewCommandConfig(), SlackCommandFunc).
InputExample(".weather tokyo").
MatchPattern(MatchPattern).
MustBuild()
// CommandConfig contains some configuration variables for weather command.
type CommandConfig struct {
APIKey string `yaml:"api_key"`
}
// NewCommandConfig creates and returns CommandConfig with default settings.
// To override default settings, pass the returned value to (json|yaml).Unmarshal or do this manually.
func NewCommandConfig() *CommandConfig {
return &CommandConfig{
APIKey: "",
}
}
// SlackCommandFunc is a function that satisfies sarah.CommandConfig type.
// This can be fed to CommandPropsBuilder.ConfigurableFunc.
func SlackCommandFunc(ctx context.Context, input sarah.Input, config sarah.CommandConfig) (*sarah.CommandResponse, error) {
strippedMessage := sarah.StripMessage(MatchPattern, input.Message())
// Share client instance with later execution
conf, _ := config.(*CommandConfig)
client := NewClient(NewConfig(conf.APIKey))
resp, err := client.LocalWeather(ctx, strippedMessage)
// If error is returned with HTTP request level, just let it know and quit.
if err != nil {
log.Errorf("Error on weather api reqeust: %s.", err.Error())
return slack.NewStringResponse("Something went wrong with weather api request."), nil
}
// If status code of 200 is returned, which means successful API request, but still the content contains error message,
// notify the user and put him in "the middle of conversation" for further communication.
if resp.Data.HasError() {
errorDescription := resp.Data.Error[0].Message
return slack.NewStringResponseWithNext(
fmt.Sprintf("Error was returned: %s.\nInput location name to retry, please.", errorDescription),
func(c context.Context, i sarah.Input) (*sarah.CommandResponse, error) {
return SlackCommandFunc(c, i, config)
},
), nil
}
request := resp.Data.Request[0]
currentCondition := resp.Data.CurrentCondition[0]
forecast := resp.Data.Weather[0]
astronomy := forecast.Astronomy[0]
currentDesc := fmt.Sprintf("Current weather at %s is... %s.", request.Query, currentCondition.Description[0].Content)
primaryLabelColor := "#32CD32" // lime green
secondaryLabelColor := "#006400" // dark green
miscLabelColor := "#808080"
attachments := []*webapi.MessageAttachment{
// Current condition and overall description
{
Fallback: currentDesc,
Pretext: "Current Condition",
Title: currentDesc,
Color: primaryLabelColor,
ImageURL: currentCondition.WeatherIcon[0].URL,
},
// Temperature
{
Fallback: fmt.Sprintf("Temperature: %d degrees Celsius.", currentCondition.Temperature),
Title: "Temperature",
Color: primaryLabelColor,
Fields: []*webapi.AttachmentField{
{
Value: fmt.Sprintf("%d ℃", currentCondition.Temperature),
Short: true,
},
},
},
// Wind speed
{
Fallback: fmt.Sprintf("Wind speed: %d Km/h. Direction: %s.", currentCondition.WindSpeed, currentCondition.WindDirectionCardinal),
Title: "Wind",
Color: primaryLabelColor,
Fields: []*webapi.AttachmentField{
{
Title: "Speed",
Value: fmt.Sprintf("%d km/h", currentCondition.WindSpeed),
Short: true,
},
{
Title: "Direction",
Value: currentCondition.WindDirectionCardinal,
Short: true,
},
},
},
// Astronomy
{
Fallback: fmt.Sprintf("Sunrise at %s. Sunset at %s.", astronomy.Sunrise, astronomy.Sunset),
Pretext: "Astronomy",
Title: "",
Color: secondaryLabelColor,
Fields: []*webapi.AttachmentField{
{
Title: "Sunrise",
Value: astronomy.Sunrise,
Short: true,
},
{
Title: "Sunset",
Value: astronomy.Sunset,
Short: true,
},
{
Title: "Moonrise",
Value: astronomy.MoonRise,
Short: true,
},
{
Title: "Moonset",
Value: astronomy.MoonSet,
Short: true,
},
},
},
}
now := time.Now()
for _, hourly := range forecast.Hourly {
if now.Hour() > hourly.Time.Hour {
continue
}
attachments = append(attachments, &webapi.MessageAttachment{
Fallback: "Hourly Forecast",
Pretext: "Hourly Forecast for " + hourly.Time.DisplayTime,
Title: hourly.Description[0].Content,
Color: miscLabelColor,
Fields: []*webapi.AttachmentField{
{
Title: "Temperature",
Value: fmt.Sprintf("%d ℃", hourly.Temperature),
Short: true,
},
{
Title: "Precipitation",
Value: fmt.Sprintf("%6.2f mm", hourly.Precipitation),
Short: true,
},
{
Title: "Wind Speed",
Value: fmt.Sprintf("%d km/h", hourly.WindSpeed),
Short: true,
},
{
Title: "Wind Direction",
Value: hourly.WindDirectionCardinal,
Short: true,
},
},
ImageURL: hourly.WeatherIcon[0].URL,
})
}
return slack.NewPostMessageResponse(input, "", attachments), nil
}