-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
echo_bot.go
196 lines (160 loc) · 4.15 KB
/
echo_bot.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
package e2etest
import (
"context"
"strconv"
"sync"
"github.com/cenkalti/backoff/v4"
"github.com/go-faster/errors"
"go.uber.org/zap"
"github.com/gotd/td/telegram"
"github.com/gotd/td/telegram/message"
"github.com/gotd/td/tg"
"github.com/gotd/td/tgerr"
)
// EchoBot is a simple echo message bot.
type EchoBot struct {
suite *Suite
logger *zap.Logger
auth chan<- *tg.User
}
// NewEchoBot creates new echo bot.
func NewEchoBot(suite *Suite, auth chan<- *tg.User) EchoBot {
return EchoBot{
suite: suite,
logger: suite.logger.Named("echobot"),
auth: auth,
}
}
type users struct {
users map[int64]*tg.User
lock sync.RWMutex
}
func newUsers() *users {
return &users{
users: map[int64]*tg.User{},
}
}
func (m *users) empty() (r bool) {
m.lock.RLock()
r = len(m.users) < 1
m.lock.RUnlock()
return
}
func (m *users) add(list ...tg.UserClass) {
m.lock.Lock()
defer m.lock.Unlock()
tg.UserClassArray(list).FillNotEmptyMap(m.users)
}
func (m *users) get(id int64) (r *tg.User) {
m.lock.RLock()
r = m.users[id]
m.lock.RUnlock()
return
}
func (b EchoBot) login(ctx context.Context, client *telegram.Client) (*tg.User, error) {
if err := b.suite.RetryAuthenticate(ctx, client.Auth()); err != nil {
return nil, errors.Wrap(err, "authenticate")
}
var me *tg.User
if err := retryFloodWait(ctx, func() (err error) {
me, err = client.Self(ctx)
return err
}); err != nil {
return nil, err
}
expectedUsername := "echobot" + strconv.FormatInt(me.ID, 10)
raw := tg.NewClient(waitInvoker{prev: client})
_, err := raw.AccountUpdateUsername(ctx, expectedUsername)
if err != nil {
if !tgerr.Is(err, tg.ErrUsernameNotModified) {
return nil, errors.Wrap(err, "update username")
}
}
if err := backoff.Retry(func() error {
me, err = client.Self(ctx)
if err != nil {
if ok, err := tgerr.FloodWait(ctx, err); ok {
return err
}
return backoff.Permanent(errors.Wrap(err, "get self"))
}
if me.Username != expectedUsername {
return errors.Errorf("expected username %q, got %q", expectedUsername, me.Username)
}
return nil
}, backoff.WithContext(backoff.NewExponentialBackOff(), ctx)); err != nil {
return nil, err
}
return me, nil
}
func (b EchoBot) handler(client *telegram.Client) tg.NewMessageHandler {
dialogsUsers := newUsers()
raw := tg.NewClient(client)
sender := message.NewSender(raw)
return func(ctx context.Context, entities tg.Entities, update *tg.UpdateNewMessage) error {
if filterMessage(update) {
return nil
}
if m, ok := update.Message.(interface{ GetMessage() string }); ok {
b.logger.Named("dispatcher").
Info("Got new message update", zap.String("message", m.GetMessage()))
}
if dialogsUsers.empty() {
dialogs, err := raw.MessagesGetDialogs(ctx, &tg.MessagesGetDialogsRequest{
Limit: 100,
OffsetPeer: &tg.InputPeerEmpty{},
})
if err != nil {
return errors.Wrap(err, "get dialogs")
}
if dlg, ok := dialogs.AsModified(); ok {
dialogsUsers.add(dlg.GetUsers()...)
}
}
switch m := update.Message.(type) {
case *tg.Message:
switch peer := m.PeerID.(type) {
case *tg.PeerUser:
user := entities.Users[peer.UserID]
if user == nil {
user = dialogsUsers.get(peer.UserID)
}
b.logger.Info("Got message",
zap.String("text", m.Message),
zap.Int64("user_id", user.ID),
zap.String("user_first_name", user.FirstName),
zap.String("username", user.Username),
)
if _, err := sender.To(user.AsInputPeer()).Text(ctx, m.Message); err != nil {
return errors.Wrap(err, "send message")
}
return nil
}
}
return nil
}
}
// Run setups and starts echo bot.
func (b EchoBot) Run(ctx context.Context) error {
dispatcher := tg.NewUpdateDispatcher()
client := b.suite.Client(b.logger, dispatcher)
dispatcher.OnNewMessage(b.handler(client))
return client.Run(ctx, func(ctx context.Context) error {
defer close(b.auth)
me, err := b.login(ctx, client)
if err != nil {
return errors.Wrap(err, "login")
}
b.logger.Info("Logged in",
zap.String("user", me.Username),
zap.Int64("id", me.ID),
)
select {
case b.auth <- me:
case <-ctx.Done():
return ctx.Err()
}
<-ctx.Done()
return nil
})
}