bot.go (view raw)
1// Package tgbotapi has functions and types used for interacting with
2// the Telegram Bot API.
3package tgbotapi
4
5import (
6 "bytes"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "io/ioutil"
12 "log"
13 "net/http"
14 "net/url"
15 "os"
16 "strconv"
17 "strings"
18 "time"
19
20 "github.com/technoweenie/multipartstreamer"
21)
22
23// BotAPI allows you to interact with the Telegram Bot API.
24type BotAPI struct {
25 Token string `json:"token"`
26 Debug bool `json:"debug"`
27 Buffer int `json:"buffer"`
28
29 Self User `json:"-"`
30 Client *http.Client `json:"-"`
31}
32
33// NewBotAPI creates a new BotAPI instance.
34//
35// It requires a token, provided by @BotFather on Telegram.
36func NewBotAPI(token string) (*BotAPI, error) {
37 return NewBotAPIWithClient(token, &http.Client{})
38}
39
40// NewBotAPIWithClient creates a new BotAPI instance
41// and allows you to pass a http.Client.
42//
43// It requires a token, provided by @BotFather on Telegram.
44func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
45 bot := &BotAPI{
46 Token: token,
47 Client: client,
48 Buffer: 100,
49 }
50
51 self, err := bot.GetMe()
52 if err != nil {
53 return nil, err
54 }
55
56 bot.Self = self
57
58 return bot, nil
59}
60
61// MakeRequest makes a request to a specific endpoint with our token.
62func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
63 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
64
65 resp, err := bot.Client.PostForm(method, params)
66 if err != nil {
67 return APIResponse{}, err
68 }
69 defer resp.Body.Close()
70
71 var apiResp APIResponse
72 bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp)
73 if err != nil {
74 return apiResp, err
75 }
76
77 if bot.Debug {
78 log.Printf("%s resp: %s", endpoint, bytes)
79 }
80
81 if !apiResp.Ok {
82 return apiResp, errors.New(apiResp.Description)
83 }
84
85 return apiResp, nil
86}
87
88// decodeAPIResponse decode response and return slice of bytes if debug enabled.
89// If debug disabled, just decode http.Response.Body stream to APIResponse struct
90// for efficient memory usage
91func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) {
92 if !bot.Debug {
93 dec := json.NewDecoder(responseBody)
94 err = dec.Decode(resp)
95 return
96 }
97
98 // if debug, read reponse body
99 data, err := ioutil.ReadAll(responseBody)
100 if err != nil {
101 return
102 }
103
104 err = json.Unmarshal(data, resp)
105 if err != nil {
106 return
107 }
108
109 return data, nil
110}
111
112// UploadFile makes a request to the API with a file.
113//
114// Requires the parameter to hold the file not be in the params.
115// File should be a string to a file path, a FileBytes struct,
116// a FileReader struct, or a url.URL.
117//
118// Note that if your FileReader has a size set to -1, it will read
119// the file into memory to calculate a size.
120func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
121 ms := multipartstreamer.New()
122
123 switch f := file.(type) {
124 case string:
125 ms.WriteFields(params)
126
127 fileHandle, err := os.Open(f)
128 if err != nil {
129 return APIResponse{}, err
130 }
131 defer fileHandle.Close()
132
133 fi, err := os.Stat(f)
134 if err != nil {
135 return APIResponse{}, err
136 }
137
138 ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
139 case FileBytes:
140 ms.WriteFields(params)
141
142 buf := bytes.NewBuffer(f.Bytes)
143 ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
144 case FileReader:
145 ms.WriteFields(params)
146
147 if f.Size != -1 {
148 ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
149
150 break
151 }
152
153 data, err := ioutil.ReadAll(f.Reader)
154 if err != nil {
155 return APIResponse{}, err
156 }
157
158 buf := bytes.NewBuffer(data)
159
160 ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
161 case url.URL:
162 params[fieldname] = f.String()
163
164 ms.WriteFields(params)
165 default:
166 return APIResponse{}, errors.New(ErrBadFileType)
167 }
168
169 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
170
171 req, err := http.NewRequest("POST", method, nil)
172 if err != nil {
173 return APIResponse{}, err
174 }
175
176 ms.SetupRequest(req)
177
178 res, err := bot.Client.Do(req)
179 if err != nil {
180 return APIResponse{}, err
181 }
182 defer res.Body.Close()
183
184 bytes, err := ioutil.ReadAll(res.Body)
185 if err != nil {
186 return APIResponse{}, err
187 }
188
189 if bot.Debug {
190 log.Println(string(bytes))
191 }
192
193 var apiResp APIResponse
194
195 err = json.Unmarshal(bytes, &apiResp)
196 if err != nil {
197 return APIResponse{}, err
198 }
199
200 if !apiResp.Ok {
201 return APIResponse{}, errors.New(apiResp.Description)
202 }
203
204 return apiResp, nil
205}
206
207// GetFileDirectURL returns direct URL to file
208//
209// It requires the FileID.
210func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) {
211 file, err := bot.GetFile(FileConfig{fileID})
212
213 if err != nil {
214 return "", err
215 }
216
217 return file.Link(bot.Token), nil
218}
219
220// GetMe fetches the currently authenticated bot.
221//
222// This method is called upon creation to validate the token,
223// and so you may get this data from BotAPI.Self without the need for
224// another request.
225func (bot *BotAPI) GetMe() (User, error) {
226 resp, err := bot.MakeRequest("getMe", nil)
227 if err != nil {
228 return User{}, err
229 }
230
231 var user User
232 json.Unmarshal(resp.Result, &user)
233
234 bot.debugLog("getMe", nil, user)
235
236 return user, nil
237}
238
239// IsMessageToMe returns true if message directed to this bot.
240//
241// It requires the Message.
242func (bot *BotAPI) IsMessageToMe(message Message) bool {
243 return strings.Contains(message.Text, "@"+bot.Self.UserName)
244}
245
246// Request sends a Chattable to Telegram, and returns the APIResponse.
247func (bot *BotAPI) Request(c Chattable) (APIResponse, error) {
248 switch t := c.(type) {
249 case Fileable:
250 if t.useExistingFile() {
251 v, err := t.values()
252 if err != nil {
253 return APIResponse{}, err
254 }
255
256 return bot.MakeRequest(t.method(), v)
257 }
258
259 p, err := t.params()
260 if err != nil {
261 return APIResponse{}, err
262 }
263
264 return bot.UploadFile(t.method(), p, t.name(), t.getFile())
265 default:
266 v, err := c.values()
267 if err != nil {
268 return APIResponse{}, err
269 }
270
271 return bot.MakeRequest(c.method(), v)
272 }
273}
274
275// Send will send a Chattable item to Telegram and provides the
276// returned Message.
277func (bot *BotAPI) Send(c Chattable) (Message, error) {
278 resp, err := bot.Request(c)
279 if err != nil {
280 return Message{}, err
281 }
282
283 var message Message
284 err = json.Unmarshal(resp.Result, &message)
285
286 return message, err
287}
288
289// debugLog checks if the bot is currently running in debug mode, and if
290// so will display information about the request and response in the
291// debug log.
292func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
293 if bot.Debug {
294 log.Printf("%s req : %+v\n", context, v)
295 log.Printf("%s resp: %+v\n", context, message)
296 }
297}
298
299// GetUserProfilePhotos gets a user's profile photos.
300//
301// It requires UserID.
302// Offset and Limit are optional.
303func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
304 v := url.Values{}
305 v.Add("user_id", strconv.Itoa(config.UserID))
306 if config.Offset != 0 {
307 v.Add("offset", strconv.Itoa(config.Offset))
308 }
309 if config.Limit != 0 {
310 v.Add("limit", strconv.Itoa(config.Limit))
311 }
312
313 resp, err := bot.MakeRequest("getUserProfilePhotos", v)
314 if err != nil {
315 return UserProfilePhotos{}, err
316 }
317
318 var profilePhotos UserProfilePhotos
319 json.Unmarshal(resp.Result, &profilePhotos)
320
321 bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
322
323 return profilePhotos, nil
324}
325
326// GetFile returns a File which can download a file from Telegram.
327//
328// Requires FileID.
329func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
330 v := url.Values{}
331 v.Add("file_id", config.FileID)
332
333 resp, err := bot.MakeRequest("getFile", v)
334 if err != nil {
335 return File{}, err
336 }
337
338 var file File
339 json.Unmarshal(resp.Result, &file)
340
341 bot.debugLog("GetFile", v, file)
342
343 return file, nil
344}
345
346// GetUpdates fetches updates.
347// If a WebHook is set, this will not return any data!
348//
349// Offset, Limit, and Timeout are optional.
350// To avoid stale items, set Offset to one higher than the previous item.
351// Set Timeout to a large number to reduce requests so you can get updates
352// instantly instead of having to wait between requests.
353func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
354 v := url.Values{}
355 if config.Offset != 0 {
356 v.Add("offset", strconv.Itoa(config.Offset))
357 }
358 if config.Limit > 0 {
359 v.Add("limit", strconv.Itoa(config.Limit))
360 }
361 if config.Timeout > 0 {
362 v.Add("timeout", strconv.Itoa(config.Timeout))
363 }
364
365 resp, err := bot.MakeRequest("getUpdates", v)
366 if err != nil {
367 return []Update{}, err
368 }
369
370 var updates []Update
371 json.Unmarshal(resp.Result, &updates)
372
373 bot.debugLog("getUpdates", v, updates)
374
375 return updates, nil
376}
377
378// GetWebhookInfo allows you to fetch information about a webhook and if
379// one currently is set, along with pending update count and error messages.
380func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) {
381 resp, err := bot.MakeRequest("getWebhookInfo", url.Values{})
382 if err != nil {
383 return WebhookInfo{}, err
384 }
385
386 var info WebhookInfo
387 err = json.Unmarshal(resp.Result, &info)
388
389 return info, err
390}
391
392// GetUpdatesChan starts and returns a channel for getting updates.
393func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) {
394 ch := make(chan Update, bot.Buffer)
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 ch <- update
411 }
412 }
413 }
414 }()
415
416 return ch, nil
417}
418
419// ListenForWebhook registers a http handler for a webhook.
420func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel {
421 ch := make(chan Update, bot.Buffer)
422
423 http.HandleFunc(pattern, 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 ch <- update
430 })
431
432 return ch
433}
434
435// GetChat gets information about a chat.
436func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) {
437 v := url.Values{}
438
439 if config.SuperGroupUsername == "" {
440 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
441 } else {
442 v.Add("chat_id", config.SuperGroupUsername)
443 }
444
445 resp, err := bot.MakeRequest("getChat", v)
446 if err != nil {
447 return Chat{}, err
448 }
449
450 var chat Chat
451 err = json.Unmarshal(resp.Result, &chat)
452
453 bot.debugLog("getChat", v, chat)
454
455 return chat, err
456}
457
458// GetChatAdministrators gets a list of administrators in the chat.
459//
460// If none have been appointed, only the creator will be returned.
461// Bots are not shown, even if they are an administrator.
462func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
463 v := url.Values{}
464
465 if config.SuperGroupUsername == "" {
466 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
467 } else {
468 v.Add("chat_id", config.SuperGroupUsername)
469 }
470
471 resp, err := bot.MakeRequest("getChatAdministrators", v)
472 if err != nil {
473 return []ChatMember{}, err
474 }
475
476 var members []ChatMember
477 err = json.Unmarshal(resp.Result, &members)
478
479 bot.debugLog("getChatAdministrators", v, members)
480
481 return members, err
482}
483
484// GetChatMembersCount gets the number of users in a chat.
485func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) {
486 v := url.Values{}
487
488 if config.SuperGroupUsername == "" {
489 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
490 } else {
491 v.Add("chat_id", config.SuperGroupUsername)
492 }
493
494 resp, err := bot.MakeRequest("getChatMembersCount", v)
495 if err != nil {
496 return -1, err
497 }
498
499 var count int
500 err = json.Unmarshal(resp.Result, &count)
501
502 bot.debugLog("getChatMembersCount", v, count)
503
504 return count, err
505}
506
507// GetChatMember gets a specific chat member.
508func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
509 v := url.Values{}
510
511 if config.SuperGroupUsername == "" {
512 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
513 } else {
514 v.Add("chat_id", config.SuperGroupUsername)
515 }
516 v.Add("user_id", strconv.Itoa(config.UserID))
517
518 resp, err := bot.MakeRequest("getChatMember", v)
519 if err != nil {
520 return ChatMember{}, err
521 }
522
523 var member ChatMember
524 err = json.Unmarshal(resp.Result, &member)
525
526 bot.debugLog("getChatMember", v, member)
527
528 return member, err
529}
530
531// GetGameHighScores allows you to get the high scores for a game.
532func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
533 v, _ := config.values()
534
535 resp, err := bot.MakeRequest(config.method(), v)
536 if err != nil {
537 return []GameHighScore{}, err
538 }
539
540 var highScores []GameHighScore
541 err = json.Unmarshal(resp.Result, &highScores)
542
543 return highScores, err
544}
545
546// GetInviteLink get InviteLink for a chat
547func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) {
548 v := url.Values{}
549
550 if config.SuperGroupUsername == "" {
551 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
552 } else {
553 v.Add("chat_id", config.SuperGroupUsername)
554 }
555
556 resp, err := bot.MakeRequest("exportChatInviteLink", v)
557 if err != nil {
558 return "", err
559 }
560
561 var inviteLink string
562 err = json.Unmarshal(resp.Result, &inviteLink)
563
564 return inviteLink, err
565}
566
567// GetStickerSet returns a StickerSet.
568func (bot *BotAPI) GetStickerSet(config GetStickerSetConfig) (StickerSet, error) {
569 v, err := config.values()
570 if err != nil {
571 return StickerSet{}, nil
572 }
573
574 resp, err := bot.MakeRequest(config.method(), v)
575 if err != nil {
576 return StickerSet{}, nil
577 }
578
579 var stickers StickerSet
580 err = json.Unmarshal(resp.Result, &stickers)
581
582 return stickers, err
583}