-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
bot.go
319 lines (258 loc) · 7.84 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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package telego
import (
"errors"
"fmt"
"reflect"
"regexp"
"strings"
"github.com/valyala/fasthttp"
"github.com/mymmrac/telego/internal/json"
ta "github.com/mymmrac/telego/telegoapi"
)
const (
defaultBotAPIServer = "https://api.telegram.org"
tokenRegexp = `^\d+:[\w-]{35}$` //nolint:gosec
attachFile = `attach://`
omitEmptySuffix = ",omitempty"
botPathPrefix = "/bot"
)
// ErrEmptyToken Bot token is empty
var ErrEmptyToken = errors.New("telego: empty token")
// ErrInvalidToken Bot token is invalid according to token regexp
var ErrInvalidToken = errors.New("telego: invalid token format")
// validateToken validates if token matches format
func validateToken(token string) bool {
reg := regexp.MustCompile(tokenRegexp)
return reg.MatchString(token)
}
// Bot represents Telegram bot
type Bot struct {
token string
apiURL string
log Logger
api ta.Caller
constructor ta.RequestConstructor
useTestServerPath bool
healthCheckRequested bool
reportWarningAsErrors bool
longPollingContext *longPollingContext
webhookContext *webhookContext
}
// BotOption represents an option that can be applied to Bot
type BotOption func(bot *Bot) error
// NewBot creates new bots with given options.
// If no options are specified, default values are used.
// Note: Default logger (that logs only errors if not configured) will hide your bot token, but it still may log
// sensitive information, it's only safe to use default logger in testing environment.
func NewBot(token string, options ...BotOption) (*Bot, error) {
if token == "" {
return nil, ErrEmptyToken
}
if !validateToken(token) {
return nil, ErrInvalidToken
}
b := &Bot{
token: token,
apiURL: defaultBotAPIServer,
log: newDefaultLogger(token),
api: ta.FastHTTPCaller{Client: &fasthttp.Client{}},
constructor: ta.DefaultConstructor{},
}
for _, option := range options {
if err := option(b); err != nil {
return nil, fmt.Errorf("telego: options: %w", err)
}
}
if b.healthCheckRequested {
if _, err := b.GetMe(); err != nil {
return nil, fmt.Errorf("telego: health check: %w", err)
}
}
return b, nil
}
// Token returns bot token
func (b *Bot) Token() string {
return b.token
}
// Logger returns bot logger
func (b *Bot) Logger() Logger {
return b.log
}
// FileDownloadURL returns URL used to download file by its file path retrieved from GetFile method
func (b *Bot) FileDownloadURL(filepath string) string {
if b.useTestServerPath {
return b.apiURL + "/file/bot" + b.token + "/test/" + filepath
}
return b.apiURL + "/file/bot" + b.token + "/" + filepath
}
// performRequest executes and parses response of method
func (b *Bot) performRequest(methodName string, parameters any, vs ...any) error {
resp, err := b.constructAndCallRequest(methodName, parameters)
if err != nil {
b.log.Errorf("Execution error %s: %s", methodName, err)
return fmt.Errorf("internal execution: %w", err)
}
b.log.Debugf("API response %s: %s", methodName, resp.String())
if !resp.Ok {
return fmt.Errorf("api: %w", resp.Error)
}
if resp.Result != nil {
var unmarshalErr error
for i := range vs {
unmarshalErr = json.Unmarshal(resp.Result, &vs[i])
if unmarshalErr == nil {
break
}
}
if unmarshalErr != nil {
return fmt.Errorf("unmarshal to %s: %w", reflect.TypeOf(vs[len(vs)-1]), unmarshalErr)
}
}
if b.reportWarningAsErrors && resp.Error != nil {
return resp.Error
}
return nil
}
// constructAndCallRequest creates and executes request with parsing of parameters
func (b *Bot) constructAndCallRequest(methodName string, parameters any) (*ta.Response, error) {
filesParams, hasFiles := filesParameters(parameters)
var data *ta.RequestData
debug := &strings.Builder{}
if hasFiles {
parsedParameters, err := parseParameters(parameters)
if err != nil {
return nil, fmt.Errorf("parsing parameters: %w", err)
}
data, err = b.constructor.MultipartRequest(parsedParameters, filesParams)
if err != nil {
return nil, fmt.Errorf("multipart request: %w", err)
}
logRequestWithFiles(debug, parsedParameters, filesParams)
} else {
var err error
data, err = b.constructor.JSONRequest(parameters)
if err != nil {
return nil, fmt.Errorf("json request: %w", err)
}
_, _ = debug.WriteString(data.Buffer.String())
}
var url string
if b.useTestServerPath {
url = b.apiURL + botPathPrefix + b.token + "/test/" + methodName
} else {
url = b.apiURL + botPathPrefix + b.token + "/" + methodName
}
debugData := strings.TrimSuffix(debug.String(), "\n")
b.log.Debugf("API call to: %q, with data: %s", url, debugData)
resp, err := b.api.Call(url, data)
if err != nil {
return nil, fmt.Errorf("request call: %w", err)
}
return resp, nil
}
// filesParameters gets all files from parameters
func filesParameters(parameters any) (files map[string]ta.NamedReader, hasFiles bool) {
if parametersWithFiles, ok := parameters.(fileCompatible); ok && !isNil(parameters) {
files = parametersWithFiles.fileParameters()
for _, file := range files {
if !isNil(file) {
hasFiles = true
break
}
}
}
return files, hasFiles
}
// parseParameters parses parameter struct to key value structure, v should be a pointer to struct
func parseParameters(v any) (map[string]string, error) {
valueOfV := reflect.ValueOf(v)
if valueOfV.Kind() != reflect.Ptr {
return nil, fmt.Errorf("%q not a pointer", valueOfV.Kind())
}
paramsStruct := valueOfV.Elem()
if paramsStruct.Kind() != reflect.Struct {
return nil, fmt.Errorf("%q not a struct", paramsStruct.Kind())
}
paramsStructType := paramsStruct.Type()
params := make(map[string]string)
for i := 0; i < paramsStructType.NumField(); i++ {
fieldType := paramsStructType.Field(i)
key := fieldType.Tag.Get("json")
key = strings.TrimSuffix(key, omitEmptySuffix)
if key == "" {
return nil, fmt.Errorf("%s does not have `json` tag", paramsStructType.String())
}
fieldValue := paramsStruct.Field(i)
value, err := parseField(fieldValue)
if err != nil {
return nil, fmt.Errorf("parse of %s: %w", paramsStructType.String(), err)
}
if value == "" {
continue
}
params[key] = value
}
return params, nil
}
// parseField parses struct field to string value
func parseField(field reflect.Value) (string, error) {
if field.IsZero() || !field.CanInterface() {
return "", nil
}
var value string
var rawString bool
fieldInterface := field.Interface()
if value, rawString = fieldInterface.(string); !rawString {
data, err := json.Marshal(fieldInterface)
if err != nil {
return "", err
}
value = string(data)
}
// Trim double quotes for values marshaled into string (like file names)
if !rawString && len(value) >= 2 && value[0] == '"' && value[len(value)-1] == '"' {
value = value[1 : len(value)-1]
}
return value, nil
}
func isNil(i any) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return reflect.ValueOf(i).IsNil()
default:
return false
}
}
func logRequestWithFiles(debug *strings.Builder, parameters map[string]string, files map[string]ta.NamedReader) {
debugFiles := make([]string, 0, len(files))
for k, v := range files {
if isNil(v) {
continue
}
if k == v.Name() {
debugFiles = append(debugFiles, fmt.Sprintf("%q", k))
} else {
debugFiles = append(debugFiles, fmt.Sprintf("%q: %q", k, v.Name()))
}
}
//nolint:errcheck
debugJSON, _ := json.Marshal(parameters)
_, _ = debug.WriteString(fmt.Sprintf("parameters: %s, files: {%s}", debugJSON, strings.Join(debugFiles, ", ")))
}
// ToPtr converts value into a pointer to value
func ToPtr[T any](value T) *T {
return &value
}
// safeSend safely send to chan and return true if chan was closed
func safeSend[T any](ch chan<- T, value T) (closed bool) {
defer func() {
if recover() != nil {
closed = true
}
}()
ch <- value
return false
}