-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
178 lines (155 loc) · 4.82 KB
/
main.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
package main
import (
"log"
"net/http"
"bytes"
"os"
"time"
"io/ioutil"
"encoding/json"
"github.com/joho/godotenv"
"gopkg.in/telegram-bot-api.v4"
"github.com/snowypowers/sgweatherbot/poller"
"github.com/snowypowers/sgweatherbot/store"
)
var nlpToken, botToken, webLink, apiKey string
var client = &http.Client{Timeout: time.Second * 10}
type context struct{
poller *poller.Poller
reply chan tgbotapi.MessageConfig
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
botToken = os.Getenv("BOT_TOKEN")
webLink = os.Getenv("WEBSITE_LINK")
apiKey = os.Getenv("DATA_API_KEY")
nlpToken = os.Getenv("NLP_TOKEN")
//Poller
p := poller.NewPoller(client)
wf2 := poller.Subscription{
"wf2",
"https://api.data.gov.sg/v1/environment/2-hour-weather-forecast",
apiKey,
300}
wf2Close := p.Listen(wf2)
//Bot
bot, err := tgbotapi.NewBotAPIWithClient(botToken, client)
if err != nil {
log.Fatal(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert(webLink+bot.Token, "cert.pem"))
if err != nil {
log.Fatal(err)
}
updates := bot.ListenForWebhook("/" + bot.Token)
//Website
http.Handle("/", http.FileServer(http.Dir("./website")))
go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
//Cmd Handling
reply := make(chan tgbotapi.MessageConfig)
ctx := context{p, reply}
for {
select {
case u:= <-updates:
go processUpdate(u, ctx)
case r := <-reply:
bot.Send(r)
}
}
//Teardown
close(wf2Close)
}
func processUpdate(update tgbotapi.Update, ctx context) {
//Command Parsing
cmd := update.Message.Command()
args := update.Message.CommandArguments()
var msg tgbotapi.MessageConfig
switch cmd {
case "w", "weather", "wf2":
msg = processWf2(update, ctx.poller.ValueByName("wf2"), args)
case "start":
msg = tgbotapi.NewMessage(update.Message.Chat.ID, "Hello!\nI am Teru!\n I provide 2 hour nowcasts of the weather in Singapore!This data is provided by NEA.\n To get the weather at a certain area, type /w <area name>.\nType /help for instructions!")
case "help":
msg = tgbotapi.NewMessage(update.Message.Chat.ID, "Use command /w to get the weather forecast for the next 2 hours")
case "about":
msg = tgbotapi.NewMessage(update.Message.Chat.ID, "Data retrieved from NEA. Conversations powered by API.ai, Coded in Go.")
case "":
//No cmds. Forward req to API.AI
msg = processNLP(update)
default:
msg = tgbotapi.NewMessage(update.Message.Chat.ID, "huh?")
}
ctx.reply <- msg
}
func processNLP(update tgbotapi.Update) tgbotapi.MessageConfig {
req := constructNLPReq(update)
res, err := client.Do(req)
if err != nil {
log.Panic(err)
}
defer res.Body.Close()
bs, err := ioutil.ReadAll(res.Body)
var resBody nlpResponse
if err := json.Unmarshal(bs, &resBody); err != nil {
log.Println(err)
}
return nlpRespToMsg(update, resBody)
}
func constructNLPReq(update tgbotapi.Update) *http.Request {
nlpBody := nlpRequest{update.Message.Text, string(update.Message.Chat.ID), "en", 20170101}
body, err := json.Marshal(nlpBody)
req, err := http.NewRequest("POST", "https://api.api.ai/v1/query", bytes.NewBuffer(body))
if err != nil {
log.Panic(err)
}
req.Header.Set("Authorization", "Bearer " + nlpToken)
req.Header.Set("Content-Type", "application/json")
return req
}
func nlpRespToMsg(update tgbotapi.Update, res nlpResponse) tgbotapi.MessageConfig {
log.Printf("NLP RESP: %v+", res)
msg := tgbotapi.NewMessage(update.Message.Chat.ID, res.Result.Speech)
return msg
}
func processWf2(update tgbotapi.Update, data []byte, args string) tgbotapi.MessageConfig {
d := store.ParseWf2(data)
a := store.ParseArea(args)
log.Printf("args: %s", a)
var msg tgbotapi.MessageConfig
switch(a) {
case "All":
msg = tgbotapi.NewMessage(update.Message.Chat.ID, printAllWf2(d))
case "North", "South", "East", "West", "Central":
msg = tgbotapi.NewMessage(update.Message.Chat.ID, printAreaWf2(d, a))
case "":
if args == "" {
msg = tgbotapi.NewMessage(update.Message.Chat.ID, "Choose a region or type in the area name after /w. \nFor example, /w Bedok.")
msg.ReplyMarkup = wf2FullKb
} else {
msg = tgbotapi.NewMessage(update.Message.Chat.ID, "Sorry, did you spell the area wrongly?")
}
default:
f := d.Forecasts[a]
msg = tgbotapi.NewMessage(update.Message.Chat.ID, "The weather at " + a + " is " + f)
}
return msg
}
func printAllWf2(w store.WF2Update) string {
s := "Weather for " + w.Timestamp.Format("Mon Jan 2 03:04 PM ") + " \n"
for k,v:= range w.Forecasts {
s += k + ": " + v + "\n"
}
return s
}
func printAreaWf2(w store.WF2Update, area string) string {
s := "The 2 hour Nowcast for " + area + " at " + w.Timestamp.Format("Mon Jan 2 03:04 PM ") + " \n"
for _,v := range regions[area] {
s += v + ": " + w.Forecasts[v] + "\n"
}
return s
}