all repos — telegram-bot-api @ b24a37443a9122cc263f3f82eaeb6b687d65db76

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