rough weather fetcher #1

Manually merged
sneak merged 4 commits from next into master 2020-09-09 03:36:32 +00:00
1 changed files with 38 additions and 1 deletions
Showing only changes of commit a38926062f - Show all commits

View File

@ -4,6 +4,7 @@ package bot
import (
"fmt"
"github.com/mattermost/mattermost-server/v5/model"
"net/http"
"os"
"os/signal"
"regexp"
@ -71,7 +72,7 @@ func (b *Bot) Main() int {
// Lets create a bot channel for logging debug messages into
b.CreateBotDebuggingChannelIfNeeded()
msg := fmt.Sprintf("_**%s** has started up_\n\nrunning on version %s", b.BotName, b.Version)
msg := fmt.Sprintf("_**%s** (version `%s`) is now starting up", b.BotName, b.Version)
b.SendMsgToDebuggingChannel(msg, "")
// Lets start listening to some channels via the websocket!
@ -229,6 +230,38 @@ func (b *Bot) Shutdown() {
syscall.Kill(syscall.Getpid(), syscall.SIGINT)
}
func (b *Bot) HandleWeatherRequest(channelid string, postid string, message string) {
msg := fmt.Sprintf("weather request received: `%s`", message)
b.SendMsgToChannel(msg, postid, channelid)
r := regexp.MustCompile(`metar\s+([A-Za-z]{4})`)
loc := r.FindString(message)
if loc == "" {
b.SendMsgToChannel("error, sorry", postid, channelid)
}
token := os.Getenv("METAR_API_TOKEN")
url := fmt.Sprintf("https://avwx.rest/api/metar/%s?options=&airport=true&reporting=true&format=json&onfail=cache", loc)
msg = fmt.Sprintf("calculated url: `%s`", url)
b.SendMsgToChannel(msg, postid, channelid)
client := http.Client{
Timeout: 5 * time.Second,
}
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", `Token `+token)
resp, err := client.Do(req)
if err != nil {
b.SendMsgToChannel(fmt.Sprintf("weather fetch error: %s", err), postid, channelid)
return
}
b.SendMsgToChannel(fmt.Sprintf("weather %s: %s", loc, resp), postid, channelid)
}
func (b *Bot) HandleMsgFromChannel(event *model.WebSocketEvent) {
post := model.PostFromJson(strings.NewReader(event.Data["post"].(string)))
@ -237,6 +270,10 @@ func (b *Bot) HandleMsgFromChannel(event *model.WebSocketEvent) {
}
//pretty.Print(post)
if matched, _ := regexp.MatchString(`(?:^|\W)metar(?:$|\W)`, post.Message); matched {
b.HandleWeatherRequest(post.ChannelId, post.Id, post.Message)
return
}
if matched, _ := regexp.MatchString(`(?:^|\W)alive(?:$|\W)`, post.Message); matched {
b.SendMsgToChannel("yes I'm running", post.Id, post.ChannelId)