all repos — telegram-bot-api @ 66446d51ffc393a94dc510f458de148ce903f028

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	var updatesCh updatesChannel = ch
455
456	go func() {
457		for {
458			updates, err := bot.GetUpdates(config)
459			if err != nil {
460				log.Println(err)
461				log.Println("Failed to get updates, retrying in 3 seconds...")
462				time.Sleep(time.Second * 3)
463
464				continue
465			}
466
467			for _, update := range updates {
468				if update.UpdateID >= config.Offset {
469					config.Offset = update.UpdateID + 1
470					ch <- update
471				}
472			}
473		}
474	}()
475
476	return updatesCh, nil
477}
478
479// ListenForWebhook registers a http handler for a webhook.
480func (bot *BotAPI) ListenForWebhook(pattern string) updatesChannel {
481	ch := make(chan Update, 100)
482	var updatesCh updatesChannel = ch
483
484	http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
485		bytes, _ := ioutil.ReadAll(r.Body)
486
487		var update Update
488		json.Unmarshal(bytes, &update)
489
490		ch <- update
491	})
492
493	return updatesCh
494}
495
496// AnswerInlineQuery sends a response to an inline query.
497//
498// Note that you must respond to an inline query within 30 seconds.
499func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) {
500	v := url.Values{}
501
502	v.Add("inline_query_id", config.InlineQueryID)
503	v.Add("cache_time", strconv.Itoa(config.CacheTime))
504	v.Add("is_personal", strconv.FormatBool(config.IsPersonal))
505	v.Add("next_offset", config.NextOffset)
506	data, err := json.Marshal(config.Results)
507	if err != nil {
508		return APIResponse{}, err
509	}
510	v.Add("results", string(data))
511	v.Add("switch_pm_text", config.SwitchPMText)
512	v.Add("switch_pm_parameter", config.SwitchPMParameter)
513
514	bot.debugLog("answerInlineQuery", v, nil)
515
516	return bot.MakeRequest("answerInlineQuery", v)
517}
518
519// AnswerCallbackQuery sends a response to an inline query callback.
520func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) {
521	v := url.Values{}
522
523	v.Add("callback_query_id", config.CallbackQueryID)
524	if config.Text != "" {
525		v.Add("text", config.Text)
526	}
527	v.Add("show_alert", strconv.FormatBool(config.ShowAlert))
528	if config.URL != "" {
529		v.Add("url", config.URL)
530	}
531	v.Add("cache_time", strconv.Itoa(config.CacheTime))
532
533	bot.debugLog("answerCallbackQuery", v, nil)
534
535	return bot.MakeRequest("answerCallbackQuery", v)
536}
537
538// KickChatMember kicks a user from a chat. Note that this only will work
539// in supergroups, and requires the bot to be an admin. Also note they
540// will be unable to rejoin until they are unbanned.
541func (bot *BotAPI) KickChatMember(config ChatMemberConfig) (APIResponse, error) {
542	v := url.Values{}
543
544	if config.SuperGroupUsername == "" {
545		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
546	} else {
547		v.Add("chat_id", config.SuperGroupUsername)
548	}
549	v.Add("user_id", strconv.Itoa(config.UserID))
550
551	bot.debugLog("kickChatMember", v, nil)
552
553	return bot.MakeRequest("kickChatMember", v)
554}
555
556// LeaveChat makes the bot leave the chat.
557func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) {
558	v := url.Values{}
559
560	if config.SuperGroupUsername == "" {
561		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
562	} else {
563		v.Add("chat_id", config.SuperGroupUsername)
564	}
565
566	bot.debugLog("leaveChat", v, nil)
567
568	return bot.MakeRequest("leaveChat", v)
569}
570
571// GetChat gets information about a chat.
572func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) {
573	v := url.Values{}
574
575	if config.SuperGroupUsername == "" {
576		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
577	} else {
578		v.Add("chat_id", config.SuperGroupUsername)
579	}
580
581	resp, err := bot.MakeRequest("getChat", v)
582	if err != nil {
583		return Chat{}, err
584	}
585
586	var chat Chat
587	err = json.Unmarshal(resp.Result, &chat)
588
589	bot.debugLog("getChat", v, chat)
590
591	return chat, err
592}
593
594// GetChatAdministrators gets a list of administrators in the chat.
595//
596// If none have been appointed, only the creator will be returned.
597// Bots are not shown, even if they are an administrator.
598func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
599	v := url.Values{}
600
601	if config.SuperGroupUsername == "" {
602		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
603	} else {
604		v.Add("chat_id", config.SuperGroupUsername)
605	}
606
607	resp, err := bot.MakeRequest("getChatAdministrators", v)
608	if err != nil {
609		return []ChatMember{}, err
610	}
611
612	var members []ChatMember
613	err = json.Unmarshal(resp.Result, &members)
614
615	bot.debugLog("getChatAdministrators", v, members)
616
617	return members, err
618}
619
620// GetChatMembersCount gets the number of users in a chat.
621func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, 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	resp, err := bot.MakeRequest("getChatMembersCount", v)
631	if err != nil {
632		return -1, err
633	}
634
635	var count int
636	err = json.Unmarshal(resp.Result, &count)
637
638	bot.debugLog("getChatMembersCount", v, count)
639
640	return count, err
641}
642
643// GetChatMember gets a specific chat member.
644func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
645	v := url.Values{}
646
647	if config.SuperGroupUsername == "" {
648		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
649	} else {
650		v.Add("chat_id", config.SuperGroupUsername)
651	}
652	v.Add("user_id", strconv.Itoa(config.UserID))
653
654	resp, err := bot.MakeRequest("getChatMember", v)
655	if err != nil {
656		return ChatMember{}, err
657	}
658
659	var member ChatMember
660	err = json.Unmarshal(resp.Result, &member)
661
662	bot.debugLog("getChatMember", v, member)
663
664	return member, err
665}
666
667// UnbanChatMember unbans a user from a chat. Note that this only will work
668// in supergroups, and requires the bot to be an admin.
669func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) {
670	v := url.Values{}
671
672	if config.SuperGroupUsername == "" {
673		v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
674	} else {
675		v.Add("chat_id", config.SuperGroupUsername)
676	}
677	v.Add("user_id", strconv.Itoa(config.UserID))
678
679	bot.debugLog("unbanChatMember", v, nil)
680
681	return bot.MakeRequest("unbanChatMember", v)
682}
683
684// GetGameHighScores allows you to get the high scores for a game.
685func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
686	v, _ := config.values()
687
688	resp, err := bot.MakeRequest(config.method(), v)
689	if err != nil {
690		return []GameHighScore{}, err
691	}
692
693	var highScores []GameHighScore
694	err = json.Unmarshal(resp.Result, &highScores)
695
696	return highScores, err
697}