/
main.go
278 lines (240 loc) · 7.06 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package main
import (
"io/ioutil"
"log"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/foxcpp/timetable_bot/ttparser"
"github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/jasonlvhit/gocron"
"github.com/pkg/errors"
"github.com/slongfield/pyfmt"
"gopkg.in/yaml.v2"
)
var bot *tgbotapi.BotAPI
var cache *Cache
var config Config
var lang LangStrings
type TimeSlot struct {
Hour, Minute int
}
func (ts *TimeSlot) UnmarshalYAML(unmarshal func(interface{}) error) error {
str := ""
if err := unmarshal(&str); err != nil {
}
splitten := strings.Split(str, ":")
if len(splitten) != 2 {
return errors.New("invalid timeslot format")
}
hourStr := splitten[0]
minuteStr := splitten[1]
if hour, err := strconv.Atoi(hourStr); err != nil {
return errors.Wrap(err, "invalid hour value")
} else {
ts.Hour = hour
}
if minute, err := strconv.Atoi(minuteStr); err != nil {
return errors.Wrap(err, "invalid minute value")
} else {
ts.Minute = minute
}
return nil
}
func ttindex(slot TimeSlot) int {
for i, slotI := range config.TimeslotsBegin {
if slotI == slot {
return i + 1
}
}
return -1
}
type Config struct {
Lang string `yaml:"lang"`
Token string `yaml:"token"`
Driver string `yaml:"driver"`
DSN string `yaml:"dsn"`
CmdProcGoroutines int `yaml:"cmd_processing_goroutines"`
Admins []int `yaml:"admins"`
NotifyChats []int64 `yaml:"notify_chats"`
NotifyInMins int `yaml:"notify_in_mins"`
NotifyOnEnd bool `yaml:"notify_on_end"`
NotifyOnBreak bool `yaml:"notify_on_break"`
TimeZone string `yaml:"timezone"`
TimeslotsBegin []TimeSlot `yaml:"timeslots_begin"`
TimeslotsBreak []TimeSlot `yaml:"timeslots_break"`
TimeslotsEnd []TimeSlot `yaml:"timeslots_end"`
SourceCfg ttparser.Cfg `yaml:"source_cfg"`
GroupMembers []string `yaml:"group_members"`
}
type LangStrings struct {
LessonTypes map[LessonType]string `yaml:"lesson_types"`
LessonTypeStrs map[string]LessonType `yaml:"lesson_types_short"`
Help string `yaml:"help"`
AdminHelp string `yaml:"adminhelp"`
Usage struct {
Schedule string `yaml:"schedule"`
Evict string `yaml:"evict"`
} `yaml:"usage"`
Replies struct {
SomethingBroke string `yaml:"something_broke"`
MissingPermissions string `yaml:"missing_permissions"`
InvalidDate string `yaml:"invalid_date"`
TimetableHeader string `yaml:"timetable_header"`
Empty string `yaml:"empty"`
NoMoreLessonsToday string `yaml:"no_more_lessons_today"`
} `yaml:"replies"`
EntryTemplate string `yaml:"entry_template"`
LessonEndNotify string `yaml:"lesson_end_notify"`
BreakNotify string `yaml:"break_notify"`
TimeslotFormat string `yaml:"timeslot_format"`
}
func extractCommand(msg *tgbotapi.Message) string {
if msg.Entities == nil {
return ""
}
for _, entity := range *msg.Entities {
if entity.Type != "bot_command" {
return ""
}
if entity.Offset != 0 {
return ""
}
fullCmd := msg.Text[:entity.Length]
if strings.Contains(fullCmd, "@") && !strings.HasSuffix(fullCmd, bot.Self.UserName) {
return ""
}
splitten := strings.Split(fullCmd, "@")
return splitten[0][1:]
}
return ""
}
func formatEntry(entry Entry) string {
ttindx := ttindex(TimeSlot{entry.Time.Hour(), entry.Time.Minute()})
return pyfmt.Must(lang.EntryTemplate, map[string]interface{}{
"num": ttindx,
"classroom": entry.Classroom,
"name": entry.Name,
"startTime": entry.Time.Format("15:04"),
"endTime": TimeSlotSet(time.Now(), config.TimeslotsEnd[ttindx-1]).Format("15:04"),
"type": lang.LessonTypes[entry.Type],
"lecturer": entry.Lecturer,
})
}
func processUpdates(updates <-chan tgbotapi.Update) {
for {
update := <-updates
if update.CallbackQuery != nil {
err := handleCallbackQuery(update.CallbackQuery)
if err != nil {
log.Printf("ERROR: while processing callback query id %v: %v\n",
update.CallbackQuery.ID, err)
}
} else {
if update.Message == nil || update.Message.Text == "" {
continue
}
msg := update.Message
if msg.Text == "<3" && msg.ReplyToMessage != nil && msg.ReplyToMessage.From.ID == bot.Self.ID {
easterEgg(msg)
continue
}
command := extractCommand(msg)
if command == "" {
continue
}
var err error
switch command {
case "today":
err = todayCmd(msg)
case "tomorrow":
err = tomorrowCmd(msg)
case "next":
err = nextCmd(msg)
case "timetable":
err = timetableCmd(msg)
case "help":
err = helpCmd(msg)
case "adminhelp":
err = adminHelpCmd(msg)
case "schedule":
err = scheduleCmd(msg)
case "evict":
err = evictCmd(msg)
}
if err != nil {
log.Printf("ERROR: while processing command %s in chatid=%d,msgid=%d,uid=%d: %v\n",
command, msg.Chat.ID, msg.MessageID, msg.From.ID, err)
}
}
}
}
func main() {
if os.Getenv("USING_SYSTEMD") == "1" {
// Don't log timestamp since journald records it anyway.
log.SetFlags(0)
}
if len(os.Args) != 2 {
log.Fatalln("Usage:", os.Args[0], "<config file>")
}
configPath := os.Args[1]
confFile, err := ioutil.ReadFile(configPath)
if err != nil {
log.Fatalln("Failed to read config file (botconf.yml):", err)
}
if err = yaml.UnmarshalStrict(confFile, &config); err != nil {
log.Fatalln("Failed to decode config file (botconf.yml):", err)
}
langFile, err := ioutil.ReadFile(config.Lang)
if err != nil {
log.Fatalln("Failed read lang file:", err)
}
if err = yaml.UnmarshalStrict(langFile, &lang); err != nil {
log.Fatalln("Failed to decode lang file:", err)
}
timezone, err = time.LoadLocation(config.TimeZone)
if err != nil {
log.Fatalln("Failed to set timezone:", err)
}
log.Println("Configuration:")
log.Println("- Lang file:", config.Lang)
log.Println("- Token:", config.Token[:10]+"...")
log.Println("- Timezone:", timezone)
log.Println("- Admins:", config.Admins)
log.Println("- Notify targets:", config.NotifyChats)
log.Printf("- Source: %+v\n", config.SourceCfg)
log.Println("- Group members:", len(config.GroupMembers), "people")
log.Println("- Notify: in", config.NotifyInMins, "before begin; on end:", config.NotifyOnEnd, "; on break:", config.NotifyOnBreak)
cache = NewCache()
bot, err = tgbotapi.NewBotAPI(config.Token)
if err != nil {
log.Fatalln("Failed to init Bot API:", err)
}
gocron.Every(1).Minute().Do(checkNotifications)
gocron.Start()
u := tgbotapi.NewUpdate(0)
u.Timeout = 25
updates, err := bot.GetUpdatesChan(u)
if err != nil {
log.Fatalln("Failed to init. updates channel:", err)
}
sig := make(chan os.Signal)
signal.Notify(sig, syscall.SIGTERM, syscall.SIGHUP, os.Interrupt)
log.Println("Started.")
if os.Getenv("USING_SYSTEMD") == "1" {
cmd := exec.Command("systemd-notify", "--ready", `--status=Listening for updates`)
if out, err := cmd.Output(); err != nil {
log.Println("Failed to notify systemd about successful startup:", err)
log.Println(string(out))
}
}
for i := 0; i < config.CmdProcGoroutines; i++ {
go processUpdates(updates)
}
s := <-sig
log.Printf("%v; stopping...\n", s)
}