all repos — telegram-bot-api @ cf3ea3f80ddfd0879a35025ff146a2e1d5ea1046

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