-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
202 lines (168 loc) · 4.91 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
"gopkg.in/yaml.v2"
"github.com/lwsanty/cheap_flights/api_client"
"github.com/lwsanty/cheap_flights/localization"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
maxResults = 5
defaultConfigPath = "config/localization.yml"
separator = ", "
waitingGif = "https://media.giphy.com/media/tXL4FHPSnVJ0A/giphy.gif"
)
func main() {
b, err := tb.NewBot(tb.Settings{
Token: os.Getenv("API_TOKEN"),
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Println("failed to acquire bot:", err)
os.Exit(1)
}
data, err := ioutil.ReadFile(getEnv("CONFIG_PATH", defaultConfigPath))
if err != nil {
log.Println("failed to read languages file:", err)
os.Exit(1)
}
regulars := make(map[string]localization.RegMsgs)
if err := yaml.Unmarshal(data, regulars); err != nil {
log.Println("failed to get languages:", err)
os.Exit(1)
}
multiHelp := getMultiHelp(regulars)
send := func(user *tb.User, text string) {
if _, err := b.Send(user, text); err != nil {
log.Println("failed to send message:", err)
}
}
b.Handle("/start", func(m *tb.Message) {
send(m.Sender, multiHelp)
})
b.Handle("/help", func(m *tb.Message) {
send(m.Sender, multiHelp)
})
b.Handle(tb.OnUserJoined, func(m *tb.Message) {
send(m.Sender, multiHelp)
})
b.Handle(tb.OnText, func(m *tb.Message) {
loc, err := localization.New(regulars, m.Text)
if err != nil {
send(m.Sender, "🔴 could not parse text/не удалось распознать текст")
log.Println("failed to prepareText:", err)
return
}
text, err := prepareText(loc, m.Text)
if err != nil {
log.Println("failed to prepareText:", err)
send(m.Sender, fmt.Sprintf("🔴 \n%s \n\n%s", loc.RegularMsgs.ParseError, loc.RegularMsgs.HelpInstructions))
return
}
src, dst, err := api_client.GetSrcDstIATAs(text)
if err != nil {
log.Println("failed to get src and dst:", err)
send(m.Sender, fmt.Sprintf("🔴🔴 \n%s \n\n%s", loc.RegularMsgs.AirportDataError, loc.RegularMsgs.HelpInstructions))
return
}
//IATAResp := fmt.Sprintf("%s ➡️ %s", src.Name, dst.Name)
//send(m.Sender, IATAResp)
results, err := api_client.GetBestPrices(src, dst)
if err != nil {
log.Println("failed to get GetBestPrices:", err)
send(m.Sender, "🔴🔴 \n"+loc.RegularMsgs.RequestError)
return
}
optionsAmount := len(results)
if optionsAmount == 0 {
// TODO: pic
send(m.Sender, loc.RegularMsgs.NothingFound)
return
}
send(m.Sender, fmt.Sprintf(loc.RegularMsgs.Results, strconv.Itoa(optionsAmount), strconv.Itoa(maxResults)))
// TODO: spinner
waitMessage, err := b.Send(m.Sender, waitingGif)
if err != nil {
log.Println("failed to send wait message:", err)
}
optionsMessageText := optionsMessage(results)
if waitMessage != nil {
err := b.Delete(waitMessage)
if err != nil {
log.Println("failed to delete wait message:", err)
}
}
send(m.Sender, optionsMessageText)
})
b.Start()
}
func optionsMessage(results []api_client.Result) string {
var resOpt []string
for i, res := range results {
if i == maxResults {
break
}
price := fmt.Sprintf(" ₽💶 %v", res.Option.Price)
rate, err := api_client.GetCurrencyRateRubEur()
if err == nil && rate != 0 {
price = fmt.Sprintf("💶 € %.2f", rate*res.Option.Price)
} else {
log.Println("failed to get currency rate:", err)
}
depText := res.Option.DepartDate
depDay, err := api_client.GetWeekdayFromDate(res.Option.DepartDate)
if err == nil {
depText = res.Option.DepartDate + " " + strings.ToLower(depDay.String())
}
retText := res.Option.ReturnDate
retDay, err := api_client.GetWeekdayFromDate(res.Option.ReturnDate)
if err == nil {
retText = res.Option.ReturnDate + " " + strings.ToLower(retDay.String())
}
resOpt = append(resOpt, strings.Join([]string{
price,
fmt.Sprintf("🛫 %v", depText),
fmt.Sprintf("🛬 %v", retText),
// fmt.Sprintf("📏 %d km", opt.Distance),
fmt.Sprintf("🔄 %d", res.Option.NumberOfChanges),
//"🔎 " + res.Option.Site,
"🔎 " + res.Link,
}, "\n"))
}
return strings.Join(resOpt, "\n\n")
}
func prepareText(l *localization.Localization, text string) (string, error) {
cities := strings.Split(text, separator)
if len(cities) != 2 {
return "", fmt.Errorf("amount of cities does not equal to 2: %v", cities)
}
var result []string
for _, c := range cities {
r, err := l.TranslateCity(c)
if err != nil {
return "", err
}
result = append(result, r)
}
return strings.Join(result, " "), nil
}
func getEnv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
func getMultiHelp(r map[string]localization.RegMsgs) string {
var result []string
for lang, text := range r {
result = append(result, fmt.Sprintf("%s: %s %s", lang, text.Help, text.HelpInstructions))
}
return strings.Join(result, "\n\n")
}