all repos — telegram-bot-api @ 9105c34c59802cba482ee90cae261218971f634c

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