/
tbcomctl.go
396 lines (327 loc) · 9.96 KB
/
tbcomctl.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
// Package tbcomctl provides common controls for telegram bots.
//
package tbcomctl
import (
"context"
"crypto/sha1"
"fmt"
"strconv"
"sync"
"time"
"golang.org/x/text/language"
"github.com/google/uuid"
tb "gopkg.in/tucnak/telebot.v3"
)
const (
FallbackLang = "en-US"
)
const (
unknown = "[unknown]"
)
// Controller is the interface that some of the common controls implement. Controllers can
// be chained together
type Controller interface {
// Handler is the controller's message handler.
Handler(c tb.Context) error
// Name returns the name of the control assigned to it on creation. When
// Controller is a part of a form, one can call Form.Controller(name) method
// to get the controller.
Name() string
// SetNext sets the next handler, when control is part of a form.
SetNext(Controller)
// SetPrev sets the previous handler.
SetPrev(Controller)
// SetForm assigns the form to the controller, this will allow controller to
// address other controls in a form by name.
SetForm(*Form)
// Form returns the form associated with the controller.
Form() *Form
// Value returns the value stored in the controller for the recipient.
Value(recipient string) (string, bool)
// OutgoingID should return the value of the outgoing message ID for the
// user and true if the message is present or false otherwise.
OutgoingID(recipient string) (int, bool)
}
type overwriter interface {
setOverwrite(b bool)
}
type commonCtl struct {
// b Boter
name string // name of the control, must be unique if used within chained controls
prev Controller
next Controller
form *Form // if not nil, controller is part of the form.
textFn TextFunc
errFn ErrFunc
privateOnly bool
overwrite bool // overwrite the previous message sent by control.
reqCache map[string]map[int]uuid.UUID // requests cache, maps message ID to request.
await map[string]int // await maps userID to the messageID and indicates that we're waiting for user to reply.
values map[string]string // values entered, maps userID to the value
messages map[string]int // messages sent, maps userID to the message_id
mu sync.RWMutex
lang string
}
// PrivateOnly is the middleware that restricts the handler to only private
// messages.
func PrivateOnly(fn tb.HandlerFunc) tb.HandlerFunc {
return PrivateOnlyMsg("", fn)
}
func PrivateOnlyMsg(msg string, fn tb.HandlerFunc) tb.HandlerFunc {
return func(c tb.Context) error {
if !c.Message().Private() {
if msg != "" {
pr := Printer(c.Sender().LanguageCode)
c.Send(pr.Sprintf(msg))
}
return nil
}
return fn(c)
}
}
type controllerKey int
var ctrlKey controllerKey
func WithController(ctx context.Context, ctrl Controller) context.Context {
return context.WithValue(ctx, ctrlKey, ctrl)
}
func ControllerFromCtx(ctx context.Context) (Controller, bool) {
ctrl, ok := ctx.Value(ctrlKey).(Controller)
return ctrl, ok
}
type StoredMessage struct {
MessageID string
ChatID int64
}
func (m StoredMessage) MessageSig() (string, int64) {
return m.MessageID, m.ChatID
}
// ValuesFunc returns values for inline buttons, possibly personalised for user u.
type ValuesFunc func(ctx context.Context, u *tb.User) ([]string, error)
// TextFunc returns formatted text, possibly personalised for user u.
type TextFunc func(ctx context.Context, u *tb.User) (string, error)
// MiddlewareFunc is the function that wraps a telebot handler and returns a handler.
type MiddlewareFunc func(tb.HandlerFunc) tb.HandlerFunc
// ErrFunc is the error processing function.
type ErrFunc func(ctx context.Context, m *tb.Message, err error)
// BtnCallbackFunc is being called once the user picks the value, it should return error if the value is incorrect, or
// ErrRetry if the retry should be performed.
type BtnCallbackFunc func(ctx context.Context, c tb.Context) error
var hasher = sha1.New
func hash(s string) string {
h := hasher()
h.Write([]byte(s))
return fmt.Sprintf("%x", h.Sum(nil))
}
type option func(ctl *commonCtl)
func optPrivateOnly(b bool) option {
return func(ctl *commonCtl) {
ctl.privateOnly = b
}
}
func optErrFunc(fn ErrFunc) option {
return func(ctl *commonCtl) {
ctl.errFn = fn
}
}
func optFallbackLang(lang string) option {
return func(ctl *commonCtl) {
_ = language.MustParse(lang) // will panic if wrong.
ctl.lang = lang
}
}
// newCommonCtl creates a new commonctl instance.
func newCommonCtl(name string, textFn TextFunc) commonCtl {
return commonCtl{
name: name,
textFn: textFn,
messages: make(map[string]int),
}
}
// register registers message in cache assigning it a request id.
func (c *commonCtl) register(r tb.Recipient, msgID int) uuid.UUID {
c.mu.Lock()
defer c.mu.Unlock()
c.requestEnsure(r)
reqID := uuid.Must(uuid.NewUUID())
c.reqCache[r.Recipient()][msgID] = reqID
c.messages[r.Recipient()] = msgID
return reqID
}
// requestEnsure ensures that request cache is initialised.
func (c *commonCtl) requestEnsure(r tb.Recipient) {
if c.reqCache == nil {
c.reqCache = make(map[string]map[int]uuid.UUID)
}
if c.reqCache[r.Recipient()] == nil {
c.reqCache[r.Recipient()] = make(map[int]uuid.UUID)
}
}
// requestFor returns a request id for message ID and a bool. Bool will be true if
// message is registered and false otherwise.
func (c *commonCtl) requestFor(r tb.Recipient, msgID int) (uuid.UUID, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
c.requestEnsure(r)
reqID, ok := c.reqCache[r.Recipient()][msgID]
return reqID, ok
}
// unregister unregisters the request from cache.
func (c *commonCtl) unregister(r tb.Recipient, msgID int) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.reqCache[r.Recipient()], msgID)
}
// reqIDInfo returns a request ID (or <unknown) and a time of the request (or zero time).
func (c *commonCtl) reqIDInfo(r tb.Recipient, msgID int) (string, time.Time) {
reqID, ok := c.requestFor(r, msgID)
if !ok {
return unknown, time.Time{}
}
return reqID.String(), time.Unix(reqID.Time().UnixTime())
}
// multibuttonMarkup returns a markup containing a bunch of buttons. If
// showCounter is true, will show a counter beside each of the labels. each
// telegram button will have a button index pressed by the user in the
// callback.Data. Prefix is the prefix that will be prepended to the unique
// before hash is called to form the Control-specific unique fields.
func (c *commonCtl) multibuttonMarkup(b *tb.Bot, btns []Button, showCounter bool, prefix string, cbFn func(tb.Context) error) *tb.ReplyMarkup {
const (
sep = ": "
)
if cbFn == nil {
panic("internal error: callback function is empty")
}
markup := new(tb.ReplyMarkup)
var buttons []tb.Btn
for i, ri := range btns {
bn := markup.Data(ri.label(showCounter, sep), hash(prefix+ri.Name), strconv.Itoa(i))
buttons = append(buttons, bn)
b.Handle(&bn, cbFn)
}
markup.Inline(organizeButtons(buttons, defNumButtons)...)
return markup
}
// SetNext sets next controller in the chain.
func (c *commonCtl) SetNext(ctrl Controller) {
if ctrl != nil {
c.next = ctrl
}
}
// SetPrev sets the previous controller in the chain.
func (c *commonCtl) SetPrev(ctrl Controller) {
if ctrl != nil {
c.prev = ctrl
}
}
func NewControllerChain(first Controller, cc ...Controller) tb.HandlerFunc {
var chain Controller
for i := len(cc) - 1; i >= 0; i-- {
cc[i].SetNext(chain)
chain = cc[i]
}
first.SetNext(chain)
return first.Handler
}
// Value returns the Controller value for the recipient.
func (c *commonCtl) Value(recipient string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
if c.values == nil {
c.values = make(map[string]string)
}
v, ok := c.values[recipient]
return v, ok
}
// SetValue sets the Controller value.
func (c *commonCtl) SetValue(recipient string, value string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.values == nil {
c.values = make(map[string]string)
}
c.values[recipient] = value
}
//
// waiting function
//
// waitFor places the outbound message ID to the waiting list. Message ID in
// outbound waiting list means that we expect the user to respond.
func (c *commonCtl) waitFor(r tb.Recipient, outboundID int) {
c.mu.Lock()
defer c.mu.Unlock()
if c.await == nil {
c.await = make(map[string]int)
}
c.await[r.Recipient()] = outboundID
}
func (c *commonCtl) stopWaiting(r tb.Recipient) int {
outboundID := c.await[r.Recipient()]
c.await[r.Recipient()] = nothing
return outboundID
}
func (c *commonCtl) outboundID(r tb.Recipient) int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.await[r.Recipient()]
}
func (c *commonCtl) isWaiting(r tb.Recipient) bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.await[r.Recipient()] != nothing
}
func (c *commonCtl) Name() string {
return c.name
}
func (c *commonCtl) SetForm(fm *Form) {
c.form = fm
}
func (c *commonCtl) Form() *Form {
return c.form
}
// OutgoingID returns the controller's outgoing message ID for the user.
func (c *commonCtl) OutgoingID(recipient string) (int, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
id, ok := c.messages[recipient]
return id, ok
}
// TextFn wraps the message in a TextFunc.
func TextFn(msg string) TextFunc {
return func(ctx context.Context, u *tb.User) (string, error) {
return msg, nil
}
}
func (c *commonCtl) setOverwrite(b bool) {
c.overwrite = b
}
func (c *commonCtl) sendOrEdit(ct tb.Context, txt string, sendOpts ...interface{}) (*tb.Message, error) {
var outbound *tb.Message
var err error
msgID, ok := c.getPreviousMsgID(ct)
if c.overwrite && ok {
prevMsg := tb.Message{ID: msgID, Chat: ct.Chat()}
outbound, err = ct.Bot().Edit(&prevMsg,
txt,
sendOpts...,
)
} else {
outbound, err = ct.Bot().Send(ct.Chat(), txt, sendOpts...)
}
return outbound, err
}
func (c *commonCtl) getPreviousMsgID(ct tb.Context) (int, bool) {
backPressed, ok := ct.Get(BackPressed.Error()).(bool)
if ok && backPressed {
ct.Set(BackPressed.Error(), false) // reset the context value
if c.next == nil {
// internal error
return 0, false
}
return c.next.OutgoingID(ct.Sender().Recipient())
}
// back not pressed
if c.prev == nil {
return 0, false
}
return c.prev.OutgoingID(ct.Sender().Recipient())
}