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/ioutil"
11 "log"
12 "net/http"
13 "net/url"
14 "os"
15 "strconv"
16 "strings"
17 "time"
18
19 "github.com/technoweenie/multipartstreamer"
20)
21
22// BotAPI allows you to interact with the Telegram Bot API.
23type BotAPI struct {
24 Token string `json:"token"`
25 Debug bool `json:"debug"`
26 Self User `json:"-"`
27 Client *http.Client `json:"-"`
28}
29
30// NewBotAPI creates a new BotAPI instance.
31//
32// It requires a token, provided by @BotFather on Telegram.
33func NewBotAPI(token string) (*BotAPI, error) {
34 return NewBotAPIWithClient(token, &http.Client{})
35}
36
37// NewBotAPIWithClient creates a new BotAPI instance
38// and allows you to pass a http.Client.
39//
40// It requires a token, provided by @BotFather on Telegram.
41func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
42 bot := &BotAPI{
43 Token: token,
44 Client: client,
45 }
46
47 self, err := bot.GetMe()
48 if err != nil {
49 return &BotAPI{}, err
50 }
51
52 bot.Self = self
53
54 return bot, nil
55}
56
57// MakeRequest makes a request to a specific endpoint with our token.
58func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
59 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
60
61 resp, err := bot.Client.PostForm(method, params)
62 if err != nil {
63 return APIResponse{}, err
64 }
65 defer resp.Body.Close()
66
67 if resp.StatusCode == http.StatusForbidden {
68 return APIResponse{}, errors.New(ErrAPIForbidden)
69 }
70
71 bytes, err := ioutil.ReadAll(resp.Body)
72 if err != nil {
73 return APIResponse{}, err
74 }
75
76 if bot.Debug {
77 log.Println(endpoint, string(bytes))
78 }
79
80 var apiResp APIResponse
81 json.Unmarshal(bytes, &apiResp)
82
83 if !apiResp.Ok {
84 return apiResp, errors.New(apiResp.Description)
85 }
86
87 return apiResp, nil
88}
89
90// makeMessageRequest makes a request to a method that returns a Message.
91func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) {
92 resp, err := bot.MakeRequest(endpoint, params)
93 if err != nil {
94 return Message{}, err
95 }
96
97 var message Message
98 json.Unmarshal(resp.Result, &message)
99
100 bot.debugLog(endpoint, params, message)
101
102 return message, nil
103}
104
105// UploadFile makes a request to the API with a file.
106//
107// Requires the parameter to hold the file not be in the params.
108// File should be a string to a file path, a FileBytes struct,
109// a FileReader struct, or a url.URL.
110//
111// Note that if your FileReader has a size set to -1, it will read
112// the file into memory to calculate a size.
113func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
114 ms := multipartstreamer.New()
115
116 switch f := file.(type) {
117 case string:
118 ms.WriteFields(params)
119
120 fileHandle, err := os.Open(f)
121 if err != nil {
122 return APIResponse{}, err
123 }
124 defer fileHandle.Close()
125
126 fi, err := os.Stat(f)
127 if err != nil {
128 return APIResponse{}, err
129 }
130
131 ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
132 case FileBytes:
133 ms.WriteFields(params)
134
135 buf := bytes.NewBuffer(f.Bytes)
136 ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
137 case FileReader:
138 ms.WriteFields(params)
139
140 if f.Size != -1 {
141 ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
142
143 break
144 }
145
146 data, err := ioutil.ReadAll(f.Reader)
147 if err != nil {
148 return APIResponse{}, err
149 }
150
151 buf := bytes.NewBuffer(data)
152
153 ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
154 case url.URL:
155 params[fieldname] = f.String()
156
157 ms.WriteFields(params)
158 default:
159 return APIResponse{}, errors.New(ErrBadFileType)
160 }
161
162 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
163
164 req, err := http.NewRequest("POST", method, nil)
165 if err != nil {
166 return APIResponse{}, err
167 }
168
169 ms.SetupRequest(req)
170
171 res, err := bot.Client.Do(req)
172 if err != nil {
173 return APIResponse{}, err
174 }
175 defer res.Body.Close()
176
177 bytes, err := ioutil.ReadAll(res.Body)
178 if err != nil {
179 return APIResponse{}, err
180 }
181
182 if bot.Debug {
183 log.Println(string(bytes))
184 }
185
186 var apiResp APIResponse
187
188 err = json.Unmarshal(bytes, &apiResp)
189 if err != nil {
190 return APIResponse{}, err
191 }
192
193 if !apiResp.Ok {
194 return APIResponse{}, errors.New(apiResp.Description)
195 }
196
197 return apiResp, nil
198}
199
200// GetFileDirectURL returns direct URL to file
201//
202// It requires the FileID.
203func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) {
204 file, err := bot.GetFile(FileConfig{fileID})
205
206 if err != nil {
207 return "", err
208 }
209
210 return file.Link(bot.Token), nil
211}
212
213// GetMe fetches the currently authenticated bot.
214//
215// This method is called upon creation to validate the token,
216// and so you may get this data from BotAPI.Self without the need for
217// another request.
218func (bot *BotAPI) GetMe() (User, error) {
219 resp, err := bot.MakeRequest("getMe", nil)
220 if err != nil {
221 return User{}, err
222 }
223
224 var user User
225 json.Unmarshal(resp.Result, &user)
226
227 bot.debugLog("getMe", nil, user)
228
229 return user, nil
230}
231
232// IsMessageToMe returns true if message directed to this bot.
233//
234// It requires the Message.
235func (bot *BotAPI) IsMessageToMe(message Message) bool {
236 return strings.Contains(message.Text, "@"+bot.Self.UserName)
237}
238
239// Send will send a Chattable item to Telegram.
240//
241// It requires the Chattable to send.
242func (bot *BotAPI) Send(c Chattable) (Message, error) {
243 switch c.(type) {
244 case Fileable:
245 return bot.sendFile(c.(Fileable))
246 default:
247 return bot.sendChattable(c)
248 }
249}
250
251// debugLog checks if the bot is currently running in debug mode, and if
252// so will display information about the request and response in the
253// debug log.
254func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
255 if bot.Debug {
256 log.Printf("%s req : %+v\n", context, v)
257 log.Printf("%s resp: %+v\n", context, message)
258 }
259}
260
261// sendExisting will send a Message with an existing file to Telegram.
262func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
263 v, err := config.values()
264
265 if err != nil {
266 return Message{}, err
267 }
268
269 message, err := bot.makeMessageRequest(method, v)
270 if err != nil {
271 return Message{}, err
272 }
273
274 return message, nil
275}
276
277// uploadAndSend will send a Message with a new file to Telegram.
278func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
279 params, err := config.params()
280 if err != nil {
281 return Message{}, err
282 }
283
284 file := config.getFile()
285
286 resp, err := bot.UploadFile(method, params, config.name(), file)
287 if err != nil {
288 return Message{}, err
289 }
290
291 var message Message
292 json.Unmarshal(resp.Result, &message)
293
294 bot.debugLog(method, nil, message)
295
296 return message, nil
297}
298
299// sendFile determines if the file is using an existing file or uploading
300// a new file, then sends it as needed.
301func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
302 if config.useExistingFile() {
303 return bot.sendExisting(config.method(), config)
304 }
305
306 return bot.uploadAndSend(config.method(), config)
307}
308
309// sendChattable sends a Chattable.
310func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
311 v, err := config.values()
312 if err != nil {
313 return Message{}, err
314 }
315
316 message, err := bot.makeMessageRequest(config.method(), v)
317
318 if err != nil {
319 return Message{}, err
320 }
321
322 return message, nil
323}
324
325// GetUserProfilePhotos gets a user's profile photos.
326//
327// It requires UserID.
328// Offset and Limit are optional.
329func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
330 v := url.Values{}
331 v.Add("user_id", strconv.Itoa(config.UserID))
332 if config.Offset != 0 {
333 v.Add("offset", strconv.Itoa(config.Offset))
334 }
335 if config.Limit != 0 {
336 v.Add("limit", strconv.Itoa(config.Limit))
337 }
338
339 resp, err := bot.MakeRequest("getUserProfilePhotos", v)
340 if err != nil {
341 return UserProfilePhotos{}, err
342 }
343
344 var profilePhotos UserProfilePhotos
345 json.Unmarshal(resp.Result, &profilePhotos)
346
347 bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
348
349 return profilePhotos, nil
350}
351
352// GetFile returns a File which can download a file from Telegram.
353//
354// Requires FileID.
355func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
356 v := url.Values{}
357 v.Add("file_id", config.FileID)
358
359 resp, err := bot.MakeRequest("getFile", v)
360 if err != nil {
361 return File{}, err
362 }
363
364 var file File
365 json.Unmarshal(resp.Result, &file)
366
367 bot.debugLog("GetFile", v, file)
368
369 return file, nil
370}
371
372// GetUpdates fetches updates.
373// If a WebHook is set, this will not return any data!
374//
375// Offset, Limit, and Timeout are optional.
376// To avoid stale items, set Offset to one higher than the previous item.
377// Set Timeout to a large number to reduce requests so you can get updates
378// instantly instead of having to wait between requests.
379func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
380 v := url.Values{}
381 if config.Offset != 0 {
382 v.Add("offset", strconv.Itoa(config.Offset))
383 }
384 if config.Limit > 0 {
385 v.Add("limit", strconv.Itoa(config.Limit))
386 }
387 if config.Timeout > 0 {
388 v.Add("timeout", strconv.Itoa(config.Timeout))
389 }
390
391 resp, err := bot.MakeRequest("getUpdates", v)
392 if err != nil {
393 return []Update{}, err
394 }
395
396 var updates []Update
397 json.Unmarshal(resp.Result, &updates)
398
399 bot.debugLog("getUpdates", v, updates)
400
401 return updates, nil
402}
403
404// RemoveWebhook unsets the webhook.
405func (bot *BotAPI) RemoveWebhook() (APIResponse, error) {
406 return bot.MakeRequest("setWebhook", url.Values{})
407}
408
409// SetWebhook sets a webhook.
410//
411// If this is set, GetUpdates will not get any data!
412//
413// If you do not have a legitimate TLS certificate, you need to include
414// your self signed certificate with the config.
415func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
416
417 if config.Certificate == nil {
418 v := url.Values{}
419 v.Add("url", config.URL.String())
420 if config.MaxConnections != 0 {
421 v.Add("max_connections", strconv.Itoa(config.MaxConnections))
422 }
423
424 return bot.MakeRequest("setWebhook", v)
425 }
426
427 params := make(map[string]string)
428 params["url"] = config.URL.String()
429 if config.MaxConnections != 0 {
430 params["max_connections"] = strconv.Itoa(config.MaxConnections)
431 }
432
433 resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
434 if err != nil {
435 return APIResponse{}, err
436 }
437
438 return resp, nil
439}
440
441// GetWebhookInfo allows you to fetch information about a webhook and if
442// one currently is set, along with pending update count and error messages.
443func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) {
444 resp, err := bot.MakeRequest("getWebhookInfo", url.Values{})
445 if err != nil {
446 return WebhookInfo{}, err
447 }
448
449 var info WebhookInfo
450 err = json.Unmarshal(resp.Result, &info)
451
452 return info, err
453}
454
455// GetUpdatesChan starts and returns a channel for getting updates.
456func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (updatesChannel, error) {
457 ch := make(chan Update, 100)
458
459 go func() {
460 for {
461 updates, err := bot.GetUpdates(config)
462 if err != nil {
463 log.Println(err)
464 log.Println("Failed to get updates, retrying in 3 seconds...")
465 time.Sleep(time.Second * 3)
466
467 continue
468 }
469
470 for _, update := range updates {
471 if update.UpdateID >= config.Offset {
472 config.Offset = update.UpdateID + 1
473 ch <- update
474 }
475 }
476 }
477 }()
478
479 return ch, nil
480}
481
482// ListenForWebhook registers a http handler for a webhook.
483func (bot *BotAPI) ListenForWebhook(pattern string) updatesChannel {
484 ch := make(chan Update, 100)
485
486 http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
487 bytes, _ := ioutil.ReadAll(r.Body)
488
489 var update Update
490 json.Unmarshal(bytes, &update)
491
492 ch <- update
493 })
494
495 return ch
496}
497
498// AnswerInlineQuery sends a response to an inline query.
499//
500// Note that you must respond to an inline query within 30 seconds.
501func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) {
502 v := url.Values{}
503
504 v.Add("inline_query_id", config.InlineQueryID)
505 v.Add("cache_time", strconv.Itoa(config.CacheTime))
506 v.Add("is_personal", strconv.FormatBool(config.IsPersonal))
507 v.Add("next_offset", config.NextOffset)
508 data, err := json.Marshal(config.Results)
509 if err != nil {
510 return APIResponse{}, err
511 }
512 v.Add("results", string(data))
513 v.Add("switch_pm_text", config.SwitchPMText)
514 v.Add("switch_pm_parameter", config.SwitchPMParameter)
515
516 bot.debugLog("answerInlineQuery", v, nil)
517
518 return bot.MakeRequest("answerInlineQuery", v)
519}
520
521// AnswerCallbackQuery sends a response to an inline query callback.
522func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) {
523 v := url.Values{}
524
525 v.Add("callback_query_id", config.CallbackQueryID)
526 if config.Text != "" {
527 v.Add("text", config.Text)
528 }
529 v.Add("show_alert", strconv.FormatBool(config.ShowAlert))
530 if config.URL != "" {
531 v.Add("url", config.URL)
532 }
533 v.Add("cache_time", strconv.Itoa(config.CacheTime))
534
535 bot.debugLog("answerCallbackQuery", v, nil)
536
537 return bot.MakeRequest("answerCallbackQuery", v)
538}
539
540// KickChatMember kicks a user from a chat. Note that this only will work
541// in supergroups, and requires the bot to be an admin. Also note they
542// will be unable to rejoin until they are unbanned.
543func (bot *BotAPI) KickChatMember(config ChatMemberConfig) (APIResponse, error) {
544 v := url.Values{}
545
546 if config.SuperGroupUsername == "" {
547 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
548 } else {
549 v.Add("chat_id", config.SuperGroupUsername)
550 }
551 v.Add("user_id", strconv.Itoa(config.UserID))
552
553 bot.debugLog("kickChatMember", v, nil)
554
555 return bot.MakeRequest("kickChatMember", v)
556}
557
558// LeaveChat makes the bot leave the chat.
559func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) {
560 v := url.Values{}
561
562 if config.SuperGroupUsername == "" {
563 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
564 } else {
565 v.Add("chat_id", config.SuperGroupUsername)
566 }
567
568 bot.debugLog("leaveChat", v, nil)
569
570 return bot.MakeRequest("leaveChat", v)
571}
572
573// GetChat gets information about a chat.
574func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) {
575 v := url.Values{}
576
577 if config.SuperGroupUsername == "" {
578 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
579 } else {
580 v.Add("chat_id", config.SuperGroupUsername)
581 }
582
583 resp, err := bot.MakeRequest("getChat", v)
584 if err != nil {
585 return Chat{}, err
586 }
587
588 var chat Chat
589 err = json.Unmarshal(resp.Result, &chat)
590
591 bot.debugLog("getChat", v, chat)
592
593 return chat, err
594}
595
596// GetChatAdministrators gets a list of administrators in the chat.
597//
598// If none have been appointed, only the creator will be returned.
599// Bots are not shown, even if they are an administrator.
600func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
601 v := url.Values{}
602
603 if config.SuperGroupUsername == "" {
604 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
605 } else {
606 v.Add("chat_id", config.SuperGroupUsername)
607 }
608
609 resp, err := bot.MakeRequest("getChatAdministrators", v)
610 if err != nil {
611 return []ChatMember{}, err
612 }
613
614 var members []ChatMember
615 err = json.Unmarshal(resp.Result, &members)
616
617 bot.debugLog("getChatAdministrators", v, members)
618
619 return members, err
620}
621
622// GetChatMembersCount gets the number of users in a chat.
623func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) {
624 v := url.Values{}
625
626 if config.SuperGroupUsername == "" {
627 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
628 } else {
629 v.Add("chat_id", config.SuperGroupUsername)
630 }
631
632 resp, err := bot.MakeRequest("getChatMembersCount", v)
633 if err != nil {
634 return -1, err
635 }
636
637 var count int
638 err = json.Unmarshal(resp.Result, &count)
639
640 bot.debugLog("getChatMembersCount", v, count)
641
642 return count, err
643}
644
645// GetChatMember gets a specific chat member.
646func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
647 v := url.Values{}
648
649 if config.SuperGroupUsername == "" {
650 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
651 } else {
652 v.Add("chat_id", config.SuperGroupUsername)
653 }
654 v.Add("user_id", strconv.Itoa(config.UserID))
655
656 resp, err := bot.MakeRequest("getChatMember", v)
657 if err != nil {
658 return ChatMember{}, err
659 }
660
661 var member ChatMember
662 err = json.Unmarshal(resp.Result, &member)
663
664 bot.debugLog("getChatMember", v, member)
665
666 return member, err
667}
668
669// UnbanChatMember unbans a user from a chat. Note that this only will work
670// in supergroups, and requires the bot to be an admin.
671func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) {
672 v := url.Values{}
673
674 if config.SuperGroupUsername == "" {
675 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
676 } else {
677 v.Add("chat_id", config.SuperGroupUsername)
678 }
679 v.Add("user_id", strconv.Itoa(config.UserID))
680
681 bot.debugLog("unbanChatMember", v, nil)
682
683 return bot.MakeRequest("unbanChatMember", v)
684}
685
686// GetGameHighScores allows you to get the high scores for a game.
687func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
688 v, _ := config.values()
689
690 resp, err := bot.MakeRequest(config.method(), v)
691 if err != nil {
692 return []GameHighScore{}, err
693 }
694
695 var highScores []GameHighScore
696 err = json.Unmarshal(resp.Result, &highScores)
697
698 return highScores, err
699}