-
Notifications
You must be signed in to change notification settings - Fork 0
/
commandsV2.go
654 lines (601 loc) · 17.8 KB
/
commandsV2.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// commandsV2 is a replacement for action-based message processing. Everything
// inside here is responsible for tying database together with telegram
// interactions.
package main
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"log"
"sort"
"strings"
)
type Callback interface {
Call(*State, *CallbackQuery) error
Match(*State, *CallbackQuery) bool
AsInlineKeyboard() *InlineKeyboard
}
type State struct {
*Clients
}
// TODO:
func (s *State) LoadCommand(chatID int64) (*SerializedCommand, error) {
return nil, nil
}
// TODO:
func (s *State) SaveCommand(chatID int64, _ *SerializedCommand) error {
return nil
}
type Bot struct {
state *State
command map[int64]Command
}
func (b *Bot) fetchCommand(chatID int64) Command {
cmd := b.command[chatID]
if cmd == nil {
s, err := b.state.LoadCommand(chatID)
if err == nil {
cmd, err = s.AsCommand()
}
if err != nil {
cmd = nil
log.Printf("INTERNAL ERROR: couldn't fetch command for chat %d: %v", chatID, err)
}
if cmd == nil {
cmd = CommandsTemplate.DefaultCommand("")
}
}
b.command[chatID] = cmd
return cmd
}
func (b *Bot) updateCommand(chatID int64, cmd Command) error {
b.command[chatID] = cmd
var s *SerializedCommand
if cmd != nil {
s = cmd.Serialize()
}
return b.state.SaveCommand(chatID, s)
}
func (b *Bot) Update(u *Update) (err error) {
chatId, _ := u.ChatId()
if err != nil {
return err
}
// Try surfacing UserError and update the bot accordingly on internal error.
defer func() {
var e UserError
if errors.As(err, &e) {
err = e.Surface(b.state)
}
if err == nil {
return
}
log.Printf("INTERNAL ERROR: %v", err)
// Reset command so that user wouldn't be stuck with internal errors
// with no way out.
if upErr := b.updateCommand(chatId, nil); upErr != nil {
log.Printf("INTERNAL ERROR: updateCommand(%d, nil): %v; while handling %v", chatId, upErr, err)
}
}()
if u.CallbackQuery != nil {
for _, c := range CommandsTemplate.Callbacks {
if c.Match(b.state, u.CallbackQuery) {
return c.Call(b.state, u.CallbackQuery)
}
}
return fmt.Errorf("INTERNAL ERROR: Did find a corresponding callback for callback query: %v", u.CallbackQuery)
}
if u.Message == nil {
// TODO: Make internal error type.
return fmt.Errorf("INTERNAL ERROR: Update is neither a message, nor a callback query: %v", u)
}
// Update is a Message.
msg := u.Message.Text
for n, f := range CommandsTemplate.Commands {
if msg == n {
cmd := f(n)
cmd, err = cmd.OnCommand(b.state, u.Message)
if err != nil {
return err
}
if cmd == nil {
cmd = CommandsTemplate.DefaultCommand("")
}
return b.updateCommand(chatId, cmd)
}
}
// None of the commands match, so process the message.
cmd := b.fetchCommand(chatId)
cmd, err = cmd.ProcessMessage(b.state, u.Message)
// On user caused error command should still be updated accordingly.
if err == nil || errors.Is(err, UserError{}) {
return b.updateCommand(chatId, cmd)
}
return err
}
type SerializedCommand struct {
// Name of the command
Name string
// Serialized command's state. Command should be able to restore it's state
// from this string.
Data []byte
}
func (s *SerializedCommand) AsCommand() (Command, error) {
factory := CommandsTemplate.DefaultCommand
if s == nil {
return factory(""), nil
}
for n, f := range CommandsTemplate.Commands {
if n == s.Name {
factory = f
}
}
cmd := factory(s.Name)
return cmd, cmd.Init(s)
}
type Command interface {
Serialize() *SerializedCommand
Init(*SerializedCommand) error
// Process message from the user.
ProcessMessage(*State, *Message) (Command, error)
// Called when user runs this command.
OnCommand(*State, *Message) (Command, error)
// Both OnCommand and ProcessMessage return the new context command
}
// Factory is used so that Command metadata is not changed accidentally.
type CommandFactory func(name string) Command
// UserError is an error that should be surfaced to the user.
type UserError struct {
Err error
ChatID int64
}
func (u UserError) Error() string {
return u.Err.Error()
}
// Surface surfaces error to the user.
func (u UserError) Surface(s *State) error {
e := u.Error()
if len(e) > 0 {
e = strings.ToUpper(e[:1]) + e[1:]
}
return s.Telegram.SendTextMessage(u.ChatID, e)
}
type question struct {
name string
ask func(s *State, chatID int64) error
validate func(*State, *Message) error
answer string
}
type multiQuestionCommand struct {
name string
// All questions should have unique names.
// range is used instead of map so that the called can control questions' order.
questions []*question
// Once user answers all questions save will be called. questions will have
// answers populated.
save func(state *State, chatID int64, questions []*question) error
// Name of the last question we have asked.
lastQuestion string
}
func MultiQuestionCommandFactory(questions []*question, save func(state *State, chatID int64, questions []*question) error) CommandFactory {
return func(name string) Command {
return &multiQuestionCommand{
name: name,
questions: questions,
save: save,
}
}
}
type multiQuestionCommandSerialized struct {
answers map[string]string
lastQuestion string
}
func (c *multiQuestionCommand) Serialize() *SerializedCommand {
// No need to serialize question names, they should be the same in CommandsTemplate.
// Need to serialize answers to the questions though.
a := make(map[string]string)
for _, q := range c.questions {
a[q.name] = q.answer
}
cs := &multiQuestionCommandSerialized{
answers: a,
lastQuestion: c.lastQuestion,
}
b, err := json.Marshal(cs)
if err != nil {
log.Printf("INTERNAL ERROR: Couldn't serialize %v: %v", cs, err)
}
return &SerializedCommand{
Name: c.name,
Data: b,
}
}
func (c *multiQuestionCommand) Init(s *SerializedCommand) error {
cs := &multiQuestionCommandSerialized{}
if err := json.Unmarshal(s.Data, &cs); err != nil {
return fmt.Errorf("Unmarshal(%s): %w", s.Data, err)
}
for _, q := range c.questions {
q.answer = cs.answers[q.name]
}
c.lastQuestion = cs.lastQuestion
return nil
}
func (c *multiQuestionCommand) OnCommand(s *State, m *Message) (Command, error) {
chatID := m.Chat.Id
if len(c.questions) == 0 {
// With to questions, no reason to have this command process messages.
return nil, c.save(s, chatID, c.questions)
}
if err := c.questions[0].ask(s, chatID); err != nil {
return nil, err
}
c.lastQuestion = c.questions[0].name
return c, nil
}
func (c *multiQuestionCommand) ProcessMessage(s *State, m *Message) (Command, error) {
var q *question
for _, qe := range c.questions {
if qe.name == c.lastQuestion {
q = qe
break
}
}
if q == nil {
return nil, fmt.Errorf("INTERNAL ERROR: Did not find a question corresponding to last question %s", c.lastQuestion)
}
if err := q.validate(s, m); err != nil {
// In case validate fails with user error, we want to be able to retry,
// so we return c to be a new command.
return c, err
}
q.answer = m.Text
var next *question = nil
for _, qe := range c.questions {
if qe.answer == "" {
next = qe
break
}
}
if next == nil {
err := c.save(s, m.Chat.Id, c.questions)
// After all questions have been answered there is no point in
// keeping trying to save, even if it fails with UserError.
return nil, err
}
if err := next.ask(s, m.Chat.Id); err != nil {
// ask should never fail with user error.
return nil, err
}
c.lastQuestion = next.name
return c, nil
}
func ReplyCommand(reply func(s *State, chatID int64) error) CommandFactory {
return MultiQuestionCommandFactory(
nil,
func(s *State, chatID int64, _ []*question) error {
return reply(s, chatID)
},
)
}
func NewMessageReply(chatID int64, text string, callbacks []Callback) *MessageReply {
var ik []*InlineKeyboard
for _, c := range callbacks {
ik = append(ik, c.AsInlineKeyboard())
}
var rm *ReplyMarkup
if len(ik) > 0 {
rm = &ReplyMarkup{
InlineKeyboard: [][]*InlineKeyboard{ik},
}
}
return &MessageReply{
ChatId: chatID,
Text: text,
ReplyMarkup: rm,
}
}
// practiceReply sends practice card to the user.
func practiceReply(s *State, chatID int64) error {
switch UsePractice {
case PracticeKnowledge:
default:
panic(fmt.Sprintf("INTERNAL: Unimplemented practice type: %v", UsePractice))
}
word, err := s.Repetitions.RepeatWord(chatID)
if err == sql.ErrNoRows {
// FIXME: Make this user error instead.
return s.Telegram.SendTextMessage(chatID, "No more rows to practice; exiting practice mode.")
}
if err != nil {
return fmt.Errorf("retrieving word for repetition: %w", err)
}
return s.Telegram.SendMessage(NewMessageReply(chatID, word, []Callback{KnowCallback{word}, DontKnowCallback{word, true}}))
}
// settingsReply sends current settings and instructions on how to change them.
func settingsReply(state *State, chatID int64) error {
s, err := state.Settings.Get(chatID)
if err != nil {
return err
}
var ls []string
for l, v := range s.TranslationLanguages {
if v {
ls = append(ls, fmt.Sprintf("%q", l))
}
}
sort.Strings(ls)
var cmds []string
for k, _ := range SettingsCommands {
cmds = append(cmds, " "+k)
}
sort.Strings(cmds)
msg := fmt.Sprintf(`
Current settings:
Input language: %q
Input language in ISO 639-3: %q
Translation languages in ISO 639-3: %s
Time Zone: %s
To modify settings use one of the commands below:
%s
`, s.InputLanguage, s.InputLanguageISO639_3, strings.Join(ls, ","), s.TimeZone, strings.Join(cmds, "\n"))
return state.Telegram.SendMessage(NewMessageReply(chatID, msg, nil))
}
// This inteface is a bit redundant. We need it though to avoid initialization
// loop with SettingsCommands depending on settingsReply and settingsReply
// depending on SettingsCommands.
type SimpleQuestionCommand interface {
Ask(_ *State, chatID int64) error
Validate(*State, *Message) error
Save(_ *State, chatID int64, answer string) error
}
func SimpleQuestionCommandFactory(c SimpleQuestionCommand) CommandFactory {
return MultiQuestionCommandFactory(
[]*question{{
name: "question",
ask: c.Ask,
validate: c.Validate,
}},
func(s *State, chatID int64, questions []*question) error {
return c.Save(s, chatID, questions[0].answer)
},
)
}
type SimpleSettingCommand struct {
question string
validate func(s *State, answer string) error
save func(s *State, chatID int64, answer string) error
}
func (c *SimpleSettingCommand) Ask(s *State, chatID int64) error {
return askQuestion(c.question)(s, chatID)
}
func (c *SimpleSettingCommand) Validate(s *State, m *Message) error {
if err := c.validate(s, m.Text); err != nil {
return UserError{ChatID: m.Chat.Id, Err: fmt.Errorf("%w. Please try again.", err)}
}
return nil
}
func (c *SimpleSettingCommand) Save(s *State, chatID int64, answer string) error {
if err := c.save(s, chatID, answer); err != nil {
return err
}
return settingsReply(s, chatID)
}
func askQuestion(q string) func(s *State, chatID int64) error {
return func(s *State, chatID int64) error {
return s.Telegram.SendTextMessage(chatID, q)
}
}
func AddCommandFactory() CommandFactory {
noopValidate := func(*State, *Message) error { return nil }
return MultiQuestionCommandFactory(
[]*question{{
name: "front",
ask: askQuestion("Enter front of the card (word, expression, question)."),
validate: noopValidate,
}, {
name: "back",
ask: askQuestion("Enter back of the card (definition, answer)."),
validate: noopValidate,
}},
func(s *State, chatID int64, qs []*question) error {
var front string
var back string
for _, q := range qs {
switch q.name {
case "front":
front = q.answer
case "back":
back = q.answer
default:
return fmt.Errorf("unexpected question in save: %v", q)
}
}
if err := s.Repetitions.Save(chatID, front, back); err != nil {
return err
}
return s.Telegram.SendTextMessage(chatID, fmt.Sprintf("Added %q for learning!", front))
},
)
}
func DeleteCommandFactory() CommandFactory {
return MultiQuestionCommandFactory(
[]*question{{
name: "word",
ask: askQuestion("Enter the word you want to delete from learning!"),
validate: func(s *State, m *Message) error {
e, err := s.Repetitions.Exists(m.Chat.Id, m.Text)
if err != nil {
return err
}
if !e {
return UserError{ChatID: m.Chat.Id, Err: fmt.Errorf("Word %q isn't saved for learning!", m.Text)}
}
return nil
},
}},
func(s *State, chatID int64, qs []*question) error {
if err := s.Repetitions.Delete(chatID, qs[0].answer); err != nil {
return err
}
return s.Telegram.SendTextMessage(chatID, fmt.Sprintf("Deleted %q!", qs[0].answer))
},
)
}
type defaultCommand struct{}
func (defaultCommand) Serialize() *SerializedCommand {
return nil
}
func (defaultCommand) Init(*SerializedCommand) error {
return nil
}
func (defaultCommand) ProcessMessage(s *State, m *Message) (Command, error) {
chatID := m.Chat.Id
if len(strings.Split(m.Text, " ")) > 1 {
return nil, UserError{ChatID: chatID, Err: fmt.Errorf("For now this bot doesn't work with expressions. Try entering a single work without spaces.")}
}
def, err := s.Repetitions.GetDefinition(m.Chat.Id, m.Text)
if err == nil {
return nil, s.Telegram.SendMessage(NewMessageReply(
m.Chat.Id, def,
[]Callback{ResetProgressCallback{m.Text}}))
}
if err != sql.ErrNoRows {
log.Printf("ERROR: Repetitions(%d, %s): %v", m.Chat.Id, m.Text, err)
}
settings, err := s.Settings.Get(chatID)
if err != nil {
return nil, fmt.Errorf("get settings: %v", err)
}
ds, err := s.Definer.Define(m.Text, settings)
if err != nil {
// TODO: Might be good to post debug logs to the reply in the debug mode.
log.Printf("Error fetching the definition: %w", err)
// TODO: Add search url to the reply?
return nil, UserError{
ChatID: m.Chat.Id,
Err: fmt.Errorf("Couldn't find definitions."),
}
}
for _, d := range ds {
if err := s.Telegram.SendMessage(&MessageReply{
ChatId: m.Chat.Id,
Text: d,
ParseMode: "MarkdownV2",
ReplyMarkup: &ReplyMarkup{
InlineKeyboard: [][]*InlineKeyboard{[]*InlineKeyboard{
LearnCallback{m.Text}.AsInlineKeyboard(),
}},
},
}); err != nil {
return nil, err
}
}
return nil, nil
}
// Should never be called.
func (defaultCommand) OnCommand(*State, *Message) (Command, error) {
return nil, nil
}
func joinCommands(m1, m2 map[string]CommandFactory) map[string]CommandFactory {
r := make(map[string]CommandFactory)
for k, v := range m1 {
if _, dup := m2[k]; dup {
panic(fmt.Sprintf("Found duplicated command: %q", k))
}
r[k] = v
}
for k, v := range m2 {
// There can be no additional duplications so no need to check it.
r[k] = v
}
return r
}
// textReply sends a message and resets state.
func textReply(text string) CommandFactory {
return ReplyCommand(func(s *State, chatID int64) error {
return s.Telegram.SendTextMessage(chatID, text)
})
}
// SettingsCommands contains all settings-related commands. They are bundled
// together for convenience to have everything in one place.
var SettingsCommands = map[string]CommandFactory{
"/language": SimpleQuestionCommandFactory(&SimpleSettingCommand{
question: func() string {
var ls []string
for l, _ := range SupportedInputLanguages {
ls = append(ls, fmt.Sprintf("%q", l))
}
sort.Strings(ls)
return fmt.Sprintf("Enter input language of your choice. Supported are %s",
strings.Join(ls, ","))
}(),
validate: func(s *State, answer string) error {
return s.Settings.ValidateLanguage(answer)
},
save: func(s *State, chatID int64, answer string) error {
return s.Settings.SetLanguage(chatID, answer)
},
}),
"/timezone": SimpleQuestionCommandFactory(&SimpleSettingCommand{
question: "Input your timezone in one of the formats: UTC, UTC+X or UTC-X.",
validate: func(s *State, answer string) error {
return s.Settings.ValidateTimeZone(answer)
},
save: func(s *State, chatID int64, answer string) error {
return s.Settings.SetTimeZone(chatID, answer)
},
}),
}
var CommandsTemplate = struct {
// When receiving a callback it will be matched here.
// Tests should test that each callback is reachable.
// Callbacks can rely only on info got from the CallbackQuery,
// Everything stored in callback should be used only in AsInlineKeyboard method.
Callbacks []Callback
// Each key in the map should directly correspond to the name of the command.
// Possible improvement would be to allow regexps in the Commands name so
// arguments can be passed there.
Commands map[string]CommandFactory
// Command returned by DefaultCommand shouldn't implement OnCommand. It
// should not be ever called.
DefaultCommand CommandFactory
}{
Commands: joinCommands(
map[string]CommandFactory{
"/start": textReply(
"Welcome to the language bot. Still in development. No instructions " +
"so far. " +
"All sentences and translations are from Tatoeba's (https://tatoeba.org) " +
"dataset, released under a CC-BY 2.0 FR."),
"/stop": textReply("Stopped. Input the word to get it's definition."),
"/practice": ReplyCommand(practiceReply),
"/settings": ReplyCommand(settingsReply),
"/add": AddCommandFactory(),
"/delete": DeleteCommandFactory(),
},
SettingsCommands,
),
Callbacks: []Callback{
KnowCallback{},
DontKnowCallback{},
LearnCallback{},
},
DefaultCommand: func(string) Command { return defaultCommand{} },
}