all repos — telegram-bot-api @ 3763be308e2d0053ffe9369dbb9949f8ba59bd09

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	Self   User         `json:"-"`
 27	Client *http.Client `json:"-"`
 28}
 29
 30// NewBotAPI creates a new BotAPI instance.
 31//
 32// It requires a token, provided by @BotFather on Telegram.
 33func NewBotAPI(token string) (*BotAPI, error) {
 34	return NewBotAPIWithClient(token, &http.Client{})
 35}
 36
 37// NewBotAPIWithClient creates a new BotAPI instance
 38// and allows you to pass a http.Client.
 39//
 40// It requires a token, provided by @BotFather on Telegram.
 41func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
 42	bot := &BotAPI{
 43		Token:  token,
 44		Client: client,
 45	}
 46
 47	self, err := bot.GetMe()
 48	if err != nil {
 49		return &BotAPI{}, err
 50	}
 51
 52	bot.Self = self
 53
 54	return bot, nil
 55}
 56
 57// MakeRequest makes a request to a specific endpoint with our token.
 58func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
 59	method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
 60
 61	resp, err := bot.Client.PostForm(method, params)
 62	if err != nil {
 63		return APIResponse{}, err
 64	}
 65	defer resp.Body.Close()
 66
 67	if resp.StatusCode == http.StatusForbidden {
 68		return APIResponse{}, errors.New(ErrAPIForbidden)
 69	}
 70
 71	bytes, err := ioutil.ReadAll(resp.Body)
 72	if err != nil {
 73		return APIResponse{}, err
 74	}
 75
 76	if bot.Debug {
 77		log.Println(endpoint, string(bytes))
 78	}
 79
 80	var apiResp APIResponse
 81	json.Unmarshal(bytes, &apiResp)
 82
 83	if !apiResp.Ok {
 84		return APIResponse{}, errors.New(apiResp.Description)
 85	}
 86
 87	return apiResp, nil
 88}
 89
 90// makeMessageRequest makes a request to a method that returns a Message.
 91func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) {
 92	resp, err := bot.MakeRequest(endpoint, params)
 93	if err != nil {
 94		return Message{}, err
 95	}
 96
 97	var message Message
 98	json.Unmarshal(resp.Result, &message)
 99
100	bot.debugLog(endpoint, params, message)
101
102	return message, nil
103}
104
105// UploadFile makes a request to the API with a file.
106//
107// Requires the parameter to hold the file not be in the params.
108// File should be a string to a file path, a FileBytes struct,
109// a FileReader struct, or a url.URL.
110//
111// Note that if your FileReader has a size set to -1, it will read
112// the file into memory to calculate a size.
113func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
114	ms := multipartstreamer.New()
115
116	switch f := file.(type) {
117	case string:
118		ms.WriteFields(params)
119
120		fileHandle, err := os.Open(f)
121		if err != nil {
122			return APIResponse{}, err
123		}
124		defer fileHandle.Close()
125
126		fi, err := os.Stat(f)
127		if err != nil {
128			return APIResponse{}, err
129		}
130
131		ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
132	case FileBytes:
133		ms.WriteFields(params)
134
135		buf := bytes.NewBuffer(f.Bytes)
136		ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
137	case FileReader:
138		ms.WriteFields(params)
139
140		if f.Size != -1 {
141			ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
142
143			break
144		}
145
146		data, err := ioutil.ReadAll(f.Reader)
147		if err != nil {
148			return APIResponse{}, err
149		}
150
151		buf := bytes.NewBuffer(data)
152
153		ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
154	case url.URL:
155		params[fieldname] = f.String()
156
157		ms.WriteFields(params)
158	default:
159		return APIResponse{}, errors.New(ErrBadFileType)
160	}
161
162	method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
163
164	req, err := http.NewRequest("POST", method, nil)
165	if err != nil {
166		return APIResponse{}, err
167	}
168
169	ms.SetupRequest(req)
170
171	res, err := bot.Client.Do(req)
172	if err != nil {
173		return APIResponse{}, err
174	}
175	defer res.Body.Close()
176
177	bytes, err := ioutil.ReadAll(res.Body)
178	if err != nil {
179		return APIResponse{}, err
180	}
181
182	if bot.Debug {
183		log.Println(string(bytes))
184	}
185
186	var apiResp APIResponse
187	json.Unmarshal(bytes, &apiResp)
188
189	if !apiResp.Ok {
190		return APIResponse{}, errors.New(apiResp.Description)
191	}
192
193	return apiResp, nil
194}
195
196// GetFileDirectURL returns direct URL to file
197//
198// It requires the FileID.
199func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) {
200	file, err := bot.GetFile(FileConfig{fileID})
201
202	if err != nil {
203		return "", err
204	}
205
206	return file.Link(bot.Token), nil
207}
208
209// GetMe fetches the currently authenticated bot.
210//
211// This method is called upon creation to validate the token,
212// and so you may get this data from BotAPI.Self without the need for
213// another request.
214func (bot *BotAPI) GetMe() (User, error) {
215	resp, err := bot.MakeRequest("getMe", nil)
216	if err != nil {
217		return User{}, err
218	}
219
220	var user User
221	json.Unmarshal(resp.Result, &user)
222
223	bot.debugLog("getMe", nil, user)
224
225	return user, nil
226}
227
228// IsMessageToMe returns true if message directed to this bot.
229//
230// It requires the Message.
231func (bot *BotAPI) IsMessageToMe(message Message) bool {
232	return strings.Contains(message.Text, "@"+bot.Self.UserName)
233}
234
235// Send will send a Chattable item to Telegram.
236//
237// It requires the Chattable to send.
238func (bot *BotAPI) Send(c Chattable) (Message, error) {
239	switch c.(type) {
240	case Fileable:
241		return bot.sendFile(c.(Fileable))
242	default:
243		return bot.sendChattable(c)
244	}
245}
246
247// debugLog checks if the bot is currently running in debug mode, and if
248// so will display information about the request and response in the
249// debug log.
250func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
251	if bot.Debug {
252		log.Printf("%s req : %+v\n", context, v)
253		log.Printf("%s resp: %+v\n", context, message)
254	}
255}
256
257// sendExisting will send a Message with an existing file to Telegram.
258func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
259	v, err := config.values()
260
261	if err != nil {
262		return Message{}, err
263	}
264
265	message, err := bot.makeMessageRequest(method, v)
266	if err != nil {
267		return Message{}, err
268	}
269
270	return message, nil
271}
272
273// uploadAndSend will send a Message with a new file to Telegram.
274func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
275	params, err := config.params()
276	if err != nil {
277		return Message{}, err
278	}
279
280	file := config.getFile()
281
282	resp, err := bot.UploadFile(method, params, config.name(), file)
283	if err != nil {
284		return Message{}, err
285	}
286
287	var message Message
288	json.Unmarshal(resp.Result, &message)
289
290	bot.debugLog(method, nil, message)
291
292	return message, nil
293}
294
295// sendFile determines if the file is using an existing file or uploading
296// a new file, then sends it as needed.
297func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
298	if config.useExistingFile() {
299		return bot.sendExisting(config.method(), config)
300	}
301
302	return bot.uploadAndSend(config.method(), config)
303}
304
305// sendChattable sends a Chattable.
306func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
307	v, err := config.values()
308	if err != nil {
309		return Message{}, err
310	}
311
312	message, err := bot.makeMessageRequest(config.method(), v)
313
314	if err != nil {
315		return Message{}, err
316	}
317
318	return message, nil
319}
320
321// GetUserProfilePhotos gets a user's profile photos.
322//
323// It requires UserID.
324// Offset and Limit are optional.
325func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
326	v := url.Values{}
327	v.Add("user_id", strconv.Itoa(config.UserID))
328	if config.Offset != 0 {
329		v.Add("offset", strconv.Itoa(config.Offset))
330	}
331	if config.Limit != 0 {
332		v.Add("limit", strconv.Itoa(config.Limit))
333	}
334
335	resp, err := bot.MakeRequest("getUserProfilePhotos", v)
336	if err != nil {
337		return UserProfilePhotos{}, err
338	}
339
340	var profilePhotos UserProfilePhotos
341	json.Unmarshal(resp.Result, &profilePhotos)
342
343	bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
344
345	return profilePhotos, nil
346}
347
348// GetFile returns a File which can download a file from Telegram.
349//
350// Requires FileID.
351func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
352	v := url.Values{}
353	v.Add("file_id", config.FileID)
354
355	resp, err := bot.MakeRequest("getFile", v)
356	if err != nil {
357		return File{}, err
358	}
359
360	var file File
361	json.Unmarshal(resp.Result, &file)
362
363	bot.debugLog("GetFile", v, file)
364
365	return file, nil
366}
367
368// GetUpdates fetches updates.
369// If a WebHook is set, this will not return any data!
370//
371// Offset, Limit, and Timeout are optional.
372// To avoid stale items, set Offset to one higher than the previous item.
373// Set Timeout to a large number to reduce requests so you can get updates
374// instantly instead of having to wait between requests.
375func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
376	v := url.Values{}
377	if config.Offset != 0 {
378		v.Add("offset", strconv.Itoa(config.Offset))
379	}
380	if config.Limit > 0 {
381		v.Add("limit", strconv.Itoa(config.Limit))
382	}
383	if config.Timeout > 0 {
384		v.Add("timeout", strconv.Itoa(config.Timeout))
385	}
386
387	resp, err := bot.MakeRequest("getUpdates", v)
388	if err != nil {
389		return []Update{}, err
390	}
391
392	var updates []Update
393	json.Unmarshal(resp.Result, &updates)
394
395	bot.debugLog("getUpdates", v, updates)
396
397	return updates, nil
398}
399
400// RemoveWebhook unsets the webhook.
401func (bot *BotAPI) RemoveWebhook() (APIResponse, error) {
402	return bot.MakeRequest("setWebhook", url.Values{})
403}
404
405// SetWebhook sets a webhook.
406//
407// If this is set, GetUpdates will not get any data!
408//
409// If you do not have a legitimate TLS certificate, you need to include
410// your self signed certificate with the config.
411func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
412	if config.Certificate == nil {
413		v := url.Values{}
414		v.Add("url", config.URL.String())
415
416		return bot.MakeRequest("setWebhook", v)
417	}
418
419	params := make(map[string]string)
420	params["url"] = config.URL.String()
421
422	resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
423	if err != nil {
424		return APIResponse{}, err
425	}
426
427	var apiResp APIResponse
428	json.Unmarshal(resp.Result, &apiResp)
429
430	if bot.Debug {
431		log.Printf("setWebhook resp: %+v\n", apiResp)
432	}
433
434	return apiResp, nil
435}
436
437// GetWebhookInfo allows you to fetch information about a webhook and if
438// one currently is set, along with pending update count and error messages.
439func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) {
440	resp, err := bot.MakeRequest("getWebhookInfo", url.Values{})
441	if err != nil {
442		return WebhookInfo{}, err
443	}
444
445	var info WebhookInfo
446	err = json.Unmarshal(resp.Result, &info)
447
448	return info, err
449}
450
451// GetUpdatesChan starts and returns a channel for getting updates.
452func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (updatesChannel, error) {
453	ch := make(chan Update, 100)
454
455	go func() {
456		for {
457			updates, err := bot.GetUpdates(config)
458			if err != nil {
459				log.Println(err)
460				log.Println("Failed to get updates, retrying in 3 seconds...")
461				time.Sleep(time.Second * 3)
462
463				continue
464			}
465
466			for _, update := range updates {
467				if update.UpdateID >= config.Offset {
468					config.Offset = update.UpdateID + 1
469					ch <- update
470				}
471			}
472		}
473	}()
474
475	return ch, nil
476}
477
478// ListenForWebhook registers a http handler for a webhook.
479func (bot *BotAPI) ListenForWebhook(pattern string) updatesChannel {
480	ch := make(chan Update, 100)
481
482	http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
483		bytes, _ := ioutil.ReadAll(r.Body)
484
485		var update Update
486		json.Unmarshal(bytes, &update)
487
488		ch <- update
489	})
490
491	return ch
492}
493
494// AnswerInlineQuery sends a response to an inline query.
495//
496// Note that you must respond to an inline query within 30 seconds.
497func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) {
498	v := url.Values{}
499
500	v.Add("inline_query_id", config.InlineQueryID)
501	v.Add("cache_time", strconv.Itoa(config.CacheTime))
502	v.Add("is_personal", strconv.FormatBool(config.IsPersonal))
503	v.Add("next_offset", config.NextOffset)
504	data, err := json.Marshal(config.Results)
505	if err != nil {
506		return APIResponse{}, err
507	}
508	v.Add("results", string(data))
509	v.Add("switch_pm_text", config.SwitchPMText)
510	v.Add("switch_pm_parameter", config.SwitchPMParameter)
511
512	bot.debugLog("answerInlineQuery", v, nil)
513
514	return bot.MakeRequest("answerInlineQuery", v)
515}
516
517// AnswerCallbackQuery sends a response to an inline query callback.
518func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) {
519	v := url.Values{}
520
521	v.Add("callback_query_id", config.CallbackQueryID)
522	if config.Text != "" {
523		v.Add("text", config.Text)
524	}
525	v.Add("show_alert", strconv.FormatBool(config.ShowAlert))
526	if config.URL != "" {
527		v.Add("url", config.URL)
528	}
529	v.Add("cache_time", strconv.Itoa(config.CacheTime))
530
531	bot.debugLog("answerCallbackQuery", v, nil)
532
533	return bot.MakeRequest("answerCallbackQuery", v)
534}
535
536// KickChatMember kicks a user from a chat. Note that this only will work
537// in supergroups, and requires the bot to be an admin. Also note they
538// will be unable to rejoin until they are unbanned.
539func (bot *BotAPI) KickChatMember(config ChatMemberConfig) (APIResponse, error) {
540	v := url.Values{}
541
542	if config.SuperGroupUsername == "" {
543		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
544	} else {
545		v.Add("chat_id", config.SuperGroupUsername)
546	}
547	v.Add("user_id", strconv.Itoa(config.UserID))
548
549	bot.debugLog("kickChatMember", v, nil)
550
551	return bot.MakeRequest("kickChatMember", v)
552}
553
554// LeaveChat makes the bot leave the chat.
555func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) {
556	v := url.Values{}
557
558	if config.SuperGroupUsername == "" {
559		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
560	} else {
561		v.Add("chat_id", config.SuperGroupUsername)
562	}
563
564	bot.debugLog("leaveChat", v, nil)
565
566	return bot.MakeRequest("leaveChat", v)
567}
568
569// GetChat gets information about a chat.
570func (bot *BotAPI) GetChat(config ChatConfig) (Chat, 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	resp, err := bot.MakeRequest("getChat", v)
580	if err != nil {
581		return Chat{}, err
582	}
583
584	var chat Chat
585	err = json.Unmarshal(resp.Result, &chat)
586
587	bot.debugLog("getChat", v, chat)
588
589	return chat, err
590}
591
592// GetChatAdministrators gets a list of administrators in the chat.
593//
594// If none have been appointed, only the creator will be returned.
595// Bots are not shown, even if they are an administrator.
596func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
597	v := url.Values{}
598
599	if config.SuperGroupUsername == "" {
600		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
601	} else {
602		v.Add("chat_id", config.SuperGroupUsername)
603	}
604
605	resp, err := bot.MakeRequest("getChatAdministrators", v)
606	if err != nil {
607		return []ChatMember{}, err
608	}
609
610	var members []ChatMember
611	err = json.Unmarshal(resp.Result, &members)
612
613	bot.debugLog("getChatAdministrators", v, members)
614
615	return members, err
616}
617
618// GetChatMembersCount gets the number of users in a chat.
619func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) {
620	v := url.Values{}
621
622	if config.SuperGroupUsername == "" {
623		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
624	} else {
625		v.Add("chat_id", config.SuperGroupUsername)
626	}
627
628	resp, err := bot.MakeRequest("getChatMembersCount", v)
629	if err != nil {
630		return -1, err
631	}
632
633	var count int
634	err = json.Unmarshal(resp.Result, &count)
635
636	bot.debugLog("getChatMembersCount", v, count)
637
638	return count, err
639}
640
641// GetChatMember gets a specific chat member.
642func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
643	v := url.Values{}
644
645	if config.SuperGroupUsername == "" {
646		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
647	} else {
648		v.Add("chat_id", config.SuperGroupUsername)
649	}
650	v.Add("user_id", strconv.Itoa(config.UserID))
651
652	resp, err := bot.MakeRequest("getChatMember", v)
653	if err != nil {
654		return ChatMember{}, err
655	}
656
657	var member ChatMember
658	err = json.Unmarshal(resp.Result, &member)
659
660	bot.debugLog("getChatMember", v, member)
661
662	return member, err
663}
664
665// UnbanChatMember unbans a user from a chat. Note that this only will work
666// in supergroups, and requires the bot to be an admin.
667func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) {
668	v := url.Values{}
669
670	if config.SuperGroupUsername == "" {
671		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
672	} else {
673		v.Add("chat_id", config.SuperGroupUsername)
674	}
675	v.Add("user_id", strconv.Itoa(config.UserID))
676
677	bot.debugLog("unbanChatMember", v, nil)
678
679	return bot.MakeRequest("unbanChatMember", v)
680}
681
682// GetGameHighScores allows you to get the high scores for a game.
683func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
684	v, _ := config.values()
685
686	resp, err := bot.MakeRequest(config.method(), v)
687	if err != nil {
688		return []GameHighScore{}, err
689	}
690
691	var highScores []GameHighScore
692	err = json.Unmarshal(resp.Result, &highScores)
693
694	return highScores, err
695}