-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.go
More file actions
82 lines (71 loc) · 2.01 KB
/
Copy pathtools.go
File metadata and controls
82 lines (71 loc) · 2.01 KB
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
// This file is part of Camponotus
// Camponotus is free software: see LICENSE.txt for more details.
package telegram
import (
"encoding/json"
"io/ioutil"
"net/http"
"sort"
)
// LongPollFetcher fetches messages using long polling
type LongPollFetcher struct {
Message chan *Message
EditedMessage chan *Message
InlineQuery chan *InlineQuery
ChosenInlineResult chan *ChosenInlineResult
CallbackQuery chan *CallbackQuery
API API
}
type byUpdateID []Update
func (b byUpdateID) Len() int { return len(b) }
func (b byUpdateID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byUpdateID) Less(i, j int) bool { return b[i].ID < b[j].ID }
// Fetch fetches messages by long polling in loops
func (l *LongPollFetcher) Fetch(limit, timeout int) error {
offset := 0
if limit < 1 {
limit = 1
}
if timeout < 0 {
timeout = 0
}
for {
data, err := l.API.GetUpdates(offset, limit, timeout)
if err != nil {
return err
}
sort.Sort(byUpdateID(data))
for _, u := range data {
if u.ID >= offset {
offset = u.ID + 1
}
switch {
case u.Message != nil && l.Message != nil:
l.Message <- u.Message
case u.EditedMessage != nil && l.EditedMessage != nil:
l.EditedMessage <- u.EditedMessage
case u.InlineQuery != nil && l.InlineQuery != nil:
l.InlineQuery <- u.InlineQuery
case u.ChosenInlineResult != nil && l.ChosenInlineResult != nil:
l.ChosenInlineResult <- u.ChosenInlineResult
case u.CallbackQuery != nil && l.CallbackQuery != nil:
l.CallbackQuery <- u.CallbackQuery
}
}
}
}
// WebhookHandler eases your work to write handler
type WebhookHandler func(w http.ResponseWriter, r *http.Request, update *Update)
func (h WebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
var u Update
if err := json.Unmarshal(buf, &u); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
h(w, r, &u)
}