all repos — telegram-bot-api @ d0711736ecd8b8ba32ff177eacf09d4b862ffaee

Golang bindings for the Telegram Bot API

bot.go (view raw)

  1// Package tgbotapi has bindings for interacting with the Telegram Bot API.
  2package tgbotapi
  3
  4import (
  5	"bytes"
  6	"encoding/json"
  7	"errors"
  8	"fmt"
  9	"github.com/technoweenie/multipartstreamer"
 10	"io/ioutil"
 11	"log"
 12	"net/http"
 13	"net/url"
 14	"os"
 15	"strconv"
 16	"time"
 17)
 18
 19// BotAPI has methods for interacting with all of Telegram's Bot API endpoints.
 20type BotAPI struct {
 21	Token   string       `json:"token"`
 22	Debug   bool         `json:"debug"`
 23	Self    User         `json:"-"`
 24	Updates chan Update  `json:"-"`
 25	Client  *http.Client `json:"-"`
 26}
 27
 28// NewBotAPI creates a new BotAPI instance.
 29// Requires a token, provided by @BotFather on Telegram
 30func NewBotAPI(token string) (*BotAPI, error) {
 31	return NewBotAPIWithClient(token, &http.Client{})
 32}
 33
 34// NewBotAPIWithClient creates a new BotAPI instance passing an http.Client.
 35// Requires a token, provided by @BotFather on Telegram
 36func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
 37	bot := &BotAPI{
 38		Token:  token,
 39		Client: client,
 40	}
 41
 42	self, err := bot.GetMe()
 43	if err != nil {
 44		return &BotAPI{}, err
 45	}
 46
 47	bot.Self = self
 48
 49	return bot, nil
 50}
 51
 52// MakeRequest makes a request to a specific endpoint with our token.
 53// All requests are POSTs because Telegram doesn't care, and it's easier.
 54func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
 55	resp, err := bot.Client.PostForm(fmt.Sprintf(APIEndpoint, bot.Token, endpoint), params)
 56	if err != nil {
 57		return APIResponse{}, err
 58	}
 59	defer resp.Body.Close()
 60
 61	if resp.StatusCode == http.StatusForbidden {
 62		return APIResponse{}, errors.New(APIForbidden)
 63	}
 64
 65	bytes, err := ioutil.ReadAll(resp.Body)
 66	if err != nil {
 67		return APIResponse{}, err
 68	}
 69
 70	if bot.Debug {
 71		log.Println(endpoint, string(bytes))
 72	}
 73
 74	var apiResp APIResponse
 75	json.Unmarshal(bytes, &apiResp)
 76
 77	if !apiResp.Ok {
 78		return APIResponse{}, errors.New(apiResp.Description)
 79	}
 80
 81	return apiResp, nil
 82}
 83
 84func (bot *BotAPI) MakeMessageRequest(endpoint string, params url.Values) (Message, error) {
 85	resp, err := bot.MakeRequest(endpoint, params)
 86	if err != nil {
 87		return Message{}, err
 88	}
 89
 90	var message Message
 91	json.Unmarshal(resp.Result, &message)
 92
 93	bot.debugLog(endpoint, params, message)
 94
 95	return message, nil
 96}
 97
 98// UploadFile makes a request to the API with a file.
 99//
100// Requires the parameter to hold the file not be in the params.
101// File should be a string to a file path, a FileBytes struct, or a FileReader struct.
102func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
103	ms := multipartstreamer.New()
104	ms.WriteFields(params)
105
106	switch f := file.(type) {
107	case string:
108		fileHandle, err := os.Open(f)
109		if err != nil {
110			return APIResponse{}, err
111		}
112		defer fileHandle.Close()
113
114		fi, err := os.Stat(f)
115		if err != nil {
116			return APIResponse{}, err
117		}
118
119		ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
120	case FileBytes:
121		buf := bytes.NewBuffer(f.Bytes)
122		ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
123	case FileReader:
124		if f.Size == -1 {
125			data, err := ioutil.ReadAll(f.Reader)
126			if err != nil {
127				return APIResponse{}, err
128			}
129			buf := bytes.NewBuffer(data)
130
131			ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
132
133			break
134		}
135
136		ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
137	default:
138		return APIResponse{}, errors.New("bad file type")
139	}
140
141	req, err := http.NewRequest("POST", fmt.Sprintf(APIEndpoint, bot.Token, endpoint), nil)
142	ms.SetupRequest(req)
143	if err != nil {
144		return APIResponse{}, err
145	}
146
147	res, err := bot.Client.Do(req)
148	if err != nil {
149		return APIResponse{}, err
150	}
151	defer res.Body.Close()
152
153	bytes, err := ioutil.ReadAll(res.Body)
154	if err != nil {
155		return APIResponse{}, err
156	}
157
158	if bot.Debug {
159		log.Println(string(bytes[:]))
160	}
161
162	var apiResp APIResponse
163	json.Unmarshal(bytes, &apiResp)
164
165	if !apiResp.Ok {
166		return APIResponse{}, errors.New(apiResp.Description)
167	}
168
169	return apiResp, nil
170}
171
172// GetMe fetches the currently authenticated bot.
173//
174// There are no parameters for this method.
175func (bot *BotAPI) GetMe() (User, error) {
176	resp, err := bot.MakeRequest("getMe", nil)
177	if err != nil {
178		return User{}, err
179	}
180
181	var user User
182	json.Unmarshal(resp.Result, &user)
183
184	if bot.Debug {
185		log.Printf("getMe: %+v\n", user)
186	}
187
188	return user, nil
189}
190
191func (bot *BotAPI) Send(c Chattable) (Message, error) {
192	switch c.(type) {
193	case Fileable:
194		return bot.sendFile(c.(Fileable))
195	default:
196		return bot.sendChattable(c)
197	}
198}
199
200func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
201	if bot.Debug {
202		log.Printf("%s req : %+v\n", context, v)
203		log.Printf("%s resp: %+v\n", context, message)
204	}
205}
206
207func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
208	v, err := config.Values()
209
210	if err != nil {
211		return Message{}, err
212	}
213
214	message, err := bot.MakeMessageRequest(method, v)
215	if err != nil {
216		return Message{}, err
217	}
218
219	return message, nil
220}
221
222func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
223	params, err := config.Params()
224	if err != nil {
225		return Message{}, err
226	}
227
228	file := config.GetFile()
229
230	resp, err := bot.UploadFile(method, params, config.Name(), file)
231	if err != nil {
232		return Message{}, err
233	}
234
235	var message Message
236	json.Unmarshal(resp.Result, &message)
237
238	if bot.Debug {
239		log.Printf("%s resp: %+v\n", method, message)
240	}
241
242	return message, nil
243}
244
245func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
246	if config.UseExistingFile() {
247		return bot.sendExisting(config.Method(), config)
248	}
249
250	return bot.uploadAndSend(config.Method(), config)
251}
252
253func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
254	v, err := config.Values()
255	if err != nil {
256		return Message{}, err
257	}
258
259	message, err := bot.MakeMessageRequest(config.Method(), v)
260
261	if err != nil {
262		return Message{}, err
263	}
264
265	return message, nil
266}
267
268// GetUserProfilePhotos gets a user's profile photos.
269//
270// Requires UserID.
271// Offset and Limit are optional.
272func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
273	v := url.Values{}
274	v.Add("user_id", strconv.Itoa(config.UserID))
275	if config.Offset != 0 {
276		v.Add("offset", strconv.Itoa(config.Offset))
277	}
278	if config.Limit != 0 {
279		v.Add("limit", strconv.Itoa(config.Limit))
280	}
281
282	resp, err := bot.MakeRequest("getUserProfilePhotos", v)
283	if err != nil {
284		return UserProfilePhotos{}, err
285	}
286
287	var profilePhotos UserProfilePhotos
288	json.Unmarshal(resp.Result, &profilePhotos)
289
290	bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
291
292	return profilePhotos, nil
293}
294
295// GetFile returns a file_id required to download a file.
296//
297// Requires FileID.
298func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
299	v := url.Values{}
300	v.Add("file_id", config.FileID)
301
302	resp, err := bot.MakeRequest("getFile", v)
303	if err != nil {
304		return File{}, err
305	}
306
307	var file File
308	json.Unmarshal(resp.Result, &file)
309
310	bot.debugLog("GetFile", v, file)
311
312	return file, nil
313}
314
315// GetUpdates fetches updates.
316// If a WebHook is set, this will not return any data!
317//
318// Offset, Limit, and Timeout are optional.
319// To not get old items, set Offset to one higher than the previous item.
320// Set Timeout to a large number to reduce requests and get responses instantly.
321func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
322	v := url.Values{}
323	if config.Offset > 0 {
324		v.Add("offset", strconv.Itoa(config.Offset))
325	}
326	if config.Limit > 0 {
327		v.Add("limit", strconv.Itoa(config.Limit))
328	}
329	if config.Timeout > 0 {
330		v.Add("timeout", strconv.Itoa(config.Timeout))
331	}
332
333	resp, err := bot.MakeRequest("getUpdates", v)
334	if err != nil {
335		return []Update{}, err
336	}
337
338	var updates []Update
339	json.Unmarshal(resp.Result, &updates)
340
341	if bot.Debug {
342		log.Printf("getUpdates: %+v\n", updates)
343	}
344
345	return updates, nil
346}
347
348// SetWebhook sets a webhook.
349// If this is set, GetUpdates will not get any data!
350//
351// Requires URL OR to set Clear to true.
352func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
353	if config.Certificate == nil {
354		v := url.Values{}
355		if !config.Clear {
356			v.Add("url", config.URL.String())
357		}
358
359		return bot.MakeRequest("setWebhook", v)
360	}
361
362	params := make(map[string]string)
363	params["url"] = config.URL.String()
364
365	resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
366	if err != nil {
367		return APIResponse{}, err
368	}
369
370	var apiResp APIResponse
371	json.Unmarshal(resp.Result, &apiResp)
372
373	if bot.Debug {
374		log.Printf("setWebhook resp: %+v\n", apiResp)
375	}
376
377	return apiResp, nil
378}
379
380// UpdatesChan starts a channel for getting updates.
381func (bot *BotAPI) UpdatesChan(config UpdateConfig) error {
382	bot.Updates = make(chan Update, 100)
383
384	go func() {
385		for {
386			updates, err := bot.GetUpdates(config)
387			if err != nil {
388				log.Println(err)
389				log.Println("Failed to get updates, retrying in 3 seconds...")
390				time.Sleep(time.Second * 3)
391
392				continue
393			}
394
395			for _, update := range updates {
396				if update.UpdateID >= config.Offset {
397					config.Offset = update.UpdateID + 1
398					bot.Updates <- update
399				}
400			}
401		}
402	}()
403
404	return nil
405}
406
407// ListenForWebhook registers a http handler for a webhook.
408func (bot *BotAPI) ListenForWebhook(pattern string) {
409	bot.Updates = make(chan Update, 100)
410
411	http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
412		bytes, _ := ioutil.ReadAll(r.Body)
413
414		var update Update
415		json.Unmarshal(bytes, &update)
416
417		bot.Updates <- update
418	})
419}
420
421// SendChatAction sets a current action in a chat.
422//
423// Requires ChatID and a valid Action (see Chat constants).
424func (bot *BotAPI) SendChatAction(config ChatActionConfig) error {
425	v, err := config.Values()
426	if err != nil {
427		return err
428	}
429
430	_, err = bot.MakeRequest("sendChatAction", v)
431	if err != nil {
432		return err
433	}
434
435	return nil
436}