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