all repos — telegram-bot-api @ f57724f783b167bf0352f706bbaf9d1642572361

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