all repos — telegram-bot-api @ ac87082c555ae9cd9cc2b0b07cf904744cf5841d

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	"log"
 13	"net/http"
 14	"net/url"
 15	"os"
 16	"strconv"
 17	"strings"
 18	"time"
 19
 20	"github.com/technoweenie/multipartstreamer"
 21)
 22
 23// BotAPI allows you to interact with the Telegram Bot API.
 24type BotAPI struct {
 25	Token  string `json:"token"`
 26	Debug  bool   `json:"debug"`
 27	Buffer int    `json:"buffer"`
 28
 29	Self   User         `json:"-"`
 30	Client *http.Client `json:"-"`
 31}
 32
 33// NewBotAPI creates a new BotAPI instance.
 34//
 35// It requires a token, provided by @BotFather on Telegram.
 36func NewBotAPI(token string) (*BotAPI, error) {
 37	return NewBotAPIWithClient(token, &http.Client{})
 38}
 39
 40// NewBotAPIWithClient creates a new BotAPI instance
 41// and allows you to pass a http.Client.
 42//
 43// It requires a token, provided by @BotFather on Telegram.
 44func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
 45	bot := &BotAPI{
 46		Token:  token,
 47		Client: client,
 48		Buffer: 100,
 49	}
 50
 51	self, err := bot.GetMe()
 52	if err != nil {
 53		return nil, err
 54	}
 55
 56	bot.Self = self
 57
 58	return bot, nil
 59}
 60
 61// MakeRequest makes a request to a specific endpoint with our token.
 62func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
 63	method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
 64
 65	resp, err := bot.Client.PostForm(method, params)
 66	if err != nil {
 67		return APIResponse{}, err
 68	}
 69	defer resp.Body.Close()
 70
 71	var apiResp APIResponse
 72	bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp)
 73	if err != nil {
 74		return apiResp, err
 75	}
 76
 77	if bot.Debug {
 78		log.Printf("%s resp: %s", endpoint, bytes)
 79	}
 80
 81	if !apiResp.Ok {
 82		return apiResp, errors.New(apiResp.Description)
 83	}
 84
 85	return apiResp, nil
 86}
 87
 88// decodeAPIResponse decode response and return slice of bytes if debug enabled.
 89// If debug disabled, just decode http.Response.Body stream to APIResponse struct
 90// for efficient memory usage
 91func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) {
 92	if !bot.Debug {
 93		dec := json.NewDecoder(responseBody)
 94		err = dec.Decode(resp)
 95		return
 96	}
 97
 98	// if debug, read reponse body
 99	data, err := ioutil.ReadAll(responseBody)
100	if err != nil {
101		return
102	}
103
104	err = json.Unmarshal(data, resp)
105	if err != nil {
106		return
107	}
108
109	return data, 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	resp, err := bot.Request(c)
251	if err != nil {
252		return Message{}, err
253	}
254
255	var message Message
256	err = json.Unmarshal(resp.Result, &message)
257
258	return message, err
259}
260
261// Request makes a request to Telegram that returns an APIResponse, rather than
262// a Message.
263func (bot *BotAPI) Request(c Chattable) (APIResponse, error) {
264	switch t := c.(type) {
265	case Fileable:
266		if t.useExistingFile() {
267			v, err := t.values()
268			if err != nil {
269				return APIResponse{}, err
270			}
271
272			return bot.MakeRequest(t.method(), v)
273		}
274
275		p, err := t.params()
276		if err != nil {
277			return APIResponse{}, err
278		}
279
280		return bot.UploadFile(t.method(), p, t.name(), t.getFile())
281	default:
282		v, err := c.values()
283		if err != nil {
284			return APIResponse{}, err
285		}
286
287		return bot.MakeRequest(c.method(), v)
288	}
289}
290
291// debugLog checks if the bot is currently running in debug mode, and if
292// so will display information about the request and response in the
293// debug log.
294func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
295	if bot.Debug {
296		log.Printf("%s req : %+v\n", context, v)
297		log.Printf("%s resp: %+v\n", context, message)
298	}
299}
300
301// GetUserProfilePhotos gets a user's profile photos.
302//
303// It requires UserID.
304// Offset and Limit are optional.
305func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
306	v := url.Values{}
307	v.Add("user_id", strconv.Itoa(config.UserID))
308	if config.Offset != 0 {
309		v.Add("offset", strconv.Itoa(config.Offset))
310	}
311	if config.Limit != 0 {
312		v.Add("limit", strconv.Itoa(config.Limit))
313	}
314
315	resp, err := bot.MakeRequest("getUserProfilePhotos", v)
316	if err != nil {
317		return UserProfilePhotos{}, err
318	}
319
320	var profilePhotos UserProfilePhotos
321	json.Unmarshal(resp.Result, &profilePhotos)
322
323	bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
324
325	return profilePhotos, nil
326}
327
328// GetFile returns a File which can download a file from Telegram.
329//
330// Requires FileID.
331func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
332	v := url.Values{}
333	v.Add("file_id", config.FileID)
334
335	resp, err := bot.MakeRequest("getFile", v)
336	if err != nil {
337		return File{}, err
338	}
339
340	var file File
341	json.Unmarshal(resp.Result, &file)
342
343	bot.debugLog("GetFile", v, file)
344
345	return file, nil
346}
347
348// GetUpdates fetches updates.
349// If a WebHook is set, this will not return any data!
350//
351// Offset, Limit, and Timeout are optional.
352// To avoid stale items, set Offset to one higher than the previous item.
353// Set Timeout to a large number to reduce requests so you can get updates
354// instantly instead of having to wait between requests.
355func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
356	v := url.Values{}
357	if config.Offset != 0 {
358		v.Add("offset", strconv.Itoa(config.Offset))
359	}
360	if config.Limit > 0 {
361		v.Add("limit", strconv.Itoa(config.Limit))
362	}
363	if config.Timeout > 0 {
364		v.Add("timeout", strconv.Itoa(config.Timeout))
365	}
366
367	resp, err := bot.MakeRequest("getUpdates", v)
368	if err != nil {
369		return []Update{}, err
370	}
371
372	var updates []Update
373	json.Unmarshal(resp.Result, &updates)
374
375	bot.debugLog("getUpdates", v, updates)
376
377	return updates, nil
378}
379
380// GetWebhookInfo allows you to fetch information about a webhook and if
381// one currently is set, along with pending update count and error messages.
382func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) {
383	resp, err := bot.MakeRequest("getWebhookInfo", url.Values{})
384	if err != nil {
385		return WebhookInfo{}, err
386	}
387
388	var info WebhookInfo
389	err = json.Unmarshal(resp.Result, &info)
390
391	return info, err
392}
393
394// GetUpdatesChan starts and returns a channel for getting updates.
395func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) {
396	ch := make(chan Update, bot.Buffer)
397
398	go func() {
399		for {
400			updates, err := bot.GetUpdates(config)
401			if err != nil {
402				log.Println(err)
403				log.Println("Failed to get updates, retrying in 3 seconds...")
404				time.Sleep(time.Second * 3)
405
406				continue
407			}
408
409			for _, update := range updates {
410				if update.UpdateID >= config.Offset {
411					config.Offset = update.UpdateID + 1
412					ch <- update
413				}
414			}
415		}
416	}()
417
418	return ch, nil
419}
420
421// ListenForWebhook registers a http handler for a webhook.
422func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel {
423	ch := make(chan Update, bot.Buffer)
424
425	http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
426		bytes, _ := ioutil.ReadAll(r.Body)
427
428		var update Update
429		json.Unmarshal(bytes, &update)
430
431		ch <- update
432	})
433
434	return ch
435}
436
437// GetChat gets information about a chat.
438func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) {
439	v := url.Values{}
440
441	if config.SuperGroupUsername == "" {
442		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
443	} else {
444		v.Add("chat_id", config.SuperGroupUsername)
445	}
446
447	resp, err := bot.MakeRequest("getChat", v)
448	if err != nil {
449		return Chat{}, err
450	}
451
452	var chat Chat
453	err = json.Unmarshal(resp.Result, &chat)
454
455	bot.debugLog("getChat", v, chat)
456
457	return chat, err
458}
459
460// GetChatAdministrators gets a list of administrators in the chat.
461//
462// If none have been appointed, only the creator will be returned.
463// Bots are not shown, even if they are an administrator.
464func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
465	v := url.Values{}
466
467	if config.SuperGroupUsername == "" {
468		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
469	} else {
470		v.Add("chat_id", config.SuperGroupUsername)
471	}
472
473	resp, err := bot.MakeRequest("getChatAdministrators", v)
474	if err != nil {
475		return []ChatMember{}, err
476	}
477
478	var members []ChatMember
479	err = json.Unmarshal(resp.Result, &members)
480
481	bot.debugLog("getChatAdministrators", v, members)
482
483	return members, err
484}
485
486// GetChatMembersCount gets the number of users in a chat.
487func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) {
488	v := url.Values{}
489
490	if config.SuperGroupUsername == "" {
491		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
492	} else {
493		v.Add("chat_id", config.SuperGroupUsername)
494	}
495
496	resp, err := bot.MakeRequest("getChatMembersCount", v)
497	if err != nil {
498		return -1, err
499	}
500
501	var count int
502	err = json.Unmarshal(resp.Result, &count)
503
504	bot.debugLog("getChatMembersCount", v, count)
505
506	return count, err
507}
508
509// GetChatMember gets a specific chat member.
510func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
511	v := url.Values{}
512
513	if config.SuperGroupUsername == "" {
514		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
515	} else {
516		v.Add("chat_id", config.SuperGroupUsername)
517	}
518	v.Add("user_id", strconv.Itoa(config.UserID))
519
520	resp, err := bot.MakeRequest("getChatMember", v)
521	if err != nil {
522		return ChatMember{}, err
523	}
524
525	var member ChatMember
526	err = json.Unmarshal(resp.Result, &member)
527
528	bot.debugLog("getChatMember", v, member)
529
530	return member, err
531}
532
533// GetGameHighScores allows you to get the high scores for a game.
534func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
535	v, _ := config.values()
536
537	resp, err := bot.MakeRequest(config.method(), v)
538	if err != nil {
539		return []GameHighScore{}, err
540	}
541
542	var highScores []GameHighScore
543	err = json.Unmarshal(resp.Result, &highScores)
544
545	return highScores, err
546}
547
548// GetInviteLink get InviteLink for a chat
549func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) {
550	v := url.Values{}
551
552	if config.SuperGroupUsername == "" {
553		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
554	} else {
555		v.Add("chat_id", config.SuperGroupUsername)
556	}
557
558	resp, err := bot.MakeRequest("exportChatInviteLink", v)
559	if err != nil {
560		return "", err
561	}
562
563	var inviteLink string
564	err = json.Unmarshal(resp.Result, &inviteLink)
565
566	return inviteLink, err
567}
568
569// GetStickerSet returns a StickerSet.
570func (bot *BotAPI) GetStickerSet(config GetStickerSetConfig) (StickerSet, error) {
571	v, err := config.values()
572	if err != nil {
573		return StickerSet{}, nil
574	}
575
576	resp, err := bot.MakeRequest(config.method(), v)
577	if err != nil {
578		return StickerSet{}, nil
579	}
580
581	var stickers StickerSet
582	err = json.Unmarshal(resp.Result, &stickers)
583
584	return stickers, err
585}