/
bot.go
159 lines (142 loc) · 4.24 KB
/
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
package bot
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"go.uber.org/zap"
"github.com/nikmy/locky/internal/workerpool"
)
func Run(ctx context.Context, log *zap.SugaredLogger, storage storage, token string) <-chan struct{} {
log.Debug("launching bot...")
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
log.Fatalf("cannot create bot API: %s", err)
}
log.Debug("successfully connected to telegram API")
var updates tgbotapi.UpdatesChannel
if webhook := os.Getenv("WEBHOOK"); webhook != "" {
updates = fromWebhook(log, bot, webhook)
} else {
_, _ = bot.Request(tgbotapi.WebhookConfig{})
u := tgbotapi.NewUpdate(0)
u.Timeout = updateTimeout
updates = bot.GetUpdatesChan(u)
}
log.Debug("listen for updates...")
return workerpool.New[tgbotapi.Update]().
WithMaxGoroutines(nWorkers).
WithContext(ctx).
WithHandler(runner(ctx, log, bot, storage)).
Range(updates).
Await()
}
func runner(ctx context.Context, log *zap.SugaredLogger, bot *tgbotapi.BotAPI, storage storage) func(update tgbotapi.Update) {
badCommand := func(update tgbotapi.Update) {
telegramAPIRequest(log, bot, tgbotapi.NewMessage(update.Message.Chat.ID, "I don't understand :("))
}
return func(update tgbotapi.Update) {
log.Debug("update has been received")
if update.Message == nil || len(update.Message.Text) == 0 {
badCommand(update)
return
}
split := strings.Split(update.Message.Text, " ")
cmd, args := split[0], split[1:]
switch cmd {
case "/start":
telegramAPIRequest(log, bot, tgbotapi.NewMessage(update.Message.Chat.ID, helloMessage))
case "/get":
if len(args) != 1 {
badCommand(update)
return
}
login, password, err := storage.Get(ctx, update.Message.From.ID, args[0])
if err != nil {
if errors.As(err, &sql.ErrNoRows) {
telegramAPIRequest(log, bot, tgbotapi.NewMessage(update.Message.Chat.ID, "no matches found"))
return
}
log.Error(storageAPIError("Get", err))
return
}
m := tgbotapi.NewMessage(update.Message.Chat.ID, fmtCreds(login, password))
m.ParseMode = "MarkdownV2"
msg, err := bot.Send(m)
if err != nil {
log.Errorf("cannot send message: %s", err)
}
go func() {
select {
case <-ctx.Done():
return
case <-time.After(20 * time.Second): // TODO: timer pool
}
telegramAPIRequest(log, bot, tgbotapi.NewDeleteMessage(msg.Chat.ID, msg.MessageID))
}()
case "/set":
if len(args) != 3 {
badCommand(update)
return
}
err := storage.Set(ctx, update.Message.From.ID, args[0], args[1], args[2])
if err != nil {
log.Error(storageAPIError("Set", err))
return
}
telegramAPIRequest(log, bot, tgbotapi.NewMessage(update.Message.Chat.ID, "saved."))
case "/del":
if len(args) != 1 {
badCommand(update)
return
}
err := storage.Del(ctx, update.Message.From.ID, args[0])
if err != nil {
if errors.As(err, &sql.ErrNoRows) {
telegramAPIRequest(log, bot, tgbotapi.NewMessage(update.Message.Chat.ID, "no matches found"))
return
}
log.Error(storageAPIError("Del", err))
return
}
telegramAPIRequest(log, bot, tgbotapi.NewMessage(update.Message.Chat.ID, "ok"))
default:
badCommand(update)
}
}
}
func fromWebhook(log *zap.SugaredLogger, bot *tgbotapi.BotAPI, webhook string) tgbotapi.UpdatesChannel {
log.Debug("setting up webhook...")
wh, err := tgbotapi.NewWebhook(webhook + bot.Token)
if err != nil {
log.Fatalf("cannot init webhook: %s", err)
}
_, err = bot.Request(wh)
if err != nil {
log.Fatalf("cannot init webhook: %s", err)
}
info, err := bot.GetWebhookInfo()
if err != nil {
log.Fatalf("cannot get webhook info: %s", err)
}
if info.LastErrorMessage != "" {
log.Errorf("webhook error: %s", info.LastErrorMessage)
}
return bot.ListenForWebhook("/" + bot.Token)
}
func telegramAPIRequest(log *zap.SugaredLogger, bot *tgbotapi.BotAPI, c tgbotapi.Chattable) {
_, err := bot.Request(c)
if err != nil {
log.Errorf("telegram API error: %s", err)
}
}
func fmtCreds(login, password string) string {
return fmt.Sprintf("login: `%s`\npassword: `%s`", login, password)
}
func storageAPIError(method string, err error) error {
return fmt.Errorf("storage API error: %s: %w", method, err)
}