all repos — telegram-bot-api @ 2476225ecc0df3aa8acbc3e577b02f487b92f5cc

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