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 shutdownChannel chan interface{}
32}
33
34// NewBotAPI creates a new BotAPI instance.
35//
36// It requires a token, provided by @BotFather on Telegram.
37func NewBotAPI(token string) (*BotAPI, error) {
38 return NewBotAPIWithClient(token, &http.Client{})
39}
40
41// NewBotAPIWithClient creates a new BotAPI instance
42// and allows you to pass a http.Client.
43//
44// It requires a token, provided by @BotFather on Telegram.
45func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
46 bot := &BotAPI{
47 Token: token,
48 Client: client,
49 Buffer: 100,
50 shutdownChannel: make(chan interface{}),
51 }
52
53 self, err := bot.GetMe()
54 if err != nil {
55 return nil, err
56 }
57
58 bot.Self = self
59
60 return bot, nil
61}
62
63// MakeRequest makes a request to a specific endpoint with our token.
64func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
65 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
66
67 resp, err := bot.Client.PostForm(method, params)
68 if err != nil {
69 return APIResponse{}, err
70 }
71 defer resp.Body.Close()
72
73 var apiResp APIResponse
74 bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp)
75 if err != nil {
76 return apiResp, err
77 }
78
79 if bot.Debug {
80 log.Printf("%s resp: %s", endpoint, bytes)
81 }
82
83 if !apiResp.Ok {
84 return apiResp, errors.New(apiResp.Description)
85 }
86
87 return apiResp, nil
88}
89
90// decodeAPIResponse decode response and return slice of bytes if debug enabled.
91// If debug disabled, just decode http.Response.Body stream to APIResponse struct
92// for efficient memory usage
93func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) {
94 if !bot.Debug {
95 dec := json.NewDecoder(responseBody)
96 err = dec.Decode(resp)
97 return
98 }
99
100 // if debug, read reponse body
101 data, err := ioutil.ReadAll(responseBody)
102 if err != nil {
103 return
104 }
105
106 err = json.Unmarshal(data, resp)
107 if err != nil {
108 return
109 }
110
111 return data, nil
112}
113
114// makeMessageRequest makes a request to a method that returns a Message.
115func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) {
116 resp, err := bot.MakeRequest(endpoint, params)
117 if err != nil {
118 return Message{}, err
119 }
120
121 var message Message
122 json.Unmarshal(resp.Result, &message)
123
124 bot.debugLog(endpoint, params, message)
125
126 return message, nil
127}
128
129// UploadFile makes a request to the API with a file.
130//
131// Requires the parameter to hold the file not be in the params.
132// File should be a string to a file path, a FileBytes struct,
133// a FileReader struct, or a url.URL.
134//
135// Note that if your FileReader has a size set to -1, it will read
136// the file into memory to calculate a size.
137func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
138 ms := multipartstreamer.New()
139
140 switch f := file.(type) {
141 case string:
142 ms.WriteFields(params)
143
144 fileHandle, err := os.Open(f)
145 if err != nil {
146 return APIResponse{}, err
147 }
148 defer fileHandle.Close()
149
150 fi, err := os.Stat(f)
151 if err != nil {
152 return APIResponse{}, err
153 }
154
155 ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
156 case FileBytes:
157 ms.WriteFields(params)
158
159 buf := bytes.NewBuffer(f.Bytes)
160 ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
161 case FileReader:
162 ms.WriteFields(params)
163
164 if f.Size != -1 {
165 ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
166
167 break
168 }
169
170 data, err := ioutil.ReadAll(f.Reader)
171 if err != nil {
172 return APIResponse{}, err
173 }
174
175 buf := bytes.NewBuffer(data)
176
177 ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
178 case url.URL:
179 params[fieldname] = f.String()
180
181 ms.WriteFields(params)
182 default:
183 return APIResponse{}, errors.New(ErrBadFileType)
184 }
185
186 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
187
188 req, err := http.NewRequest("POST", method, nil)
189 if err != nil {
190 return APIResponse{}, err
191 }
192
193 ms.SetupRequest(req)
194
195 res, err := bot.Client.Do(req)
196 if err != nil {
197 return APIResponse{}, err
198 }
199 defer res.Body.Close()
200
201 bytes, err := ioutil.ReadAll(res.Body)
202 if err != nil {
203 return APIResponse{}, err
204 }
205
206 if bot.Debug {
207 log.Println(string(bytes))
208 }
209
210 var apiResp APIResponse
211
212 err = json.Unmarshal(bytes, &apiResp)
213 if err != nil {
214 return APIResponse{}, err
215 }
216
217 if !apiResp.Ok {
218 return APIResponse{}, errors.New(apiResp.Description)
219 }
220
221 return apiResp, nil
222}
223
224// GetFileDirectURL returns direct URL to file
225//
226// It requires the FileID.
227func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) {
228 file, err := bot.GetFile(FileConfig{fileID})
229
230 if err != nil {
231 return "", err
232 }
233
234 return file.Link(bot.Token), nil
235}
236
237// GetMe fetches the currently authenticated bot.
238//
239// This method is called upon creation to validate the token,
240// and so you may get this data from BotAPI.Self without the need for
241// another request.
242func (bot *BotAPI) GetMe() (User, error) {
243 resp, err := bot.MakeRequest("getMe", nil)
244 if err != nil {
245 return User{}, err
246 }
247
248 var user User
249 json.Unmarshal(resp.Result, &user)
250
251 bot.debugLog("getMe", nil, user)
252
253 return user, nil
254}
255
256// IsMessageToMe returns true if message directed to this bot.
257//
258// It requires the Message.
259func (bot *BotAPI) IsMessageToMe(message Message) bool {
260 return strings.Contains(message.Text, "@"+bot.Self.UserName)
261}
262
263// Send will send a Chattable item to Telegram.
264//
265// It requires the Chattable to send.
266func (bot *BotAPI) Send(c Chattable) (Message, error) {
267 switch c.(type) {
268 case Fileable:
269 return bot.sendFile(c.(Fileable))
270 default:
271 return bot.sendChattable(c)
272 }
273}
274
275// debugLog checks if the bot is currently running in debug mode, and if
276// so will display information about the request and response in the
277// debug log.
278func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
279 if bot.Debug {
280 log.Printf("%s req : %+v\n", context, v)
281 log.Printf("%s resp: %+v\n", context, message)
282 }
283}
284
285// sendExisting will send a Message with an existing file to Telegram.
286func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
287 v, err := config.values()
288
289 if err != nil {
290 return Message{}, err
291 }
292
293 message, err := bot.makeMessageRequest(method, v)
294 if err != nil {
295 return Message{}, err
296 }
297
298 return message, nil
299}
300
301// uploadAndSend will send a Message with a new file to Telegram.
302func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
303 params, err := config.params()
304 if err != nil {
305 return Message{}, err
306 }
307
308 file := config.getFile()
309
310 resp, err := bot.UploadFile(method, params, config.name(), file)
311 if err != nil {
312 return Message{}, err
313 }
314
315 var message Message
316 json.Unmarshal(resp.Result, &message)
317
318 bot.debugLog(method, nil, message)
319
320 return message, nil
321}
322
323// sendFile determines if the file is using an existing file or uploading
324// a new file, then sends it as needed.
325func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
326 if config.useExistingFile() {
327 return bot.sendExisting(config.method(), config)
328 }
329
330 return bot.uploadAndSend(config.method(), config)
331}
332
333// sendChattable sends a Chattable.
334func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
335 v, err := config.values()
336 if err != nil {
337 return Message{}, err
338 }
339
340 message, err := bot.makeMessageRequest(config.method(), v)
341
342 if err != nil {
343 return Message{}, err
344 }
345
346 return message, nil
347}
348
349// GetUserProfilePhotos gets a user's profile photos.
350//
351// It requires UserID.
352// Offset and Limit are optional.
353func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
354 v := url.Values{}
355 v.Add("user_id", strconv.Itoa(config.UserID))
356 if config.Offset != 0 {
357 v.Add("offset", strconv.Itoa(config.Offset))
358 }
359 if config.Limit != 0 {
360 v.Add("limit", strconv.Itoa(config.Limit))
361 }
362
363 resp, err := bot.MakeRequest("getUserProfilePhotos", v)
364 if err != nil {
365 return UserProfilePhotos{}, err
366 }
367
368 var profilePhotos UserProfilePhotos
369 json.Unmarshal(resp.Result, &profilePhotos)
370
371 bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
372
373 return profilePhotos, nil
374}
375
376// GetFile returns a File which can download a file from Telegram.
377//
378// Requires FileID.
379func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
380 v := url.Values{}
381 v.Add("file_id", config.FileID)
382
383 resp, err := bot.MakeRequest("getFile", v)
384 if err != nil {
385 return File{}, err
386 }
387
388 var file File
389 json.Unmarshal(resp.Result, &file)
390
391 bot.debugLog("GetFile", v, file)
392
393 return file, nil
394}
395
396// GetUpdates fetches updates.
397// If a WebHook is set, this will not return any data!
398//
399// Offset, Limit, and Timeout are optional.
400// To avoid stale items, set Offset to one higher than the previous item.
401// Set Timeout to a large number to reduce requests so you can get updates
402// instantly instead of having to wait between requests.
403func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
404 v := url.Values{}
405 if config.Offset != 0 {
406 v.Add("offset", strconv.Itoa(config.Offset))
407 }
408 if config.Limit > 0 {
409 v.Add("limit", strconv.Itoa(config.Limit))
410 }
411 if config.Timeout > 0 {
412 v.Add("timeout", strconv.Itoa(config.Timeout))
413 }
414
415 resp, err := bot.MakeRequest("getUpdates", v)
416 if err != nil {
417 return []Update{}, err
418 }
419
420 var updates []Update
421 json.Unmarshal(resp.Result, &updates)
422
423 bot.debugLog("getUpdates", v, updates)
424
425 return updates, nil
426}
427
428// RemoveWebhook unsets the webhook.
429func (bot *BotAPI) RemoveWebhook() (APIResponse, error) {
430 return bot.MakeRequest("setWebhook", url.Values{})
431}
432
433// SetWebhook sets a webhook.
434//
435// If this is set, GetUpdates will not get any data!
436//
437// If you do not have a legitimate TLS certificate, you need to include
438// your self signed certificate with the config.
439func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
440
441 if config.Certificate == nil {
442 v := url.Values{}
443 v.Add("url", config.URL.String())
444 if config.MaxConnections != 0 {
445 v.Add("max_connections", strconv.Itoa(config.MaxConnections))
446 }
447
448 return bot.MakeRequest("setWebhook", v)
449 }
450
451 params := make(map[string]string)
452 params["url"] = config.URL.String()
453 if config.MaxConnections != 0 {
454 params["max_connections"] = strconv.Itoa(config.MaxConnections)
455 }
456
457 resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
458 if err != nil {
459 return APIResponse{}, err
460 }
461
462 return resp, nil
463}
464
465// GetWebhookInfo allows you to fetch information about a webhook and if
466// one currently is set, along with pending update count and error messages.
467func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) {
468 resp, err := bot.MakeRequest("getWebhookInfo", url.Values{})
469 if err != nil {
470 return WebhookInfo{}, err
471 }
472
473 var info WebhookInfo
474 err = json.Unmarshal(resp.Result, &info)
475
476 return info, err
477}
478
479// GetUpdatesChan starts and returns a channel for getting updates.
480func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) {
481 ch := make(chan Update, bot.Buffer)
482
483 go func() {
484 for {
485 select {
486 case <-bot.shutdownChannel:
487 return
488 default:
489 }
490
491 updates, err := bot.GetUpdates(config)
492 if err != nil {
493 log.Println(err)
494 log.Println("Failed to get updates, retrying in 3 seconds...")
495 time.Sleep(time.Second * 3)
496
497 continue
498 }
499
500 for _, update := range updates {
501 if update.UpdateID >= config.Offset {
502 config.Offset = update.UpdateID + 1
503 ch <- update
504 }
505 }
506 }
507 }()
508
509 return ch, nil
510}
511
512// StopReceivingUpdates stops the go routine which receives updates
513func (bot *BotAPI) StopReceivingUpdates() {
514 if bot.Debug {
515 log.Println("Stopping the update receiver routine...")
516 }
517 close(bot.shutdownChannel)
518}
519
520// ListenForWebhook registers a http handler for a webhook.
521func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel {
522 ch := make(chan Update, bot.Buffer)
523
524 http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
525 bytes, _ := ioutil.ReadAll(r.Body)
526
527 var update Update
528 json.Unmarshal(bytes, &update)
529
530 ch <- update
531 })
532
533 return ch
534}
535
536// AnswerInlineQuery sends a response to an inline query.
537//
538// Note that you must respond to an inline query within 30 seconds.
539func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) {
540 v := url.Values{}
541
542 v.Add("inline_query_id", config.InlineQueryID)
543 v.Add("cache_time", strconv.Itoa(config.CacheTime))
544 v.Add("is_personal", strconv.FormatBool(config.IsPersonal))
545 v.Add("next_offset", config.NextOffset)
546 data, err := json.Marshal(config.Results)
547 if err != nil {
548 return APIResponse{}, err
549 }
550 v.Add("results", string(data))
551 v.Add("switch_pm_text", config.SwitchPMText)
552 v.Add("switch_pm_parameter", config.SwitchPMParameter)
553
554 bot.debugLog("answerInlineQuery", v, nil)
555
556 return bot.MakeRequest("answerInlineQuery", v)
557}
558
559// AnswerCallbackQuery sends a response to an inline query callback.
560func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) {
561 v := url.Values{}
562
563 v.Add("callback_query_id", config.CallbackQueryID)
564 if config.Text != "" {
565 v.Add("text", config.Text)
566 }
567 v.Add("show_alert", strconv.FormatBool(config.ShowAlert))
568 if config.URL != "" {
569 v.Add("url", config.URL)
570 }
571 v.Add("cache_time", strconv.Itoa(config.CacheTime))
572
573 bot.debugLog("answerCallbackQuery", v, nil)
574
575 return bot.MakeRequest("answerCallbackQuery", v)
576}
577
578// KickChatMember kicks a user from a chat. Note that this only will work
579// in supergroups, and requires the bot to be an admin. Also note they
580// will be unable to rejoin until they are unbanned.
581func (bot *BotAPI) KickChatMember(config KickChatMemberConfig) (APIResponse, 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 v.Add("user_id", strconv.Itoa(config.UserID))
590
591 if config.UntilDate != 0 {
592 v.Add("until_date", strconv.FormatInt(config.UntilDate, 10))
593 }
594
595 bot.debugLog("kickChatMember", v, nil)
596
597 return bot.MakeRequest("kickChatMember", v)
598}
599
600// LeaveChat makes the bot leave the chat.
601func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) {
602 v := url.Values{}
603
604 if config.SuperGroupUsername == "" {
605 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
606 } else {
607 v.Add("chat_id", config.SuperGroupUsername)
608 }
609
610 bot.debugLog("leaveChat", v, nil)
611
612 return bot.MakeRequest("leaveChat", v)
613}
614
615// GetChat gets information about a chat.
616func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) {
617 v := url.Values{}
618
619 if config.SuperGroupUsername == "" {
620 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
621 } else {
622 v.Add("chat_id", config.SuperGroupUsername)
623 }
624
625 resp, err := bot.MakeRequest("getChat", v)
626 if err != nil {
627 return Chat{}, err
628 }
629
630 var chat Chat
631 err = json.Unmarshal(resp.Result, &chat)
632
633 bot.debugLog("getChat", v, chat)
634
635 return chat, err
636}
637
638// GetChatAdministrators gets a list of administrators in the chat.
639//
640// If none have been appointed, only the creator will be returned.
641// Bots are not shown, even if they are an administrator.
642func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
643 v := url.Values{}
644
645 if config.SuperGroupUsername == "" {
646 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
647 } else {
648 v.Add("chat_id", config.SuperGroupUsername)
649 }
650
651 resp, err := bot.MakeRequest("getChatAdministrators", v)
652 if err != nil {
653 return []ChatMember{}, err
654 }
655
656 var members []ChatMember
657 err = json.Unmarshal(resp.Result, &members)
658
659 bot.debugLog("getChatAdministrators", v, members)
660
661 return members, err
662}
663
664// GetChatMembersCount gets the number of users in a chat.
665func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) {
666 v := url.Values{}
667
668 if config.SuperGroupUsername == "" {
669 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
670 } else {
671 v.Add("chat_id", config.SuperGroupUsername)
672 }
673
674 resp, err := bot.MakeRequest("getChatMembersCount", v)
675 if err != nil {
676 return -1, err
677 }
678
679 var count int
680 err = json.Unmarshal(resp.Result, &count)
681
682 bot.debugLog("getChatMembersCount", v, count)
683
684 return count, err
685}
686
687// GetChatMember gets a specific chat member.
688func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
689 v := url.Values{}
690
691 if config.SuperGroupUsername == "" {
692 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
693 } else {
694 v.Add("chat_id", config.SuperGroupUsername)
695 }
696 v.Add("user_id", strconv.Itoa(config.UserID))
697
698 resp, err := bot.MakeRequest("getChatMember", v)
699 if err != nil {
700 return ChatMember{}, err
701 }
702
703 var member ChatMember
704 err = json.Unmarshal(resp.Result, &member)
705
706 bot.debugLog("getChatMember", v, member)
707
708 return member, err
709}
710
711// UnbanChatMember unbans a user from a chat. Note that this only will work
712// in supergroups and channels, and requires the bot to be an admin.
713func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) {
714 v := url.Values{}
715
716 if config.SuperGroupUsername != "" {
717 v.Add("chat_id", config.SuperGroupUsername)
718 } else if config.ChannelUsername != "" {
719 v.Add("chat_id", config.ChannelUsername)
720 } else {
721 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
722 }
723 v.Add("user_id", strconv.Itoa(config.UserID))
724
725 bot.debugLog("unbanChatMember", v, nil)
726
727 return bot.MakeRequest("unbanChatMember", v)
728}
729
730// RestrictChatMember to restrict a user in a supergroup. The bot must be an
731//administrator in the supergroup for this to work and must have the
732//appropriate admin rights. Pass True for all boolean parameters to lift
733//restrictions from a user. Returns True on success.
734func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIResponse, error) {
735 v := url.Values{}
736
737 if config.SuperGroupUsername != "" {
738 v.Add("chat_id", config.SuperGroupUsername)
739 } else if config.ChannelUsername != "" {
740 v.Add("chat_id", config.ChannelUsername)
741 } else {
742 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
743 }
744 v.Add("user_id", strconv.Itoa(config.UserID))
745
746 if &config.CanSendMessages != nil {
747 v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages))
748 }
749 if &config.CanSendMediaMessages != nil {
750 v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages))
751 }
752 if &config.CanSendOtherMessages != nil {
753 v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages))
754 }
755 if &config.CanAddWebPagePreviews != nil {
756 v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews))
757 }
758 if config.UntilDate != 0 {
759 v.Add("until_date", strconv.FormatInt(config.UntilDate, 10))
760 }
761
762 bot.debugLog("restrictChatMember", v, nil)
763
764 return bot.MakeRequest("restrictChatMember", v)
765}
766
767// PromoteChatMember add admin rights to user
768func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) {
769 v := url.Values{}
770
771 if config.SuperGroupUsername != "" {
772 v.Add("chat_id", config.SuperGroupUsername)
773 } else if config.ChannelUsername != "" {
774 v.Add("chat_id", config.ChannelUsername)
775 } else {
776 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
777 }
778 v.Add("user_id", strconv.Itoa(config.UserID))
779
780 if &config.CanChangeInfo != nil {
781 v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo))
782 }
783 if &config.CanPostMessages != nil {
784 v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages))
785 }
786 if &config.CanEditMessages != nil {
787 v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages))
788 }
789 if &config.CanDeleteMessages != nil {
790 v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages))
791 }
792 if &config.CanInviteUsers != nil {
793 v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers))
794 }
795 if &config.CanRestrictMembers != nil {
796 v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers))
797 }
798 if &config.CanPinMessages != nil {
799 v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages))
800 }
801 if &config.CanPromoteMembers != nil {
802 v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers))
803 }
804
805 bot.debugLog("promoteChatMember", v, nil)
806
807 return bot.MakeRequest("promoteChatMember", v)
808}
809
810// GetGameHighScores allows you to get the high scores for a game.
811func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
812 v, _ := config.values()
813
814 resp, err := bot.MakeRequest(config.method(), v)
815 if err != nil {
816 return []GameHighScore{}, err
817 }
818
819 var highScores []GameHighScore
820 err = json.Unmarshal(resp.Result, &highScores)
821
822 return highScores, err
823}
824
825// AnswerShippingQuery allows you to reply to Update with shipping_query parameter.
826func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) {
827 v := url.Values{}
828
829 v.Add("shipping_query_id", config.ShippingQueryID)
830 v.Add("ok", strconv.FormatBool(config.OK))
831 if config.OK == true {
832 data, err := json.Marshal(config.ShippingOptions)
833 if err != nil {
834 return APIResponse{}, err
835 }
836 v.Add("shipping_options", string(data))
837 } else {
838 v.Add("error_message", config.ErrorMessage)
839 }
840
841 bot.debugLog("answerShippingQuery", v, nil)
842
843 return bot.MakeRequest("answerShippingQuery", v)
844}
845
846// AnswerPreCheckoutQuery allows you to reply to Update with pre_checkout_query.
847func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) {
848 v := url.Values{}
849
850 v.Add("pre_checkout_query_id", config.PreCheckoutQueryID)
851 v.Add("ok", strconv.FormatBool(config.OK))
852 if config.OK != true {
853 v.Add("error", config.ErrorMessage)
854 }
855
856 bot.debugLog("answerPreCheckoutQuery", v, nil)
857
858 return bot.MakeRequest("answerPreCheckoutQuery", v)
859}
860
861// DeleteMessage deletes a message in a chat
862func (bot *BotAPI) DeleteMessage(config DeleteMessageConfig) (APIResponse, error) {
863 v, err := config.values()
864 if err != nil {
865 return APIResponse{}, err
866 }
867
868 bot.debugLog(config.method(), v, nil)
869
870 return bot.MakeRequest(config.method(), v)
871}
872
873// GetInviteLink get InviteLink for a chat
874func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) {
875 v := url.Values{}
876
877 if config.SuperGroupUsername == "" {
878 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
879 } else {
880 v.Add("chat_id", config.SuperGroupUsername)
881 }
882
883 resp, err := bot.MakeRequest("exportChatInviteLink", v)
884 if err != nil {
885 return "", err
886 }
887
888 var inviteLink string
889 err = json.Unmarshal(resp.Result, &inviteLink)
890
891 return inviteLink, err
892}
893
894// PinChatMessage pin message in supergroup
895func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) {
896 v, err := config.values()
897 if err != nil {
898 return APIResponse{}, err
899 }
900
901 bot.debugLog(config.method(), v, nil)
902
903 return bot.MakeRequest(config.method(), v)
904}
905
906// UnpinChatMessage unpin message in supergroup
907func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) {
908 v, err := config.values()
909 if err != nil {
910 return APIResponse{}, err
911 }
912
913 bot.debugLog(config.method(), v, nil)
914
915 return bot.MakeRequest(config.method(), v)
916}
917
918// SetChatTitle change title of chat.
919func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (APIResponse, error) {
920 v, err := config.values()
921 if err != nil {
922 return APIResponse{}, err
923 }
924
925 bot.debugLog(config.method(), v, nil)
926
927 return bot.MakeRequest(config.method(), v)
928}
929
930// SetChatDescription change description of chat.
931func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) {
932 v, err := config.values()
933 if err != nil {
934 return APIResponse{}, err
935 }
936
937 bot.debugLog(config.method(), v, nil)
938
939 return bot.MakeRequest(config.method(), v)
940}
941
942// SetChatPhoto change photo of chat.
943func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) {
944 params, err := config.params()
945 if err != nil {
946 return APIResponse{}, err
947 }
948
949 file := config.getFile()
950
951 return bot.UploadFile(config.method(), params, config.name(), file)
952}
953
954// DeleteChatPhoto delete photo of chat.
955func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) {
956 v, err := config.values()
957 if err != nil {
958 return APIResponse{}, err
959 }
960
961 bot.debugLog(config.method(), v, nil)
962
963 return bot.MakeRequest(config.method(), v)
964}