-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.go
273 lines (228 loc) · 6.21 KB
/
bot.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
package tgf
import (
"errors"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
var (
CouldNotExteactContextErr = errors.New("could not extract context")
UserErr = errors.New("user error")
)
func InitBotAPI(token string, telegramWebHookURL string, debug bool) (*tgbotapi.BotAPI, error) {
// TODO: need to figure out how to setup webhooks propery
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
return nil, err
}
bot.Debug = debug
return bot, nil
}
type Bot struct {
commands tgbotapi.SetMyCommandsConfig
journeyMap map[string]HandlerInterface
log Logger
bot *tgbotapi.BotAPI
journeyStore JourneyStore
}
func NewBot(bot *tgbotapi.BotAPI, commands tgbotapi.SetMyCommandsConfig, journeyMap map[string]HandlerInterface, log Logger, js JourneyStore) *Bot {
return &Bot{
bot: bot,
commands: commands,
journeyMap: journeyMap,
log: log,
journeyStore: js,
}
}
func (b *Bot) SetLogger(logger Logger) {
b.log = logger
}
func (b *Bot) StartBot(debug bool) error {
if b.log == nil {
b.log = NewDefaultLogger(debug)
}
b.log.Info("Authorized on account %s", b.bot.Self.UserName)
_, err := b.bot.Request(b.commands)
if err != nil {
return err
}
botcfg := tgbotapi.NewUpdate(0)
botcfg.Timeout = 60
updates := b.bot.GetUpdatesChan(botcfg)
for update := range updates {
go b.handleUpdate(update)
}
return nil
}
func (b *Bot) handleUpdate(update tgbotapi.Update) {
b.log.LogUpdate(update)
if update.Message == nil && update.CallbackQuery == nil {
return
}
var message *tgbotapi.Message
if update.Message != nil {
message = update.Message
}
if update.CallbackQuery != nil {
message = update.CallbackQuery.Message
}
if message == nil {
return
}
ctx := &Context{
Update: update,
nextHasBeenSet: false,
Log: b.log,
bot: b.bot,
}
chatID := ctx.GetChatID()
if message.IsCommand() {
c := message.Command()
ctx.Journey = &Journey{}
ctx.Journey.Command = c
ctx.Journey.Next = 0
ctx.Journey.TelegramChatID = chatID
} else {
j, err := b.journeyStore.GetJourneyByChatID(chatID)
if err != nil {
b.log.Error("[JOURNEY ERROR]: trying to access handler journey store: %w", err.Error())
return
}
if j == nil {
b.log.Error("[JOURNEY ERROR]: journey nil")
return
}
ctx.Journey = j
}
b.createCallbacks(ctx)
err := b.getJourney(ctx)
if err != nil {
b.log.Error("[HANDLER ERROR]: getting handler: %w", err)
return
}
err = b.execHandler(ctx)
if err != nil {
b.log.Error("[HANDLER ERROR]: error executing handler: %w", err)
return
}
// Joruney exit
if ctx.Journey == nil {
return
}
if len(ctx.handlers) > ctx.Journey.Next {
if !ctx.nextHasBeenSet {
if ctx.handlers == nil && ctx.handlers[ctx.Journey.Next+1] == nil {
ctx.Exit()
return
}
ctx.nextHasBeenSet = true
ctx.Journey.Next += 1
}
_, err := b.journeyStore.UpsertJourneyByTelegeramChatID(chatID, *ctx.Journey)
if err != nil {
b.log.Error("[JOURNEY ERROR]: trying to upsert handler journey DB: %w", err)
return
}
return
}
// if this is the last in the journey, cleanup
b.log.Debug("[SCHEDULER]: cleaning up journey for chat: %s", ctx.GetChatID())
err = b.journeyStore.CleanupChatJourney(chatID)
if err != nil {
b.log.Error("[DB ERROR]: trying to cleanup handler journey DB: %w", err)
return
}
}
func (b *Bot) createCallbacks(ctx *Context) {
ctx.skipTo = func(i int) {
if ctx.handlers[i] == nil {
b.log.Error("[SKIP TO ERROR]: invalid index %d", i)
ctx.Exit()
return
}
ctx.Journey.Next = i
err := b.execHandler(ctx)
if err != nil {
b.log.Error("[HANDLER ERROR]: error executing next handler in skipBy: %w", err)
return
}
if ctx.Journey != nil {
b.log.Debug("[SCHEDULER]: cleaning up journey for chat: %d", ctx.GetChatID())
err = b.journeyStore.CleanupChatJourney(ctx.GetChatID())
if err != nil {
b.log.Error("[DB ERROR]: trying to cleanup handler journey DB: %w", err)
return
}
}
ctx.nextHasBeenSet = false
}
ctx.exit = func() {
if len(ctx.Journey.MessagesCleanup) > 0 {
b.log.Debug("[CLEANUP]: message(s) to delete: %d", len(ctx.Journey.MessagesCleanup))
for _, messageID := range ctx.Journey.MessagesCleanup {
deleteMsg := tgbotapi.NewDeleteMessage(ctx.GetChatID(), messageID)
_, err := b.bot.Request(deleteMsg)
if err != nil {
b.log.Error("[BOT ERROR]: trying to cleanup messages: %w", err)
}
}
}
if ctx.Journey != nil {
b.log.Debug("[SCHEDULER]: cleaning up journey for chat: %d", ctx.GetChatID())
err := b.journeyStore.CleanupChatJourney(ctx.GetChatID())
if err != nil {
b.log.Error("[DB ERROR]: trying to cleanup handler journey DB: %w", err)
return
}
}
ctx.Journey = nil
}
ctx.changeJourney = func(command string, i int) {
if command != ctx.Journey.Command {
b.getJourney(ctx)
}
if ctx.handlers[i] == nil {
b.log.Error("[CHANGE HANDLER ERROR]: invalid index %d", i)
return
}
ctx.Journey.Next = i
}
}
func (b *Bot) getJourney(ctx *Context) error {
handlerJourney, ok := b.journeyMap[ctx.Journey.Command]
if !ok {
return cmdNotImplementedErr
}
journey := handlerJourney.GetHandlerJourney()
if journey[ctx.Journey.Next] == nil {
return errors.New("error trying to access handler journey which is nil")
}
ctx.handlers = journey
return nil
}
var (
cmdNotImplementedErr = errors.New("command not implemented")
)
func (b *Bot) execHandler(ctx *Context) error {
chatID := ctx.GetChatID()
// journey exit
if ctx.Journey == nil || ctx.handlers[ctx.Journey.Next] == nil {
return nil
}
err := ctx.handlers[ctx.Journey.Next](ctx)
if err != nil {
if err != UserErr {
b.log.Error("[HANDLER ERROR]: chatID %d, error: %w", chatID, err)
msg := tgbotapi.NewMessage(chatID, "Sorry, internal server error")
if _, err := b.bot.Send(msg); err != nil {
return fmt.Errorf("[HANDLER ERROR]: failed to send message %w", err)
}
}
b.log.Debug("[SCHEDULER]: cleaning up journey for chat: %d", chatID)
errCleanup := b.journeyStore.CleanupChatJourney(chatID)
if errCleanup != nil {
return fmt.Errorf("[HANDLER ERROR]: trying to cleanup handler journey %w", errCleanup)
}
return fmt.Errorf("[HANDLER ERROR]: %w", err)
}
return nil
}