bot.go (view raw)
1// Package tgbotapi has bindings for interacting with the Telegram Bot API.
2package tgbotapi
3
4import (
5 "bytes"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "github.com/technoweenie/multipartstreamer"
10 "io/ioutil"
11 "log"
12 "net/http"
13 "net/url"
14 "os"
15 "strconv"
16 "time"
17)
18
19// BotAPI has methods for interacting with all of Telegram's Bot API endpoints.
20type BotAPI struct {
21 Token string `json:"token"`
22 Debug bool `json:"debug"`
23 Self User `json:"-"`
24 Updates chan Update `json:"-"`
25 Client *http.Client `json:"-"`
26}
27
28// NewBotAPI creates a new BotAPI instance.
29// Requires a token, provided by @BotFather on Telegram
30func NewBotAPI(token string) (*BotAPI, error) {
31 return NewBotAPIWithClient(token, &http.Client{})
32}
33
34// NewBotAPIWithClient creates a new BotAPI instance passing an http.Client.
35// Requires a token, provided by @BotFather on Telegram
36func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
37 bot := &BotAPI{
38 Token: token,
39 Client: client,
40 }
41
42 self, err := bot.GetMe()
43 if err != nil {
44 return &BotAPI{}, err
45 }
46
47 bot.Self = self
48
49 return bot, nil
50}
51
52// MakeRequest makes a request to a specific endpoint with our token.
53// All requests are POSTs because Telegram doesn't care, and it's easier.
54func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
55 resp, err := bot.Client.PostForm(fmt.Sprintf(APIEndpoint, bot.Token, endpoint), params)
56 if err != nil {
57 return APIResponse{}, err
58 }
59 defer resp.Body.Close()
60
61 if resp.StatusCode == http.StatusForbidden {
62 return APIResponse{}, errors.New(APIForbidden)
63 }
64
65 bytes, err := ioutil.ReadAll(resp.Body)
66 if err != nil {
67 return APIResponse{}, err
68 }
69
70 if bot.Debug {
71 log.Println(endpoint, string(bytes))
72 }
73
74 var apiResp APIResponse
75 json.Unmarshal(bytes, &apiResp)
76
77 if !apiResp.Ok {
78 return APIResponse{}, errors.New(apiResp.Description)
79 }
80
81 return apiResp, nil
82}
83
84func (bot *BotAPI) MakeMessageRequest(endpoint string, params url.Values) (Message, error) {
85 resp, err := bot.MakeRequest(endpoint, params)
86 if err != nil {
87 return Message{}, err
88 }
89
90 var message Message
91 json.Unmarshal(resp.Result, &message)
92
93 bot.debugLog(endpoint, params, message)
94
95 return message, nil
96}
97
98// UploadFile makes a request to the API with a file.
99//
100// Requires the parameter to hold the file not be in the params.
101// File should be a string to a file path, a FileBytes struct, or a FileReader struct.
102func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
103 ms := multipartstreamer.New()
104 ms.WriteFields(params)
105
106 switch f := file.(type) {
107 case string:
108 fileHandle, err := os.Open(f)
109 if err != nil {
110 return APIResponse{}, err
111 }
112 defer fileHandle.Close()
113
114 fi, err := os.Stat(f)
115 if err != nil {
116 return APIResponse{}, err
117 }
118
119 ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
120 case FileBytes:
121 buf := bytes.NewBuffer(f.Bytes)
122 ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
123 case FileReader:
124 if f.Size == -1 {
125 data, err := ioutil.ReadAll(f.Reader)
126 if err != nil {
127 return APIResponse{}, err
128 }
129 buf := bytes.NewBuffer(data)
130
131 ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
132
133 break
134 }
135
136 ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
137 default:
138 return APIResponse{}, errors.New("bad file type")
139 }
140
141 req, err := http.NewRequest("POST", fmt.Sprintf(APIEndpoint, bot.Token, endpoint), nil)
142 ms.SetupRequest(req)
143 if err != nil {
144 return APIResponse{}, err
145 }
146
147 res, err := bot.Client.Do(req)
148 if err != nil {
149 return APIResponse{}, err
150 }
151 defer res.Body.Close()
152
153 bytes, err := ioutil.ReadAll(res.Body)
154 if err != nil {
155 return APIResponse{}, err
156 }
157
158 if bot.Debug {
159 log.Println(string(bytes[:]))
160 }
161
162 var apiResp APIResponse
163 json.Unmarshal(bytes, &apiResp)
164
165 if !apiResp.Ok {
166 return APIResponse{}, errors.New(apiResp.Description)
167 }
168
169 return apiResp, nil
170}
171
172func (this *BotAPI) getFileDirectUrl(fileID string) (string, error) {
173 file, err := this.GetFile(FileConfig{fileID})
174
175 if err != nil {
176 return "", err
177 }
178
179 return file.Link(this.Token), nil
180}
181
182// GetMe fetches the currently authenticated bot.
183//
184// There are no parameters for this method.
185func (bot *BotAPI) GetMe() (User, error) {
186 resp, err := bot.MakeRequest("getMe", nil)
187 if err != nil {
188 return User{}, err
189 }
190
191 var user User
192 json.Unmarshal(resp.Result, &user)
193
194 if bot.Debug {
195 log.Printf("getMe: %+v\n", user)
196 }
197
198 return user, nil
199}
200
201func (bot *BotAPI) Send(c Chattable) (Message, error) {
202 switch c.(type) {
203 case Fileable:
204 return bot.sendFile(c.(Fileable))
205 default:
206 return bot.sendChattable(c)
207 }
208}
209
210func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
211 if bot.Debug {
212 log.Printf("%s req : %+v\n", context, v)
213 log.Printf("%s resp: %+v\n", context, message)
214 }
215}
216
217func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
218 v, err := config.Values()
219
220 if err != nil {
221 return Message{}, err
222 }
223
224 message, err := bot.MakeMessageRequest(method, v)
225 if err != nil {
226 return Message{}, err
227 }
228
229 return message, nil
230}
231
232func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
233 params, err := config.Params()
234 if err != nil {
235 return Message{}, err
236 }
237
238 file := config.GetFile()
239
240 resp, err := bot.UploadFile(method, params, config.Name(), file)
241 if err != nil {
242 return Message{}, err
243 }
244
245 var message Message
246 json.Unmarshal(resp.Result, &message)
247
248 if bot.Debug {
249 log.Printf("%s resp: %+v\n", method, message)
250 }
251
252 return message, nil
253}
254
255func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
256 if config.UseExistingFile() {
257 return bot.sendExisting(config.Method(), config)
258 }
259
260 return bot.uploadAndSend(config.Method(), config)
261}
262
263func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
264 v, err := config.Values()
265 if err != nil {
266 return Message{}, err
267 }
268
269 message, err := bot.MakeMessageRequest(config.Method(), v)
270
271 if err != nil {
272 return Message{}, err
273 }
274
275 return message, nil
276}
277
278// GetUserProfilePhotos gets a user's profile photos.
279//
280// Requires UserID.
281// Offset and Limit are optional.
282func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
283 v := url.Values{}
284 v.Add("user_id", strconv.Itoa(config.UserID))
285 if config.Offset != 0 {
286 v.Add("offset", strconv.Itoa(config.Offset))
287 }
288 if config.Limit != 0 {
289 v.Add("limit", strconv.Itoa(config.Limit))
290 }
291
292 resp, err := bot.MakeRequest("getUserProfilePhotos", v)
293 if err != nil {
294 return UserProfilePhotos{}, err
295 }
296
297 var profilePhotos UserProfilePhotos
298 json.Unmarshal(resp.Result, &profilePhotos)
299
300 bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
301
302 return profilePhotos, nil
303}
304
305// GetFile returns a file_id required to download a file.
306//
307// Requires FileID.
308func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
309 v := url.Values{}
310 v.Add("file_id", config.FileID)
311
312 resp, err := bot.MakeRequest("getFile", v)
313 if err != nil {
314 return File{}, err
315 }
316
317 var file File
318 json.Unmarshal(resp.Result, &file)
319
320 bot.debugLog("GetFile", v, file)
321
322 return file, nil
323}
324
325// GetUpdates fetches updates.
326// If a WebHook is set, this will not return any data!
327//
328// Offset, Limit, and Timeout are optional.
329// To not get old items, set Offset to one higher than the previous item.
330// Set Timeout to a large number to reduce requests and get responses instantly.
331func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
332 v := url.Values{}
333 if config.Offset > 0 {
334 v.Add("offset", strconv.Itoa(config.Offset))
335 }
336 if config.Limit > 0 {
337 v.Add("limit", strconv.Itoa(config.Limit))
338 }
339 if config.Timeout > 0 {
340 v.Add("timeout", strconv.Itoa(config.Timeout))
341 }
342
343 resp, err := bot.MakeRequest("getUpdates", v)
344 if err != nil {
345 return []Update{}, err
346 }
347
348 var updates []Update
349 json.Unmarshal(resp.Result, &updates)
350
351 if bot.Debug {
352 log.Printf("getUpdates: %+v\n", updates)
353 }
354
355 return updates, nil
356}
357
358func (bot *BotAPI) RemoveWebhook() (APIResponse, error) {
359 return bot.MakeRequest("setWebhook", url.Values{})
360}
361
362// SetWebhook sets a webhook.
363// If this is set, GetUpdates will not get any data!
364//
365// Requires URL OR to set Clear to true.
366func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
367 if config.Certificate == nil {
368 v := url.Values{}
369 v.Add("url", config.URL.String())
370
371 return bot.MakeRequest("setWebhook", v)
372 }
373
374 params := make(map[string]string)
375 params["url"] = config.URL.String()
376
377 resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
378 if err != nil {
379 return APIResponse{}, err
380 }
381
382 var apiResp APIResponse
383 json.Unmarshal(resp.Result, &apiResp)
384
385 if bot.Debug {
386 log.Printf("setWebhook resp: %+v\n", apiResp)
387 }
388
389 return apiResp, nil
390}
391
392// UpdatesChan starts a channel for getting updates.
393func (bot *BotAPI) UpdatesChan(config UpdateConfig) error {
394 bot.Updates = make(chan Update, 100)
395
396 go func() {
397 for {
398 updates, err := bot.GetUpdates(config)
399 if err != nil {
400 log.Println(err)
401 log.Println("Failed to get updates, retrying in 3 seconds...")
402 time.Sleep(time.Second * 3)
403
404 continue
405 }
406
407 for _, update := range updates {
408 if update.UpdateID >= config.Offset {
409 config.Offset = update.UpdateID + 1
410 bot.Updates <- update
411 }
412 }
413 }
414 }()
415
416 return nil
417}
418
419// ListenForWebhook registers a http handler for a webhook.
420func (bot *BotAPI) ListenForWebhook(pattern string) http.Handler {
421 bot.Updates = make(chan Update, 100)
422
423 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
424 bytes, _ := ioutil.ReadAll(r.Body)
425
426 var update Update
427 json.Unmarshal(bytes, &update)
428
429 bot.Updates <- update
430 })
431
432 http.HandleFunc(pattern, handler)
433
434 return handler
435}