-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
47 lines (40 loc) · 1.07 KB
/
helper.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
package tele_prompt
import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
type Handler[T any] func() (T, error)
type SendMessageConfig[T any] struct {
InitialMessage tgbotapi.Chattable
OnErrorMessage tgbotapi.Chattable
OnMaxRetryMessage tgbotapi.Chattable
Handler Handler[T]
MaxRetry int
}
func SendMessage[T any](bot *tgbotapi.BotAPI, config SendMessageConfig[T]) (T, error) {
var t T
_, err := bot.Send(config.InitialMessage)
if err != nil {
return t, err
}
retryCount := 0
for {
t, err := config.Handler()
if err != nil {
// if OnErrorMessage is not set, SendMessage will not handle errors
if config.OnErrorMessage == nil {
return t, err
}
// if OnErrorMessage is set, SendMessage will retry
retryCount++
if config.MaxRetry > 0 && retryCount > config.MaxRetry {
if config.OnMaxRetryMessage != nil {
bot.Send(config.OnMaxRetryMessage)
}
return t, ErrMaxRetries
}
if _, err := bot.Send(config.OnErrorMessage); err != nil {
return t, err
}
continue
}
return t, nil
}
}