forked from tucnak/telebot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
211 lines (170 loc) · 4.33 KB
/
api.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
package telebot
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
)
// Raw lets you call any method of Bot API manually.
func (b *Bot) Raw(method string, payload interface{}) ([]byte, error) {
url := b.URL + "/bot" + b.Token + "/" + method
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
return []byte{}, wrapSystem(err)
}
resp, err := b.client.Post(url, "application/json", &buf)
if err != nil {
return []byte{}, errors.Wrap(err, "http.Post failed")
}
resp.Close = true
defer resp.Body.Close()
json, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, wrapSystem(err)
}
return json, nil
}
func addFileToWriter(writer *multipart.Writer,
filename, field string, file interface{}) error {
var reader io.Reader
if r, ok := file.(io.Reader); ok {
reader = r
} else if path, ok := file.(string); ok {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
reader = f
} else {
return errors.Errorf("File for field `%v` should be an io.ReadCloser or string", field)
}
part, err := writer.CreateFormFile(field, filename)
if err != nil {
return err
}
_, err = io.Copy(part, reader)
return err
}
func (b *Bot) sendFiles(method string, files map[string]File,
params map[string]string) ([]byte, error) {
body := &bytes.Buffer{}
rawFiles := map[string]interface{}{}
for name, f := range files {
switch {
case f.InCloud():
params[name] = f.FileID
case f.FileURL != "":
params[name] = f.FileURL
case f.OnDisk():
rawFiles[name] = f.FileLocal
case f.FileReader != nil:
rawFiles[name] = f.FileReader
default:
return nil, errors.Errorf("sendFiles: File for field %s doesn't exist", name)
}
}
if len(rawFiles) == 0 {
return b.Raw(method, params)
}
writer := multipart.NewWriter(body)
for field, file := range rawFiles {
if err := addFileToWriter(writer, params["file_name"], field, file); err != nil {
return nil, wrapSystem(err)
}
}
for field, value := range params {
if err := writer.WriteField(field, value); err != nil {
return nil, wrapSystem(err)
}
}
if err := writer.Close(); err != nil {
return nil, wrapSystem(err)
}
url := b.URL + "/bot" + b.Token + "/" + method
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, wrapSystem(err)
}
req.Header.Add("Content-Type", writer.FormDataContentType())
resp, err := b.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "http.Post failed")
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusInternalServerError {
return nil, errors.New("api error: internal server error")
}
json, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, wrapSystem(err)
}
return json, nil
}
func (b *Bot) sendObject(f *File, what string, params map[string]string, files map[string]File) (*Message, error) {
sendWhat := "send" + strings.Title(what)
if what == "videoNote" {
what = "video_note"
}
sendFiles := map[string]File{what: *f}
for k, v := range files {
sendFiles[k] = v
}
respJSON, err := b.sendFiles(sendWhat, sendFiles, params)
if err != nil {
return nil, err
}
return extractMsgResponse(respJSON)
}
func (b *Bot) getMe() (*User, error) {
meJSON, err := b.Raw("getMe", nil)
if err != nil {
return nil, err
}
var botInfo struct {
Ok bool
Result *User
Description string
}
err = json.Unmarshal(meJSON, &botInfo)
if err != nil {
return nil, errors.Wrap(err, "bad response json")
}
if !botInfo.Ok {
return nil, errors.Errorf("api error: %s", botInfo.Description)
}
return botInfo.Result, nil
}
func (b *Bot) getUpdates(offset int, timeout time.Duration) (upd []Update, err error) {
params := map[string]string{
"offset": strconv.Itoa(offset),
"timeout": strconv.Itoa(int(timeout / time.Second)),
}
updatesJSON, errCommand := b.Raw("getUpdates", params)
if errCommand != nil {
err = errCommand
return
}
var updatesReceived struct {
Ok bool
Result []Update
Description string
}
err = json.Unmarshal(updatesJSON, &updatesReceived)
if err != nil {
err = errors.Wrap(err, "bad response json")
return
}
if !updatesReceived.Ok {
err = errors.Errorf("api error: %s", updatesReceived.Description)
return
}
return updatesReceived.Result, nil
}