-
Notifications
You must be signed in to change notification settings - Fork 0
/
send.go
232 lines (186 loc) · 4.36 KB
/
send.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
package slogtelegram
import (
"context"
"fmt"
"iter"
"net/http"
"os"
"strings"
"sync"
"time"
"gopkg.in/telebot.v4"
)
var (
messageSeparator = "\n---\n"
messageMaxSize = 4096
)
type Sender interface {
Send(msg string) error
Close() error
}
type SenderOptions struct {
// Token is the Telegram bot token to send messages. It is required, please generate it from @BotFather.
Token string
// ChatID is the chat ID to send messages to (private, group or channel).
ChatID int64
// HTTPClient is the client used to send messages to the Telegram API.
HTTPClient *http.Client
// BaseURL is the Telegram API basic url to send messages.
BaseURL string
// BatchSize is the maximum number of messages to send in a single batch.
BatchSize uint64
// FlushInterval is the maximum duration to wait before sending a batch.
FlushInterval time.Duration
// Verbose specifies whether to print the Telegram API requests and responses.
Verbose bool
// Instance is a custom sender instance to use.
Instance Sender
}
func NewSender(opts SenderOptions) Sender {
if opts.Instance != nil {
return opts.Instance
}
if opts.Token == "" {
panic(fmt.Sprintf("%stoken is required", errPrefix))
}
if opts.ChatID == 0 {
panic(fmt.Sprintf("%schat ID is required", errPrefix))
}
if opts.HTTPClient == nil {
opts.HTTPClient = http.DefaultClient
}
client, err := telebot.NewBot(telebot.Settings{
URL: opts.BaseURL,
Token: opts.Token,
Verbose: opts.Verbose,
Client: opts.HTTPClient,
ParseMode: telebot.ModeHTML,
Offline: true,
})
if err != nil {
panic(fmt.Sprintf("%s%v", errPrefix, err))
}
sender := NewTelebotSender(client, opts.ChatID)
if opts.BatchSize == 0 && opts.FlushInterval == 0 {
return sender
}
return NewBatchSender(sender, opts.BatchSize, opts.FlushInterval)
}
type client interface {
Send(to telebot.Recipient, what any, opts ...any) (*telebot.Message, error)
}
type TelebotSender struct {
client client
chatID int64
}
func NewTelebotSender(client client, chatID int64) *TelebotSender {
return &TelebotSender{
client: client,
chatID: chatID,
}
}
func (s *TelebotSender) Send(msg string) error {
if _, err := s.client.Send(telebot.ChatID(s.chatID), msg); err != nil {
return err
}
return nil
}
func (s *TelebotSender) Close() error {
return nil
}
type BatchSender struct {
parent Sender
items []string
wg sync.WaitGroup
mutex sync.Mutex
batchSize uint64
flushInterval time.Duration
cancel func()
}
func NewBatchSender(parent Sender, batchSize uint64, flushInterval time.Duration) *BatchSender {
s := &BatchSender{
parent: parent,
items: make([]string, 0, batchSize),
batchSize: batchSize,
flushInterval: flushInterval,
}
ctx, cancel := context.WithCancel(context.Background())
s.cancel = cancel
s.wg.Add(1)
go func() {
defer s.wg.Done()
s.run(ctx)
}()
return s
}
func (s *BatchSender) Send(msg string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
s.items = append(s.items, msg)
if uint64(len(s.items)) >= s.batchSize {
s.wg.Add(1)
go func() {
defer s.wg.Done()
if err := s.flush(); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
}()
}
return nil
}
func (s *BatchSender) Close() error {
s.cancel()
s.wg.Wait()
return s.parent.Close()
}
func (s *BatchSender) run(ctx context.Context) {
ticker := time.NewTicker(s.flushInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
if err := s.flush(); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
return
case <-ticker.C:
if err := s.flush(); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
}
}
}
func (s *BatchSender) flush() error {
s.mutex.Lock()
if len(s.items) == 0 {
s.mutex.Unlock()
return nil
}
items := append([]string(nil), s.items...)
s.items = s.items[:0]
s.mutex.Unlock()
for chunk := range s.chunks(items) {
if err := s.parent.Send(chunk); err != nil {
return err
}
}
return nil
}
func (s *BatchSender) chunks(items []string) iter.Seq[string] {
return func(yield func(string) bool) {
var b strings.Builder
for _, item := range items {
if b.Len() > 0 && b.Len()+len(item)+len(messageSeparator) > messageMaxSize {
if !yield(b.String()) {
return
}
b.Reset()
}
b.WriteString(item)
b.WriteString(messageSeparator)
}
if b.Len() > 0 {
yield(b.String())
}
}
}