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("deleteWebhook", 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 return
499 default:
500 }
501
502 updates, err := bot.GetUpdates(config)
503 if err != nil {
504 log.Println(err)
505 log.Println("Failed to get updates, retrying in 3 seconds...")
506 time.Sleep(time.Second * 3)
507
508 continue
509 }
510
511 for _, update := range updates {
512 if update.UpdateID >= config.Offset {
513 config.Offset = update.UpdateID + 1
514 ch <- update
515 }
516 }
517 }
518 }()
519
520 return ch, nil
521}
522
523// StopReceivingUpdates stops the go routine which receives updates
524func (bot *BotAPI) StopReceivingUpdates() {
525 if bot.Debug {
526 log.Println("Stopping the update receiver routine...")
527 }
528 close(bot.shutdownChannel)
529}
530
531// ListenForWebhook registers a http handler for a webhook.
532func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel {
533 ch := make(chan Update, bot.Buffer)
534
535 http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
536 bytes, _ := ioutil.ReadAll(r.Body)
537 r.Body.Close()
538
539 var update Update
540 json.Unmarshal(bytes, &update)
541
542 ch <- update
543 })
544
545 return ch
546}
547
548// AnswerInlineQuery sends a response to an inline query.
549//
550// Note that you must respond to an inline query within 30 seconds.
551func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) {
552 v := url.Values{}
553
554 v.Add("inline_query_id", config.InlineQueryID)
555 v.Add("cache_time", strconv.Itoa(config.CacheTime))
556 v.Add("is_personal", strconv.FormatBool(config.IsPersonal))
557 v.Add("next_offset", config.NextOffset)
558 data, err := json.Marshal(config.Results)
559 if err != nil {
560 return APIResponse{}, err
561 }
562 v.Add("results", string(data))
563 v.Add("switch_pm_text", config.SwitchPMText)
564 v.Add("switch_pm_parameter", config.SwitchPMParameter)
565
566 bot.debugLog("answerInlineQuery", v, nil)
567
568 return bot.MakeRequest("answerInlineQuery", v)
569}
570
571// AnswerCallbackQuery sends a response to an inline query callback.
572func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) {
573 v := url.Values{}
574
575 v.Add("callback_query_id", config.CallbackQueryID)
576 if config.Text != "" {
577 v.Add("text", config.Text)
578 }
579 v.Add("show_alert", strconv.FormatBool(config.ShowAlert))
580 if config.URL != "" {
581 v.Add("url", config.URL)
582 }
583 v.Add("cache_time", strconv.Itoa(config.CacheTime))
584
585 bot.debugLog("answerCallbackQuery", v, nil)
586
587 return bot.MakeRequest("answerCallbackQuery", v)
588}
589
590// KickChatMember kicks a user from a chat. Note that this only will work
591// in supergroups, and requires the bot to be an admin. Also note they
592// will be unable to rejoin until they are unbanned.
593func (bot *BotAPI) KickChatMember(config KickChatMemberConfig) (APIResponse, error) {
594 v := url.Values{}
595
596 if config.SuperGroupUsername == "" {
597 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
598 } else {
599 v.Add("chat_id", config.SuperGroupUsername)
600 }
601 v.Add("user_id", strconv.Itoa(config.UserID))
602
603 if config.UntilDate != 0 {
604 v.Add("until_date", strconv.FormatInt(config.UntilDate, 10))
605 }
606
607 bot.debugLog("kickChatMember", v, nil)
608
609 return bot.MakeRequest("kickChatMember", v)
610}
611
612// LeaveChat makes the bot leave the chat.
613func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) {
614 v := url.Values{}
615
616 if config.SuperGroupUsername == "" {
617 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
618 } else {
619 v.Add("chat_id", config.SuperGroupUsername)
620 }
621
622 bot.debugLog("leaveChat", v, nil)
623
624 return bot.MakeRequest("leaveChat", v)
625}
626
627// GetChat gets information about a chat.
628func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) {
629 v := url.Values{}
630
631 if config.SuperGroupUsername == "" {
632 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
633 } else {
634 v.Add("chat_id", config.SuperGroupUsername)
635 }
636
637 resp, err := bot.MakeRequest("getChat", v)
638 if err != nil {
639 return Chat{}, err
640 }
641
642 var chat Chat
643 err = json.Unmarshal(resp.Result, &chat)
644
645 bot.debugLog("getChat", v, chat)
646
647 return chat, err
648}
649
650// GetChatAdministrators gets a list of administrators in the chat.
651//
652// If none have been appointed, only the creator will be returned.
653// Bots are not shown, even if they are an administrator.
654func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
655 v := url.Values{}
656
657 if config.SuperGroupUsername == "" {
658 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
659 } else {
660 v.Add("chat_id", config.SuperGroupUsername)
661 }
662
663 resp, err := bot.MakeRequest("getChatAdministrators", v)
664 if err != nil {
665 return []ChatMember{}, err
666 }
667
668 var members []ChatMember
669 err = json.Unmarshal(resp.Result, &members)
670
671 bot.debugLog("getChatAdministrators", v, members)
672
673 return members, err
674}
675
676// GetChatMembersCount gets the number of users in a chat.
677func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) {
678 v := url.Values{}
679
680 if config.SuperGroupUsername == "" {
681 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
682 } else {
683 v.Add("chat_id", config.SuperGroupUsername)
684 }
685
686 resp, err := bot.MakeRequest("getChatMembersCount", v)
687 if err != nil {
688 return -1, err
689 }
690
691 var count int
692 err = json.Unmarshal(resp.Result, &count)
693
694 bot.debugLog("getChatMembersCount", v, count)
695
696 return count, err
697}
698
699// GetChatMember gets a specific chat member.
700func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
701 v := url.Values{}
702
703 if config.SuperGroupUsername == "" {
704 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
705 } else {
706 v.Add("chat_id", config.SuperGroupUsername)
707 }
708 v.Add("user_id", strconv.Itoa(config.UserID))
709
710 resp, err := bot.MakeRequest("getChatMember", v)
711 if err != nil {
712 return ChatMember{}, err
713 }
714
715 var member ChatMember
716 err = json.Unmarshal(resp.Result, &member)
717
718 bot.debugLog("getChatMember", v, member)
719
720 return member, err
721}
722
723// UnbanChatMember unbans a user from a chat. Note that this only will work
724// in supergroups and channels, and requires the bot to be an admin.
725func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) {
726 v := url.Values{}
727
728 if config.SuperGroupUsername != "" {
729 v.Add("chat_id", config.SuperGroupUsername)
730 } else if config.ChannelUsername != "" {
731 v.Add("chat_id", config.ChannelUsername)
732 } else {
733 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
734 }
735 v.Add("user_id", strconv.Itoa(config.UserID))
736
737 bot.debugLog("unbanChatMember", v, nil)
738
739 return bot.MakeRequest("unbanChatMember", v)
740}
741
742// RestrictChatMember to restrict a user in a supergroup. The bot must be an
743//administrator in the supergroup for this to work and must have the
744//appropriate admin rights. Pass True for all boolean parameters to lift
745//restrictions from a user. Returns True on success.
746func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIResponse, error) {
747 v := url.Values{}
748
749 if config.SuperGroupUsername != "" {
750 v.Add("chat_id", config.SuperGroupUsername)
751 } else if config.ChannelUsername != "" {
752 v.Add("chat_id", config.ChannelUsername)
753 } else {
754 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
755 }
756 v.Add("user_id", strconv.Itoa(config.UserID))
757
758 if config.CanSendMessages != nil {
759 v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages))
760 }
761 if config.CanSendMediaMessages != nil {
762 v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages))
763 }
764 if config.CanSendOtherMessages != nil {
765 v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages))
766 }
767 if config.CanAddWebPagePreviews != nil {
768 v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews))
769 }
770 if config.UntilDate != 0 {
771 v.Add("until_date", strconv.FormatInt(config.UntilDate, 10))
772 }
773
774 bot.debugLog("restrictChatMember", v, nil)
775
776 return bot.MakeRequest("restrictChatMember", v)
777}
778
779// PromoteChatMember add admin rights to user
780func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) {
781 v := url.Values{}
782
783 if config.SuperGroupUsername != "" {
784 v.Add("chat_id", config.SuperGroupUsername)
785 } else if config.ChannelUsername != "" {
786 v.Add("chat_id", config.ChannelUsername)
787 } else {
788 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
789 }
790 v.Add("user_id", strconv.Itoa(config.UserID))
791
792 if config.CanChangeInfo != nil {
793 v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo))
794 }
795 if config.CanPostMessages != nil {
796 v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages))
797 }
798 if config.CanEditMessages != nil {
799 v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages))
800 }
801 if config.CanDeleteMessages != nil {
802 v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages))
803 }
804 if config.CanInviteUsers != nil {
805 v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers))
806 }
807 if config.CanRestrictMembers != nil {
808 v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers))
809 }
810 if config.CanPinMessages != nil {
811 v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages))
812 }
813 if config.CanPromoteMembers != nil {
814 v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers))
815 }
816
817 bot.debugLog("promoteChatMember", v, nil)
818
819 return bot.MakeRequest("promoteChatMember", v)
820}
821
822// GetGameHighScores allows you to get the high scores for a game.
823func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
824 v, _ := config.values()
825
826 resp, err := bot.MakeRequest(config.method(), v)
827 if err != nil {
828 return []GameHighScore{}, err
829 }
830
831 var highScores []GameHighScore
832 err = json.Unmarshal(resp.Result, &highScores)
833
834 return highScores, err
835}
836
837// AnswerShippingQuery allows you to reply to Update with shipping_query parameter.
838func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) {
839 v := url.Values{}
840
841 v.Add("shipping_query_id", config.ShippingQueryID)
842 v.Add("ok", strconv.FormatBool(config.OK))
843 if config.OK == true {
844 data, err := json.Marshal(config.ShippingOptions)
845 if err != nil {
846 return APIResponse{}, err
847 }
848 v.Add("shipping_options", string(data))
849 } else {
850 v.Add("error_message", config.ErrorMessage)
851 }
852
853 bot.debugLog("answerShippingQuery", v, nil)
854
855 return bot.MakeRequest("answerShippingQuery", v)
856}
857
858// AnswerPreCheckoutQuery allows you to reply to Update with pre_checkout_query.
859func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) {
860 v := url.Values{}
861
862 v.Add("pre_checkout_query_id", config.PreCheckoutQueryID)
863 v.Add("ok", strconv.FormatBool(config.OK))
864 if config.OK != true {
865 v.Add("error", config.ErrorMessage)
866 }
867
868 bot.debugLog("answerPreCheckoutQuery", v, nil)
869
870 return bot.MakeRequest("answerPreCheckoutQuery", v)
871}
872
873// DeleteMessage deletes a message in a chat
874func (bot *BotAPI) DeleteMessage(config DeleteMessageConfig) (APIResponse, error) {
875 v, err := config.values()
876 if err != nil {
877 return APIResponse{}, err
878 }
879
880 bot.debugLog(config.method(), v, nil)
881
882 return bot.MakeRequest(config.method(), v)
883}
884
885// GetInviteLink get InviteLink for a chat
886func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) {
887 v := url.Values{}
888
889 if config.SuperGroupUsername == "" {
890 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
891 } else {
892 v.Add("chat_id", config.SuperGroupUsername)
893 }
894
895 resp, err := bot.MakeRequest("exportChatInviteLink", v)
896 if err != nil {
897 return "", err
898 }
899
900 var inviteLink string
901 err = json.Unmarshal(resp.Result, &inviteLink)
902
903 return inviteLink, err
904}
905
906// PinChatMessage pin message in supergroup
907func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (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// UnpinChatMessage unpin message in supergroup
919func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (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// SetChatTitle change title of chat.
931func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (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// SetChatDescription change description of chat.
943func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) {
944 v, err := config.values()
945 if err != nil {
946 return APIResponse{}, err
947 }
948
949 bot.debugLog(config.method(), v, nil)
950
951 return bot.MakeRequest(config.method(), v)
952}
953
954// SetChatPhoto change photo of chat.
955func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) {
956 params, err := config.params()
957 if err != nil {
958 return APIResponse{}, err
959 }
960
961 file := config.getFile()
962
963 return bot.UploadFile(config.method(), params, config.name(), file)
964}
965
966// DeleteChatPhoto delete photo of chat.
967func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) {
968 v, err := config.values()
969 if err != nil {
970 return APIResponse{}, err
971 }
972
973 bot.debugLog(config.method(), v, nil)
974
975 return bot.MakeRequest(config.method(), v)
976}