all repos — telegram-bot-api @ 7629a37f7708fa9a24c55fd490114922d026bdb3

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