-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
618 lines (527 loc) · 16.7 KB
/
context.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
package crare
import (
"errors"
"strings"
"time"
"github.com/cornelk/hashmap"
)
// Context wraps an update and represents the context of current event.
type Context interface {
// Bot returns the bot instance.
Bot() *Bot
// Update returns the original update.
Update() Update
// Message returns stored message if such presented.
Message() *Message
// Callback returns stored callback if such presented.
Callback() *Callback
// Query returns stored query if such presented.
Query() *Query
// InlineResult returns stored inline result if such presented.
InlineResult() *InlineResult
// ShippingQuery returns stored shipping query if such presented.
ShippingQuery() *ShippingQuery
// PreCheckoutQuery returns stored pre checkout query if such presented.
PreCheckoutQuery() *PreCheckoutQuery
// Poll returns stored poll if such presented.
Poll() *Poll
// PollAnswer returns stored poll answer if such presented.
PollAnswer() *PollAnswer
// ChatMember returns chat member changes.
ChatMember() *ChatMemberUpdate
// ChatJoinRequest returns the chat join request.
ChatJoinRequest() *ChatJoinRequest
// Migration returns both migration from and to chat IDs.
Migration() (int64, int64)
// Sender returns the current recipient, depending on the context type.
// Returns nil if user is not presented.
Sender() *User
// Chat returns the current chat, depending on the context type.
// Returns nil if chat is not presented.
Chat() *Chat
// Recipient combines both Sender and Chat functions. If there is no user
// the chat will be returned. The native context cannot be without sender,
// but it is useful in the case when the context created intentionally
// by the NewContext constructor and have only Chat field inside.
Recipient() Recipient
// Text returns the message text, depending on the context type.
// In the case when no related data presented, returns an empty string.
Text() string
// Entities returns the message entities, whether it's media caption's or the text's.
// In the case when no entities presented, returns a nil.
Entities() Entities
// Data returns the current data, depending on the context type.
// If the context contains command, returns its arguments string.
// If the context contains payment, returns its payload.
// In the case when no related data presented, returns an empty string.
Data() string
// Args returns a raw slice of command or callback arguments as strings.
// The message arguments split by space, while the callback's ones by a "|" symbol.
Args() []string
// Send sends a message to the current recipient.
// See Send from bot.go.
Send(what any, opts ...any) (*Message, error)
// SendAlbum sends an album to the current recipient.
// See SendAlbum from bot.go.
SendAlbum(a Album, opts ...any) error
// Reply replies to the current message.
// See Reply from bot.go.
Reply(what any, opts ...any) (*Message, error)
// Forward forwards the given message to the current recipient.
// See Forward from bot.go.
Forward(msg Editable, opts ...any) error
// ForwardTo forwards the current message to the given recipient.
// See Forward from bot.go
ForwardTo(to Recipient, opts ...any) error
// Edit edits the current message.
// See Edit from bot.go.
Edit(what any, opts ...any) error
// EditCaption edits the caption of the current message.
// See EditCaption from bot.go.
EditCaption(caption string, opts ...any) error
// EditOrSend edits the current message if the update is callback,
// otherwise the content is sent to the chat as a separate message.
EditOrSend(what any, opts ...any) error
// EditOrReply edits the current message if the update is callback,
// otherwise the content is replied as a separate message.
EditOrReply(what any, opts ...any) (*Message, error)
// Delete removes the current message.
// See Delete from bot.go.
Delete() error
// DeleteAfter waits for the duration to elapse and then removes the
// message. It handles an error automatically using b.OnError callback.
// It returns a Timer that can be used to cancel the call using its Stop method.
DeleteAfter(d time.Duration) *time.Timer
// Notify updates the chat action for the current recipient.
// See Notify from bot.go.
Notify(action ChatAction) error
// Ship replies to the current shipping query.
// See Ship from bot.go.
Ship(what ...any) error
// Accept finalizes the current deal.
// See Accept from bot.go.
Accept(errorMessage ...string) error
// Answer sends a response to the current inline query.
// See Answer from bot.go.
Answer(resp *QueryResponse) error
// Respond sends a response for the current callback query.
// See Respond from bot.go.
Respond(resp ...*CallbackResponse) error
// Get retrieves data from the context.
Get(key string) any
// Set saves data in the context.
Set(key string, val any)
// Release Context
ReleaseContext()
// Next pass control to the next middleware/ctx function.
Next() error
// Next pass control to the next middleware/ctx function.
Done() error
// Determine whether the function can continue to run
NextStatus() bool
// Determine whether the function can continue to run
SetNextStatus(b bool)
}
// nativeContext is a native implementation of the Context interface.
// "context" is taken by context package, maybe there is a better name.
type nativeContext struct {
b *Bot
u Update
next bool
store *hashmap.Map[string, any]
}
// Bot returns the bot instance.
func (c *nativeContext) Bot() *Bot {
return c.b
}
// Update returns the original update.
func (c *nativeContext) Update() Update {
return c.u
}
// Message returns stored message if such presented.
func (c *nativeContext) Message() *Message {
switch {
case c.u.Message != nil:
return c.u.Message
case c.u.Callback != nil:
return c.u.Callback.Message
case c.u.EditedMessage != nil:
return c.u.EditedMessage
case c.u.ChannelPost != nil:
if c.u.ChannelPost.PinnedMessage != nil {
return c.u.ChannelPost.PinnedMessage
}
return c.u.ChannelPost
case c.u.EditedChannelPost != nil:
return c.u.EditedChannelPost
default:
return nil
}
}
// Callback returns stored callback if such presented.
func (c *nativeContext) Callback() *Callback {
return c.u.Callback
}
// Query returns stored query if such presented.
func (c *nativeContext) Query() *Query {
return c.u.Query
}
// InlineResult returns stored inline result if such presented.
func (c *nativeContext) InlineResult() *InlineResult {
return c.u.InlineResult
}
// ShippingQuery returns stored shipping query if such presented.
func (c *nativeContext) ShippingQuery() *ShippingQuery {
return c.u.ShippingQuery
}
// PreCheckoutQuery returns stored pre checkout query if such presented.
func (c *nativeContext) PreCheckoutQuery() *PreCheckoutQuery {
return c.u.PreCheckoutQuery
}
// ChatMember returns chat member changes.
func (c *nativeContext) ChatMember() *ChatMemberUpdate {
switch {
case c.u.ChatMember != nil:
return c.u.ChatMember
case c.u.MyChatMember != nil:
return c.u.MyChatMember
default:
return nil
}
}
// ChatJoinRequest returns chat member join request.
func (c *nativeContext) ChatJoinRequest() *ChatJoinRequest {
return c.u.ChatJoinRequest
}
// Poll returns stored poll if such presented.
func (c *nativeContext) Poll() *Poll {
return c.u.Poll
}
// PollAnswer returns stored poll answer if such presented.
func (c *nativeContext) PollAnswer() *PollAnswer {
return c.u.PollAnswer
}
// Migration returns both migration from and to chat IDs.
func (c *nativeContext) Migration() (int64, int64) {
return c.u.Message.MigrateFrom, c.u.Message.MigrateTo
}
func (c *nativeContext) Topic() *Topic {
m := c.u.Message
if m == nil {
return nil
}
switch {
case m.TopicCreated != nil:
return m.TopicCreated
case m.TopicReopened != nil:
return m.TopicReopened
case m.TopicEdited != nil:
return m.TopicEdited
}
return nil
}
// Sender returns the current recipient, depending on the context type.
// Returns nil if user is not presented.
func (c *nativeContext) Sender() *User {
switch {
case c.u.Callback != nil:
return c.u.Callback.Sender
case c.Message() != nil:
return c.Message().Sender
case c.u.Query != nil:
return c.u.Query.Sender
case c.u.InlineResult != nil:
return c.u.InlineResult.Sender
case c.u.ShippingQuery != nil:
return c.u.ShippingQuery.Sender
case c.u.PreCheckoutQuery != nil:
return c.u.PreCheckoutQuery.Sender
case c.u.PollAnswer != nil:
return c.u.PollAnswer.Sender
case c.u.MyChatMember != nil:
return c.u.MyChatMember.Sender
case c.u.ChatMember != nil:
return c.u.ChatMember.Sender
case c.u.ChatJoinRequest != nil:
return c.u.ChatJoinRequest.Sender
default:
return nil
}
}
// Chat returns the current chat, depending on the context type.
// Returns nil if chat is not presented.
func (c *nativeContext) Chat() *Chat {
switch {
case c.Message() != nil:
return c.Message().Chat
case c.u.MyChatMember != nil:
return c.u.MyChatMember.Chat
case c.u.ChatMember != nil:
return c.u.ChatMember.Chat
case c.u.ChatJoinRequest != nil:
return c.u.ChatJoinRequest.Chat
default:
return nil
}
}
// Recipient combines both Sender and Chat functions. If there is no user
// the chat will be returned. The native context cannot be without sender,
// but it is useful in the case when the context created intentionally
// by the NewContext constructor and have only Chat field inside.
func (c *nativeContext) Recipient() Recipient {
chat := c.Chat()
if chat != nil {
return chat
}
return c.Sender()
}
// Text returns the message text, depending on the context type.
// In the case when no related data presented, returns an empty string.
func (c *nativeContext) Text() string {
m := c.Message()
if m == nil {
return ""
}
if m.Caption != "" {
return m.Caption
}
return m.Text
}
// Entities returns the message entities, whether it's media caption's or the text's.
// In the case when no entities presented, returns a nil.
func (c *nativeContext) Entities() Entities {
m := c.Message()
if m == nil {
return nil
}
if len(m.CaptionEntities) > 0 {
return m.CaptionEntities
}
return m.Entities
}
// Data returns the current data, depending on the context type.
// If the context contains command, returns its arguments string.
// If the context contains payment, returns its payload.
// In the case when no related data presented, returns an empty string.
func (c *nativeContext) Data() string {
switch {
case c.u.Message != nil:
return c.u.Message.Payload
case c.u.Callback != nil:
return c.u.Callback.Data
case c.u.Query != nil:
return c.u.Query.Text
case c.u.InlineResult != nil:
return c.u.InlineResult.Query
case c.u.ShippingQuery != nil:
return c.u.ShippingQuery.Payload
case c.u.PreCheckoutQuery != nil:
return c.u.PreCheckoutQuery.Payload
default:
return ""
}
}
// Args returns a raw slice of command or callback arguments as strings.
// The message arguments split by space, while the callback's ones by a "|" symbol.
func (c *nativeContext) Args() []string {
switch {
case c.u.Message != nil:
payload := strings.Trim(c.u.Message.Payload, " ")
if payload != "" {
return strings.Split(payload, " ")
}
case c.u.Callback != nil:
return strings.Split(c.u.Callback.Data, "|")
case c.u.Query != nil:
return strings.Split(c.u.Query.Text, " ")
case c.u.InlineResult != nil:
return strings.Split(c.u.InlineResult.Query, " ")
}
return nil
}
// Send sends a message to the current recipient.
// See Send from bot.go.
func (c *nativeContext) Send(what any, opts ...any) (*Message, error) {
e, err := c.b.Send(c.Recipient(), what, opts...)
return e, err
}
// SendAlbum sends an album to the current recipient.
// See SendAlbum from bot.go.
func (c *nativeContext) SendAlbum(a Album, opts ...any) error {
_, err := c.b.SendAlbum(c.Recipient(), a, opts...)
return err
}
// Reply replies to the current message.
// See Reply from bot.go.
func (c *nativeContext) Reply(what any, opts ...any) (*Message, error) {
msg := c.Message()
if msg == nil {
return nil, ErrBadContext
}
return c.b.Reply(msg, what, opts...)
}
// Forward forwards the given message to the current recipient.
// See Forward from bot.go.
func (c *nativeContext) Forward(msg Editable, opts ...any) error {
_, err := c.b.Forward(c.Recipient(), msg, opts...)
return err
}
// ForwardTo forwards the current message to the given recipient.
// See Forward from bot.go
func (c *nativeContext) ForwardTo(to Recipient, opts ...any) error {
msg := c.Message()
if msg == nil {
return ErrBadContext
}
_, err := c.b.Forward(to, msg, opts...)
return err
}
// Edit edits the current message.
// See Edit from bot.go.
func (c *nativeContext) Edit(what any, opts ...any) error {
if c.u.InlineResult != nil {
_, err := c.b.Edit(c.u.InlineResult, what, opts...)
return err
}
if c.u.Callback != nil {
_, err := c.b.Edit(c.u.Callback, what, opts...)
return err
}
return ErrBadContext
}
// EditCaption edits the caption of the current message.
// See EditCaption from bot.go.
func (c *nativeContext) EditCaption(caption string, opts ...any) error {
if c.u.InlineResult != nil {
_, err := c.b.EditCaption(c.u.InlineResult, caption, opts...)
return err
}
if c.u.Callback != nil {
_, err := c.b.EditCaption(c.u.Callback, caption, opts...)
return err
}
return ErrBadContext
}
// EditOrSend edits the current message if the update is callback,
// otherwise the content is sent to the chat as a separate message.
func (c *nativeContext) EditOrSend(what any, opts ...any) error {
err := c.Edit(what, opts...)
if err == ErrBadContext {
_, err := c.Send(what, opts...)
return err
}
return err
}
// EditOrReply edits the current message if the update is callback,
// otherwise the content is replied as a separate message.
func (c *nativeContext) EditOrReply(what any, opts ...any) (*Message, error) {
err := c.Edit(what, opts...)
if err == ErrBadContext {
return c.Reply(what, opts...)
}
return nil, err
}
// Delete removes the current message.
// See Delete from bot.go.
func (c *nativeContext) Delete() error {
msg := c.Message()
if msg == nil {
return ErrBadContext
}
return c.b.Delete(msg)
}
// DeleteAfter waits for the duration to elapse and then removes the
// message. It handles an error automatically using b.OnError callback.
// It returns a Timer that can be used to cancel the call using its Stop method.
func (c *nativeContext) DeleteAfter(d time.Duration) *time.Timer {
return time.AfterFunc(d, func() {
if err := c.Delete(); err != nil {
c.b.OnError(err, c)
}
})
}
// Determine whether the function can continue to run
func (c *nativeContext) NextStatus() bool {
return c.next
}
func (c *nativeContext) SetNextStatus(b bool) {
c.next = b
}
// Next pass control to the next middleware/ctx function.
func (c *nativeContext) Next() error {
c.next = true
return nil
}
// Next pass control to the next middleware/ctx function.
func (c *nativeContext) Done() error {
return nil
}
// Notify updates the chat action for the current recipient.
// See Notify from bot.go.
func (c *nativeContext) Notify(action ChatAction) error {
return c.b.Notify(c.Recipient(), action)
}
// Ship replies to the current shipping query.
// See Ship from bot.go.
func (c *nativeContext) Ship(what ...any) error {
if c.u.ShippingQuery == nil {
return errors.New("crare: context shipping query is nil")
}
return c.b.Ship(c.u.ShippingQuery, what...)
}
// Accept finalizes the current deal.
// See Accept from bot.go.
func (c *nativeContext) Accept(errorMessage ...string) error {
if c.u.PreCheckoutQuery == nil {
return errors.New("crare: context pre checkout query is nil")
}
return c.b.Accept(c.u.PreCheckoutQuery, errorMessage...)
}
// Respond sends a response for the current callback query.
// See Respond from bot.go.
func (c *nativeContext) Respond(resp ...*CallbackResponse) error {
if c.u.Callback == nil {
return errors.New("crare: context callback is nil")
}
return c.b.Respond(c.u.Callback, resp...)
}
// Answer sends a response to the current inline query.
// See Answer from bot.go.
func (c *nativeContext) Answer(resp *QueryResponse) error {
if c.u.Query == nil {
return errors.New("crare: context inline query is nil")
}
return c.b.Answer(c.u.Query, resp)
}
// Set saves data in the context.
func (c *nativeContext) Set(k string, v any) {
if c.store == nil {
c.store = hashmap.New[string, any]()
}
c.store.Set(k, v)
}
// Get retrieves data from the context.
func (c *nativeContext) Get(k string) any {
if c.store == nil {
c.store = hashmap.New[string, any]()
}
v, _ := c.store.Get(k)
return v
}
// Release the Context. After it is released,
// the previous Context should not be continued to be used.
func (n *nativeContext) ReleaseContext() {
if n == nil {
return
}
n.next = false
if n.store != nil {
n.store.Range(func(k string, v any) bool {
n.store.Del(k)
return true
})
}
n.b = nil
n.u = Update{}
ctxPool.Put(n)
}