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