-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
terentyev.go
98 lines (81 loc) · 2.15 KB
/
terentyev.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
package e2etest
import (
"context"
"time"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"golang.org/x/xerrors"
"github.com/gotd/td/telegram/internal/helpers"
"github.com/gotd/td/telegram/message"
"github.com/gotd/td/tg"
)
// User is a simple user bot.
type User struct {
suite *Suite
text []string
username string
logger *zap.Logger
message chan string
}
// NewUser creates new User bot.
func NewUser(suite *Suite, text []string, username string) User {
return User{
suite: suite,
text: text,
username: username,
logger: suite.Log.Named("terentyev"),
message: make(chan string, 1),
}
}
func (u User) messageHandler(ctx context.Context, entities tg.Entities, update *tg.UpdateNewMessage) error {
if filterMessage(update) {
return nil
}
if m, ok := update.Message.(interface{ GetMessage() string }); ok {
u.logger.Named("dispatcher").
Info("Got new message update", zap.String("message", m.GetMessage()))
}
msg, ok := update.Message.(*tg.Message)
if !ok {
return xerrors.Errorf("unexpected type %T", update.Message)
}
select {
case u.message <- msg.Message:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Run setups and starts user bot.
func (u User) Run(ctx context.Context) error {
dispatcher := tg.NewUpdateDispatcher()
dispatcher.OnNewMessage(u.messageHandler)
client := u.suite.Client(u.logger, dispatcher)
sender := message.NewSender(tg.NewClient(waitInvoker{prev: client}))
return client.Run(ctx, func(ctx context.Context) error {
if err := u.suite.RetryAuthenticate(ctx, client); err != nil {
return xerrors.Errorf("authenticate: %w", err)
}
peer, err := sender.Resolve(u.username).AsInputPeer(ctx)
if err != nil {
return xerrors.Errorf("resolve bot username %q: %w", u.username, err)
}
for _, line := range u.text {
time.Sleep(2 * time.Second)
_, err = sender.To(peer).Text(ctx, line)
if flood, err := helpers.FloodWait(ctx, err); err != nil {
if flood {
continue
}
return err
}
select {
case gotMessage := <-u.message:
require.Equal(u.suite.TB, line, gotMessage)
case <-ctx.Done():
return ctx.Err()
}
}
return nil
})
}