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