all repos — telegram-bot-api @ d4b2e3c2136aa63ffce72c297c97a9c3e0a06cc8

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