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 Buffer int `json:"buffer"`
27
28 Self User `json:"-"`
29 Client *http.Client `json:"-"`
30}
31
32// NewBotAPI creates a new BotAPI instance.
33//
34// It requires a token, provided by @BotFather on Telegram.
35func NewBotAPI(token string) (*BotAPI, error) {
36 return NewBotAPIWithClient(token, &http.Client{})
37}
38
39// NewBotAPIWithClient creates a new BotAPI instance
40// and allows you to pass a http.Client.
41//
42// It requires a token, provided by @BotFather on Telegram.
43func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
44 bot := &BotAPI{
45 Token: token,
46 Client: client,
47 Buffer: 100,
48 }
49
50 self, err := bot.GetMe()
51 if err != nil {
52 return nil, err
53 }
54
55 bot.Self = self
56
57 return bot, nil
58}
59
60// MakeRequest makes a request to a specific endpoint with our token.
61func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
62 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
63
64 resp, err := bot.Client.PostForm(method, params)
65 if err != nil {
66 return APIResponse{}, err
67 }
68 defer resp.Body.Close()
69
70 if resp.StatusCode == http.StatusForbidden {
71 return APIResponse{}, errors.New(ErrAPIForbidden)
72 }
73
74 if resp.StatusCode != http.StatusOK {
75 return APIResponse{}, errors.New(http.StatusText(resp.StatusCode))
76 }
77
78 bytes, err := ioutil.ReadAll(resp.Body)
79 if err != nil {
80 return APIResponse{}, err
81 }
82
83 if bot.Debug {
84 log.Println(endpoint, string(bytes))
85 }
86
87 var apiResp APIResponse
88 json.Unmarshal(bytes, &apiResp)
89
90 if !apiResp.Ok {
91 return apiResp, errors.New(apiResp.Description)
92 }
93
94 return apiResp, nil
95}
96
97// makeMessageRequest makes a request to a method that returns a Message.
98func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) {
99 resp, err := bot.MakeRequest(endpoint, params)
100 if err != nil {
101 return Message{}, err
102 }
103
104 var message Message
105 json.Unmarshal(resp.Result, &message)
106
107 bot.debugLog(endpoint, params, message)
108
109 return message, 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// Send will send a Chattable item to Telegram.
247//
248// It requires the Chattable to send.
249func (bot *BotAPI) Send(c Chattable) (Message, error) {
250 switch c.(type) {
251 case Fileable:
252 return bot.sendFile(c.(Fileable))
253 default:
254 return bot.sendChattable(c)
255 }
256}
257
258// debugLog checks if the bot is currently running in debug mode, and if
259// so will display information about the request and response in the
260// debug log.
261func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
262 if bot.Debug {
263 log.Printf("%s req : %+v\n", context, v)
264 log.Printf("%s resp: %+v\n", context, message)
265 }
266}
267
268// sendExisting will send a Message with an existing file to Telegram.
269func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
270 v, err := config.values()
271
272 if err != nil {
273 return Message{}, err
274 }
275
276 message, err := bot.makeMessageRequest(method, v)
277 if err != nil {
278 return Message{}, err
279 }
280
281 return message, nil
282}
283
284// uploadAndSend will send a Message with a new file to Telegram.
285func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
286 params, err := config.params()
287 if err != nil {
288 return Message{}, err
289 }
290
291 file := config.getFile()
292
293 resp, err := bot.UploadFile(method, params, config.name(), file)
294 if err != nil {
295 return Message{}, err
296 }
297
298 var message Message
299 json.Unmarshal(resp.Result, &message)
300
301 bot.debugLog(method, nil, message)
302
303 return message, nil
304}
305
306// sendFile determines if the file is using an existing file or uploading
307// a new file, then sends it as needed.
308func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
309 if config.useExistingFile() {
310 return bot.sendExisting(config.method(), config)
311 }
312
313 return bot.uploadAndSend(config.method(), config)
314}
315
316// sendChattable sends a Chattable.
317func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
318 v, err := config.values()
319 if err != nil {
320 return Message{}, err
321 }
322
323 message, err := bot.makeMessageRequest(config.method(), v)
324
325 if err != nil {
326 return Message{}, err
327 }
328
329 return message, nil
330}
331
332// GetUserProfilePhotos gets a user's profile photos.
333//
334// It requires UserID.
335// Offset and Limit are optional.
336func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
337 v := url.Values{}
338 v.Add("user_id", strconv.Itoa(config.UserID))
339 if config.Offset != 0 {
340 v.Add("offset", strconv.Itoa(config.Offset))
341 }
342 if config.Limit != 0 {
343 v.Add("limit", strconv.Itoa(config.Limit))
344 }
345
346 resp, err := bot.MakeRequest("getUserProfilePhotos", v)
347 if err != nil {
348 return UserProfilePhotos{}, err
349 }
350
351 var profilePhotos UserProfilePhotos
352 json.Unmarshal(resp.Result, &profilePhotos)
353
354 bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
355
356 return profilePhotos, nil
357}
358
359// GetFile returns a File which can download a file from Telegram.
360//
361// Requires FileID.
362func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
363 v := url.Values{}
364 v.Add("file_id", config.FileID)
365
366 resp, err := bot.MakeRequest("getFile", v)
367 if err != nil {
368 return File{}, err
369 }
370
371 var file File
372 json.Unmarshal(resp.Result, &file)
373
374 bot.debugLog("GetFile", v, file)
375
376 return file, nil
377}
378
379// GetUpdates fetches updates.
380// If a WebHook is set, this will not return any data!
381//
382// Offset, Limit, and Timeout are optional.
383// To avoid stale items, set Offset to one higher than the previous item.
384// Set Timeout to a large number to reduce requests so you can get updates
385// instantly instead of having to wait between requests.
386func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
387 v := url.Values{}
388 if config.Offset != 0 {
389 v.Add("offset", strconv.Itoa(config.Offset))
390 }
391 if config.Limit > 0 {
392 v.Add("limit", strconv.Itoa(config.Limit))
393 }
394 if config.Timeout > 0 {
395 v.Add("timeout", strconv.Itoa(config.Timeout))
396 }
397
398 resp, err := bot.MakeRequest("getUpdates", v)
399 if err != nil {
400 return []Update{}, err
401 }
402
403 var updates []Update
404 json.Unmarshal(resp.Result, &updates)
405
406 bot.debugLog("getUpdates", v, updates)
407
408 return updates, nil
409}
410
411// RemoveWebhook unsets the webhook.
412func (bot *BotAPI) RemoveWebhook() (APIResponse, error) {
413 return bot.MakeRequest("setWebhook", url.Values{})
414}
415
416// SetWebhook sets a webhook.
417//
418// If this is set, GetUpdates will not get any data!
419//
420// If you do not have a legitimate TLS certificate, you need to include
421// your self signed certificate with the config.
422func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
423
424 if config.Certificate == nil {
425 v := url.Values{}
426 v.Add("url", config.URL.String())
427 if config.MaxConnections != 0 {
428 v.Add("max_connections", strconv.Itoa(config.MaxConnections))
429 }
430
431 return bot.MakeRequest("setWebhook", v)
432 }
433
434 params := make(map[string]string)
435 params["url"] = config.URL.String()
436 if config.MaxConnections != 0 {
437 params["max_connections"] = strconv.Itoa(config.MaxConnections)
438 }
439
440 resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
441 if err != nil {
442 return APIResponse{}, err
443 }
444
445 return resp, nil
446}
447
448// GetWebhookInfo allows you to fetch information about a webhook and if
449// one currently is set, along with pending update count and error messages.
450func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) {
451 resp, err := bot.MakeRequest("getWebhookInfo", url.Values{})
452 if err != nil {
453 return WebhookInfo{}, err
454 }
455
456 var info WebhookInfo
457 err = json.Unmarshal(resp.Result, &info)
458
459 return info, err
460}
461
462// GetUpdatesChan starts and returns a channel for getting updates.
463func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) {
464 ch := make(chan Update, bot.Buffer)
465
466 go func() {
467 for {
468 updates, err := bot.GetUpdates(config)
469 if err != nil {
470 log.Println(err)
471 log.Println("Failed to get updates, retrying in 3 seconds...")
472 time.Sleep(time.Second * 3)
473
474 continue
475 }
476
477 for _, update := range updates {
478 if update.UpdateID >= config.Offset {
479 config.Offset = update.UpdateID + 1
480 ch <- update
481 }
482 }
483 }
484 }()
485
486 return ch, nil
487}
488
489// ListenForWebhook registers a http handler for a webhook.
490func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel {
491 ch := make(chan Update, bot.Buffer)
492
493 http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
494 bytes, _ := ioutil.ReadAll(r.Body)
495
496 var update Update
497 json.Unmarshal(bytes, &update)
498
499 ch <- update
500 })
501
502 return ch
503}
504
505// AnswerInlineQuery sends a response to an inline query.
506//
507// Note that you must respond to an inline query within 30 seconds.
508func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) {
509 v := url.Values{}
510
511 v.Add("inline_query_id", config.InlineQueryID)
512 v.Add("cache_time", strconv.Itoa(config.CacheTime))
513 v.Add("is_personal", strconv.FormatBool(config.IsPersonal))
514 v.Add("next_offset", config.NextOffset)
515 data, err := json.Marshal(config.Results)
516 if err != nil {
517 return APIResponse{}, err
518 }
519 v.Add("results", string(data))
520 v.Add("switch_pm_text", config.SwitchPMText)
521 v.Add("switch_pm_parameter", config.SwitchPMParameter)
522
523 bot.debugLog("answerInlineQuery", v, nil)
524
525 return bot.MakeRequest("answerInlineQuery", v)
526}
527
528// AnswerCallbackQuery sends a response to an inline query callback.
529func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) {
530 v := url.Values{}
531
532 v.Add("callback_query_id", config.CallbackQueryID)
533 if config.Text != "" {
534 v.Add("text", config.Text)
535 }
536 v.Add("show_alert", strconv.FormatBool(config.ShowAlert))
537 if config.URL != "" {
538 v.Add("url", config.URL)
539 }
540 v.Add("cache_time", strconv.Itoa(config.CacheTime))
541
542 bot.debugLog("answerCallbackQuery", v, nil)
543
544 return bot.MakeRequest("answerCallbackQuery", v)
545}
546
547// KickChatMember kicks a user from a chat. Note that this only will work
548// in supergroups, and requires the bot to be an admin. Also note they
549// will be unable to rejoin until they are unbanned.
550func (bot *BotAPI) KickChatMember(config ChatMemberConfig) (APIResponse, error) {
551 v := url.Values{}
552
553 if config.SuperGroupUsername == "" {
554 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
555 } else {
556 v.Add("chat_id", config.SuperGroupUsername)
557 }
558 v.Add("user_id", strconv.Itoa(config.UserID))
559
560 bot.debugLog("kickChatMember", v, nil)
561
562 return bot.MakeRequest("kickChatMember", v)
563}
564
565// LeaveChat makes the bot leave the chat.
566func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) {
567 v := url.Values{}
568
569 if config.SuperGroupUsername == "" {
570 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
571 } else {
572 v.Add("chat_id", config.SuperGroupUsername)
573 }
574
575 bot.debugLog("leaveChat", v, nil)
576
577 return bot.MakeRequest("leaveChat", v)
578}
579
580// GetChat gets information about a chat.
581func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) {
582 v := url.Values{}
583
584 if config.SuperGroupUsername == "" {
585 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
586 } else {
587 v.Add("chat_id", config.SuperGroupUsername)
588 }
589
590 resp, err := bot.MakeRequest("getChat", v)
591 if err != nil {
592 return Chat{}, err
593 }
594
595 var chat Chat
596 err = json.Unmarshal(resp.Result, &chat)
597
598 bot.debugLog("getChat", v, chat)
599
600 return chat, err
601}
602
603// GetChatAdministrators gets a list of administrators in the chat.
604//
605// If none have been appointed, only the creator will be returned.
606// Bots are not shown, even if they are an administrator.
607func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
608 v := url.Values{}
609
610 if config.SuperGroupUsername == "" {
611 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
612 } else {
613 v.Add("chat_id", config.SuperGroupUsername)
614 }
615
616 resp, err := bot.MakeRequest("getChatAdministrators", v)
617 if err != nil {
618 return []ChatMember{}, err
619 }
620
621 var members []ChatMember
622 err = json.Unmarshal(resp.Result, &members)
623
624 bot.debugLog("getChatAdministrators", v, members)
625
626 return members, err
627}
628
629// GetChatMembersCount gets the number of users in a chat.
630func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) {
631 v := url.Values{}
632
633 if config.SuperGroupUsername == "" {
634 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
635 } else {
636 v.Add("chat_id", config.SuperGroupUsername)
637 }
638
639 resp, err := bot.MakeRequest("getChatMembersCount", v)
640 if err != nil {
641 return -1, err
642 }
643
644 var count int
645 err = json.Unmarshal(resp.Result, &count)
646
647 bot.debugLog("getChatMembersCount", v, count)
648
649 return count, err
650}
651
652// GetChatMember gets a specific chat member.
653func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
654 v := url.Values{}
655
656 if config.SuperGroupUsername == "" {
657 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
658 } else {
659 v.Add("chat_id", config.SuperGroupUsername)
660 }
661 v.Add("user_id", strconv.Itoa(config.UserID))
662
663 resp, err := bot.MakeRequest("getChatMember", v)
664 if err != nil {
665 return ChatMember{}, err
666 }
667
668 var member ChatMember
669 err = json.Unmarshal(resp.Result, &member)
670
671 bot.debugLog("getChatMember", v, member)
672
673 return member, err
674}
675
676// UnbanChatMember unbans a user from a chat. Note that this only will work
677// in supergroups, and requires the bot to be an admin.
678func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) {
679 v := url.Values{}
680
681 if config.SuperGroupUsername == "" {
682 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
683 } else {
684 v.Add("chat_id", config.SuperGroupUsername)
685 }
686 v.Add("user_id", strconv.Itoa(config.UserID))
687
688 bot.debugLog("unbanChatMember", v, nil)
689
690 return bot.MakeRequest("unbanChatMember", v)
691}
692
693// GetGameHighScores allows you to get the high scores for a game.
694func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
695 v, _ := config.values()
696
697 resp, err := bot.MakeRequest(config.method(), v)
698 if err != nil {
699 return []GameHighScore{}, err
700 }
701
702 var highScores []GameHighScore
703 err = json.Unmarshal(resp.Result, &highScores)
704
705 return highScores, err
706}
707
708func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) {
709 v := url.Values{}
710
711 v.Add("shipping_query_id", config.ShippingQueryID)
712 v.Add("ok", strconv.FormatBool(config.Ok))
713 if config.Ok == true {
714 data, err := json.Marshal(config.ShippingOptions)
715 if err != nil {
716 return APIResponse{}, err
717 }
718 v.Add("shipping_options", string(data))
719 } else {
720 v.Add("error_message", config.ErrorMessage)
721 }
722
723 bot.debugLog("answerShippingQuery", v, nil)
724
725 return bot.MakeRequest("answerShippingQuery", v)
726}
727
728func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) {
729 v := url.Values{}
730
731 v.Add("pre_checkout_query_id", config.PreCheckoutQueryID)
732 v.Add("ok", strconv.FormatBool(config.Ok))
733 if config.Ok != true {
734 v.Add("error", config.ErrorMessage)
735 }
736
737 bot.debugLog("answerPreCheckoutQuery", v, nil)
738
739 return bot.MakeRequest("answerPreCheckoutQuery", v)
740}