all repos — telegram-bot-api @ 6b5102fab5586322d6fe98112fc671ad23dfae33

Golang bindings for the Telegram Bot API

bot.go (view raw)

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