forked from yanzay/tbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
362 lines (321 loc) · 9.42 KB
/
server.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package tbot
import (
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"regexp"
"time"
)
var (
apiBaseURL = "https://api.telegram.org"
)
// Server will connect and serve all updates from Telegram
type Server struct {
webhookURL string
listenAddr string
baseURL string
httpClient *http.Client
client *Client
token string
logger Logger
stop chan struct{}
updatesParams url.Values
bufferSize int
nextOffset int
messageHandlers []messageHandler
messageHandlersAuto []messageHandlerAuto
editMessageHandler handlerFunc
channelPostHandler handlerFunc
editChannelPostHandler handlerFunc
inlineQueryHandler func(*InlineQuery)
inlineResultHandler func(*ChosenInlineResult)
callbackHandler func(*CallbackQuery)
shippingHandler func(*ShippingQuery)
preCheckoutHandler func(*PreCheckoutQuery)
pollHandler func(*Poll)
pollAnswerHandler func(*PollAnswer)
middlewares []Middleware
}
// UpdateHandler is a function for middlewares
type UpdateHandler func(*Update)
// Middleware is a middleware for updates
type Middleware func(UpdateHandler) UpdateHandler
// ServerOption type for additional Server options
type ServerOption func(*Server)
type handlerFunc func(*Message)
type messageHandler struct {
rx *regexp.Regexp
f handlerFunc
}
type messageHandlerAuto struct {
f handlerFunc
}
/*
New creates new Server. Available options:
WithWebhook(url, addr string)
WithHTTPClient(client *http.Client)
WithBaseURL(baseURL string)
*/
func New(token string, options ...ServerOption) *Server {
s := &Server{
httpClient: http.DefaultClient,
token: token,
logger: nopLogger{},
baseURL: apiBaseURL,
editMessageHandler: func(*Message) {},
channelPostHandler: func(*Message) {},
editChannelPostHandler: func(*Message) {},
inlineQueryHandler: func(*InlineQuery) {},
inlineResultHandler: func(*ChosenInlineResult) {},
callbackHandler: func(*CallbackQuery) {},
shippingHandler: func(*ShippingQuery) {},
preCheckoutHandler: func(*PreCheckoutQuery) {},
pollHandler: func(*Poll) {},
pollAnswerHandler: func(*PollAnswer) {},
stop: make(chan struct{}, 0),
}
for _, opt := range options {
opt(s)
}
// bot, err := tgbotapi.NewBotAPIWithClient(token, s.httpClient)
s.client = NewClient(token, s.httpClient, s.baseURL)
return s
}
// WithWebhook returns ServerOption for given Webhook URL and Server address to listen.
// e.g. WithWebhook("https://bot.example.com/super/url", "0.0.0.0:8080")
func WithWebhook(url, addr string) ServerOption {
return func(s *Server) {
s.webhookURL = url
s.listenAddr = addr
}
}
// WithBaseURL sets custom apiBaseURL for server.
// It may be necessary to run the server in some countries
func WithBaseURL(baseURL string) ServerOption {
return func(s *Server) {
s.baseURL = baseURL
}
}
// WithHTTPClient sets custom http client for server.
func WithHTTPClient(client *http.Client) ServerOption {
return func(s *Server) {
s.httpClient = client
}
}
// WithLogger sets logger for tbot
func WithLogger(logger Logger) ServerOption {
return func(s *Server) {
s.logger = logger
}
}
// Use adds middleware to server
func (s *Server) Use(m Middleware, handler func(*Message)) {
oldMiddlewares := s.middlewares
s.middlewares = append(s.middlewares, m)
newMiddlewares := s.middlewares
// Check if a new m was appended
if len(newMiddlewares) > len(oldMiddlewares) {
// Trigger the desired action
fmt.Println("Update success")
s.HandleMessageAuto(handler)
}
}
// Start listening for updates
func (s *Server) Start() error {
if len(s.token) == 0 {
return fmt.Errorf("token is empty")
}
updates, err := s.getUpdates()
if err != nil {
return err
}
for {
select {
case update := <-updates:
handleUpdate := func(update *Update) {
switch {
case update.Message != nil:
s.handleMessage(update.Message)
case update.EditedMessage != nil:
s.editMessageHandler(update.EditedMessage)
case update.ChannelPost != nil:
s.channelPostHandler(update.ChannelPost)
case update.EditedChannelPost != nil:
s.editChannelPostHandler(update.EditedChannelPost)
case update.InlineQuery != nil:
s.inlineQueryHandler(update.InlineQuery)
case update.ChosenInlineResult != nil:
s.inlineResultHandler(update.ChosenInlineResult)
case update.CallbackQuery != nil:
s.callbackHandler(update.CallbackQuery)
case update.ShippingQuery != nil:
s.shippingHandler(update.ShippingQuery)
case update.PreCheckoutQuery != nil:
s.preCheckoutHandler(update.PreCheckoutQuery)
case update.Poll != nil:
s.pollHandler(update.Poll)
case update.PollAnswer != nil:
s.pollAnswerHandler(update.PollAnswer)
}
}
var f = handleUpdate
for i := len(s.middlewares) - 1; i >= 0; i-- {
f = s.middlewares[i](f)
}
go f(update)
case <-s.stop:
return nil
}
}
}
// Client returns Telegram API Client
func (s *Server) Client() *Client {
return s.client
}
// Stop listening for updates
func (s *Server) Stop() {
s.stop <- struct{}{}
}
func (s *Server) getUpdates() (chan *Update, error) {
if s.webhookURL != "" && s.listenAddr != "" {
return s.listenUpdates()
}
s.client.deleteWebhook()
return s.longPoolUpdates()
}
func (s *Server) listenUpdates() (chan *Update, error) {
err := s.client.setWebhook(s.webhookURL)
if err != nil {
return nil, fmt.Errorf("unable to set webhook: %v", err)
}
updates := make(chan *Update)
handler := func(w http.ResponseWriter, r *http.Request) {
up := &Update{}
err := json.NewDecoder(r.Body).Decode(up)
if err != nil {
s.logger.Errorf("unable to decode update: %v", err)
return
}
updates <- up
}
l, err := net.Listen("tcp", s.listenAddr)
if err != nil {
return nil, err
}
go http.Serve(l, http.HandlerFunc(handler))
return updates, nil
}
func (s *Server) longPoolUpdates() (chan *Update, error) {
s.logger.Debugf("fetching updates...")
endpoint := fmt.Sprintf("%s/bot%s/%s", s.baseURL, s.token, "getUpdates")
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return nil, err
}
params := s.updatesParams
if params == nil {
params = url.Values{}
}
params.Set("timeout", fmt.Sprint(3600))
req.URL.RawQuery = params.Encode()
updates := make(chan *Update, s.bufferSize)
go func() {
for {
params.Set("offset", fmt.Sprint(s.nextOffset))
req.URL.RawQuery = params.Encode()
resp, err := s.httpClient.Do(req)
if err != nil {
s.logger.Errorf("unable to perform request: %v", err)
time.Sleep(1 * time.Second)
continue
}
var updatesResp *struct {
OK bool `json:"ok"`
Result []*Update `json:"result"`
Description string `json:"description"`
}
err = json.NewDecoder(resp.Body).Decode(&updatesResp)
if err != nil {
s.logger.Errorf("unable to decode response: %v", err)
time.Sleep(1 * time.Second)
continue
}
err = resp.Body.Close()
if err != nil {
s.logger.Errorf("unable to close response body: %v", err)
}
if !updatesResp.OK {
s.logger.Errorf("updates query fail: %s", updatesResp.Description)
time.Sleep(1 * time.Second)
continue
}
for _, up := range updatesResp.Result {
s.nextOffset = up.UpdateID + 1
updates <- up
}
}
}()
return updates, nil
}
// HandleMessage sets handler for incoming messages
func (s *Server) HandleMessage(pattern string, handler func(*Message)) {
rx := regexp.MustCompile(pattern)
s.messageHandlers = append(s.messageHandlers, messageHandler{rx: rx, f: handler})
}
func (s *Server) HandleMessageAuto(handler func(*Message)) {
s.messageHandlersAuto = append(s.messageHandlersAuto, messageHandlerAuto{f: handler})
}
// HandleEditedMessage set handler for incoming edited messages
func (s *Server) HandleEditedMessage(handler func(*Message)) {
s.editMessageHandler = handler
}
// HandleChannelPost set handler for incoming channel post
func (s *Server) HandleChannelPost(handler func(*Message)) {
s.channelPostHandler = handler
}
// HandleEditChannelPost set handler for incoming edited channel post
func (s *Server) HandleEditChannelPost(handler func(*Message)) {
s.editChannelPostHandler = handler
}
// HandleInlineQuery set handler for inline queries
func (s *Server) HandleInlineQuery(handler func(*InlineQuery)) {
s.inlineQueryHandler = handler
}
// HandleInlineResult set inline result handler
func (s *Server) HandleInlineResult(handler func(*ChosenInlineResult)) {
s.inlineResultHandler = handler
}
// HandleCallback set handler for inline buttons
func (s *Server) HandleCallback(handler func(*CallbackQuery)) {
s.callbackHandler = handler
}
// HandleShipping set handler for shipping queries
func (s *Server) HandleShipping(handler func(*ShippingQuery)) {
s.shippingHandler = handler
}
// HandlePreCheckout set handler for pre-checkout queries
func (s *Server) HandlePreCheckout(handler func(*PreCheckoutQuery)) {
s.preCheckoutHandler = handler
}
// HandlePollUpdate set handler for anonymous poll updates
func (s *Server) HandlePollUpdate(handler func(*Poll)) {
s.pollHandler = handler
}
// HandlePollAnswer set handler for non-anonymous poll updates
func (s *Server) HandlePollAnswer(handler func(*PollAnswer)) {
s.pollAnswerHandler = handler
}
func (s *Server) handleMessage(msg *Message) {
for _, handler := range s.messageHandlers {
if handler.rx.MatchString(msg.Text) {
handler.f(msg)
return
}
}
for _, handlerAuto := range s.messageHandlersAuto {
handlerAuto.f(msg)
return
}
}