-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
113 lines (92 loc) · 1.79 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
package telebot
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type Bot struct {
Token string
client *http.Client
Me *User
}
func New(token string) (*Bot, error) {
b := &Bot{
Token: token,
client: &http.Client{},
}
me, err := b.GetMe()
if err != nil {
return nil, err
}
b.Me = me
return b, nil
}
func (b *Bot) GetMe() (*User, error) {
apiResp, err := b.makeRequest("getMe")
if err != nil {
return nil, err
}
var user User
err = json.Unmarshal(apiResp.Result, &user)
if err != nil {
return nil, err
}
return &user, nil
}
func (b *Bot) GetUpdatesChan() <-chan *Update {
ch := make(chan *Update, 100)
go func() {
for {
updates, err := b.GetUpdates()
if err != nil {
close(ch)
return
}
for _, upd := range updates {
ch <- upd
}
}
}()
return ch
}
func (b *Bot) GetUpdates() ([]*Update, error) {
apiResp, err := b.makeRequest("getUpdates")
if err != nil {
return nil, err
}
var updates []*Update
if err := json.Unmarshal(apiResp.Result, &updates); err != nil {
return nil, err
}
return updates, err
}
func (b *Bot) makeRequest(method string) (*APIResponse, error) {
endpoint = fmt.Sprintf(endpoint, b.Token, method)
req, err := http.NewRequest(http.MethodPost, endpoint, nil)
if err != nil {
return nil, err
}
if req.Body != nil {
defer req.Body.Close()
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := b.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var apiResp APIResponse
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &apiResp)
if err != nil {
return nil, err
}
if !apiResp.OK {
return nil, fmt.Errorf("error: %d %s", apiResp.ErrorCode, apiResp.Description)
}
return &apiResp, err
}