-
Notifications
You must be signed in to change notification settings - Fork 5
/
sender.go
84 lines (77 loc) · 1.42 KB
/
sender.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
package bots
import (
"fmt"
"go.uber.org/zap"
tb "gopkg.in/tucnak/telebot.v2"
"strconv"
"sync"
)
type Sender struct {
done chan struct{}
in chan *Msg
wg sync.WaitGroup
}
type Msg struct {
To tb.Recipient
What interface{}
Options []interface{}
}
func NewSender() *Sender {
return &Sender{}
}
func (s *Sender) Init(goroutine int) {
s.done = make(chan struct{})
s.in = make(chan *Msg)
for i := 0; i < goroutine; i++ {
go func() {
s.sender()
}()
}
}
func (s *Sender) Stop() {
s.wg.Wait()
close(s.done)
fmt.Println("task finished")
}
func (s *Sender) SendMessageByID(ID int64, what interface{}, options ...interface{}) {
s.wg.Add(1)
go func() {
chat, err := bot.ChatByID(strconv.FormatInt(ID, 10))
if err != nil {
zap.S().Errorw("failed to get chat",
"error", err,
"id", ID,
)
s.wg.Done()
return
}
s.SendMessage(chat, what, options...)
}()
}
func (s *Sender) SendMessage(to tb.Recipient, what interface{}, options ...interface{}) {
s.in <- &Msg{
To: to,
What: what,
Options: options,
}
}
func (s *Sender) sender() {
for {
select {
case msg, f := <-s.in:
if !f {
continue
}
fmt.Println("send to " + msg.To.Recipient())
if _, err := bot.Send(msg.To, msg.What, msg.Options...); err != nil {
zap.S().Errorw("failed to send msg",
"error", err,
"id", msg.To.Recipient(),
)
}
s.wg.Done()
case <-s.done:
return
}
}
}